python筆記

語法規則

  • 下列語法中的“if”、“elif”以及“else”要保持對齊。 相對於正文向外超出兩個空格。
    {
    if
    elif
    else
    }

  • 函數定義後面要加“:”

  • “引號” 代表字符串

np.random產生隨機數

import numpy as np
(1)浮點數
A = np.random.random(3)
# 產生[0,1]內的隨機浮點數
A1 = np.random.random((2,3))
# 在[0,1]內隨機產生2行3列的矩陣。
# 調用函數時,後面加“()”,括號內的數據纔是真正需要設置的。所以會出現重括號。
B = np.random.uniform(20,305)
# 在[20,30]之間產生5個隨機浮點數2)整數
D = np.random.randint(10,205)
# 在[10,20]之間產生5個隨機整數
E = np.random.permutation(10)
# 產生[0,9]的隨機順序的整數
E1 = np.random.permutation(10)[:3]
# 從[0,9]中選取3個隨機整數
E2 = np.random.permutation([9,3,4,2,8,6])
# 輸出所給數據的隨機順序3)在一定範圍內按順序生成數字
x = np.mgird[-1:1:complex(0,n)]
# 在[-1,1]內按從小到大的順序產生n個數字

列表(list)、元組(tuple)以及數組(array)

  • array [1,2,3].shape (3L,)
  • array [[1,2,3]].shape (1L,3L)
  • array [[1],[2],[3]].shape (3L,1L)
  • array [1,2,3].reshape(3,1).shape (3L,1L)
  • tuple:代表元組 numpy.ndarray:numpy中的n維元組
  • list 沒有shape或者reshape等屬性,數組(array)操作更加方便,array輸出爲list的形式。
  • list定義利用’[]’,tuple定義利用’()’

pca類的理解

  • pca類有parameters和attributes,調用pca類的attributes時不需要加參數,例:pca.components_.reshape ,但在調用pca類中的其他函數時需要加參數,例:pca.fit(X)。根據需求制定。

zip函數

 zip函數舉例:
 a = [1,2,3]
 b = [4,5,6]
 print zip(a,b)
 [(1, 4), (2, 5), (3, 6)]

plot畫圖的一般流程

  • plt.figure()
  • plt.xlabel('') 橫座標
  • plt.ylabel('') 縱座標
  • plt.legend(loc = 'lower right') 顯示圖中各線條意義
    # 畫出各線段所表示的含義(每條曲線表示的意義)
  • plt.title(title) 標題
  • plt.show() 顯示圖片

實例如下:

plt.figure()
    plt.plot(n_components, pca_scores, 'b', label = 'PCA scores')
    plt.plot(n_components, fa_scores, 'r', label = 'FA scores')
    #plt.axvline and plt.axhline 分別是豎直劃線和水平劃線的含義
    plt.axvline(rank, color='g', label='TRUTH:%d' %rank, linestyle='-')
    plt.axvline(n_components_pca, color = 'b',
                label = 'PCA CV:%d' % n_components_pca,linestyle='--')
    plt.axvline(n_components_fa, color = 'r',
                label='FactorAnalysis CV:%d' % n_components_fa,
                linestyle='--')
    plt.axvline(n_components_pca_mle, color='k',
                label='PCA MLE:%d' % n_components_pca_mle,linestyle='--')

    #compare with other covariance estimators
    plt.axhline(shrunk_cov_score(X), color='violet',
                label='Shrunk Covariance MLE', linestyle='-.')

    plt.axhline(lw_score(X), color='orange',
                label='LedoitWolf MLE' % n_components_pca_mle, linestyle='-.')

    plt.xlabel('nb of components')
    plt.ylabel('CV scores')
    plt.legend(loc = 'lower right')
    # 畫出各線段所表示的含義(每條曲線表示的意義)
    plt.title(title)
    plt.show()

range、np.arange以及xrange區別

  • range多用作循環,range(0,10)返回一個list對象
print range(3)  [0, 1, 2]
print range(1,4)  [1, 2]

for i in range(n_row * n_col):
        plt.subplot(n_row, n_col, i+1) # 在每個區域畫圖
  • arange是numpy模塊中的函數,使用前需要先導入此模塊,arange(3):返回array類型對象。
    【注:range()中的步長不能爲小數,但是np.arange()中的步長可以爲小數】
n_components = np.arange(0, n_features, 5)  
# n_components   array ([0,5,10,15,...,45]) 
  • xrange()也是用作循環,只是xrang(0,10)不返回list,返回xrange對象。每次調用返回其中的一個值。
    返回很大的數的時候或者頻繁的需要break時候,xrange性能更好。

【注意:python3.x中把xrange()取消了】

time計時函數

import time as time
t0 = time()
#中間加需要計算時間的代碼內容
print time()-t0

reshape函數

faces_centered -= faces_centered.mean(axis=1).reshape(n_samples, -1)
#  faces_centered.mean(axis = 1) 按列求平均值,得到一列
# reshape.(n_samples, -1) 中的‘-1’表示由實際情況而定,不具體指定是多少

enumerate函數
用於遍歷(images)中的索引以及值(下標以及數據)

seq = ['one','two','three']
for i ,j in enumerate(seq):
    print i,j
output:
0   one
1   two
2   three

for i, comp in enumerate(images):
    # enumerate 用於遍歷images中的index以及value
    # i用於存儲索引(index),comp用於存儲值(value)
    plt.subplot(n_row, n_col, i + 1)

fetch_lfw_people獲取人臉數據集各參數作用

# 獲取人臉數據集
lfw_people = fetch_lfw_people(min_faces_per_person = 70, resize = 0.4)
# print lfw_people 函數把符合條件的照片專爲一個(n_samples,n_features)的矩陣
# fetch_lfw_people 函數用於提取lfw(人臉數據集)數據集中的數據
# min_face_per_person 保留文件夾中照片數大於70的人臉數據集
# Each row corresponds to a ravelled face image of original size 62*47 pixels
# 每一行對應一個原始尺寸爲62*47像素的臉部圖像,默認resize爲0.5,如果變爲0.4後,size爲50*37
n_samples, h, w, = lfw_people.images.shape
# n_samples = 1288, h = 50, w = 37
# 挑選了1288張人臉,其中每個人的人臉照片都超過70張,picture.shape()=50*37

random_state = 42,代表每次產生相同的隨機分組

# split train and test data
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size = 0.25, random_state = 42)
# 利用train_test_split函數將數據分爲訓練集和測試集
# random_state 代表是隨機數的種子,填寫數字,代表每次產生相同的隨機數組。
# 數字爲0或者不填,每次產生的隨機數組都不同 

%d、%s以及%.3f

print('Extracting the top %d eigenfaces from %d faces' 
        %(n_components, X_train.shape[0]))
print'predicted: %s\ntrue:     %s' %(pred_name, true_name))
print("done in %0.3fs" % train_time)

rsplit函數用法

def title(y_pred, y_test, target_names, i):
    # 返回預測人臉姓和測試人臉姓的對比title
    pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
    # rsplit('',1) 從右邊開始,以右邊第一個空格爲分界,分成兩個字符
    #組成一個list
    # 此處代表把'姓'和'名'分開,然後把後面的'姓'提取出來
    # 末尾加[-1]代表引用分割後的列表的最後一個元素
    true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
    return 'predicted: %s\ntrue:     %s' %(pred_name, true_name)

np.logspace(-2, 0, 30)

shrinkages = np.logspace(-2, 0, 30)
# [-2,0]中挑選30個點,然後取以10爲底的對數,
# x = np.random.uniform(-2,0,30), shrinkages = log(10)(x) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章