Python進行深度學習—邏輯迴歸

第一步,讀取數據。
from tensorflow.examples.tutorials.mnist import input_data data = input_data.read_data_sets('data/MNIST/',one_hot = False) 
第二步,設置訓練集和測試集。
# 獲取訓練集和測試集 X0 = data.train.images Y0 = data.train.labels X1 = data.validation.images Y1 = data.validation.labels # 查看訓練集 print(X0.shape) 
第三步,可視化部分數據。
from matplotlib import pyplot as plt plt.figure() fig, ax = plt.subplots(2,5) ax = ax.flatten() for i in range(10): # 獲取 Y == i 的 X0 的第一個樣本,並轉換爲28 * 28的矩陣 Im = X0[Y0 == i][0].reshape(28,28) ax[i].imshow(Im) plt.show() 
第四步,轉化Y變量形式。
# 轉換爲 one-hot 型因變量 import tensorflow as tf from keras.utils import to_categorical YY0 = to_categorical(Y0) YY1 = to_categorical(Y1) 
第五步,構建模型。
from keras.layers import Activation, Dense, Flatten, Input from keras import Model input_shape = (784, ) input_layer = Input(input_shape) x = input_layer x = Dense(10)(x) x = Activation('softmax')(x) output_layer = x model = Model(input_layer, output_layer) model.summary() 
第六步,擬合模型,得到模型參數。
from keras.optimizers import Adam # 設置模型參數 model.compile(optimizer = Adam(0.01), loss = 'categorical_crossentropy', metrics = ['accuracy']) # 擬合模型 model.fit(X0,YY0, validation_data = (X1, YY1), batch_size = 100, epochs = 10) 
發佈了51 篇原創文章 · 獲贊 54 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章