DL(一)——吳恩達神經網絡與深度學習第二週課程作業記錄

參考文章:
https://blog.csdn.net/u013733326/article/details/79639509
https://www.cnblogs.com/chay/articles/10575174.html
https://www.imooc.com/article/69514

讀取數據集

def load_dataset():
    train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
    train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
    train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels

    test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
    test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
    test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels

    classes = np.array(test_dataset["list_classes"][:]) # the list of classes
    
    train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
    test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
    
    return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes

數據預處理

#導入數據,“_orig”代表這裏是原始數據,我們還要進一步處理才能使用
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()#由數據集獲取一些基本參數
#其中train_set_y爲訓練集中的標籤數組
m_train = train_set_x_orig.shape[0]  #訓練集大小209
m_test = test_set_x_orig.shape[0]    #測試集大小50
num_px = train_set_x_orig.shape[1]  #圖片寬度64,大小是64×64
#將圖片數據向量化(扁平化)
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T
#T表示轉置,-1表示剩餘元素除了逗號前面的進行扁平化
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T
#對數據進行標準化
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.

說明:

  1. train_set_x_orig:是原始數據的形狀(209, 64, 64, 3),第一維代表m,即樣本數量,第二維第三維分別是圖片的長和寬,第四維代表圖片的RGB三個通道。

  2. .shape可以獲取一個矩陣的形狀,可通過[i]來知道每一維的大小;
    .reshape()用來重構矩陣的形狀,直接在裏面填寫維度即可
    此處的特殊用法:當要把一個向量X(m,a,b,c)這個四維向量扁平化成X_flatten(m,a* b* c)的二維向量,可以寫X_flatten=X.reshape(X.shape[0],-1)即可,其中“-1”代表把剩餘維度壓扁的模式。而代碼中還有一個.T,代表轉置,因爲我們希望把訓練樣本壓縮成(64* 64 *3,m)的形式。

  3. 經過標準化(也稱歸一化)之後,等高線就變規矩了,就很容易梯度下降了。另外,對於圖片數據的話,進行標準化很簡單,因爲RGB三個通道的範圍都是255,我們對圖片的處理就是直接除以255即可。

後面的步驟比較簡單,閱讀代碼就可以瞭解怎麼實現

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章