大話Tensorflow2.0(二):全連接神經網絡結構

大話Tensorflow2.0(二):全連接神經網絡結構

第一個全連接神經網絡結構的代碼復現

通過代碼整個流程的理解,大致是建立了一個全連接的網絡神經結構,輸入的一個長度爲784的張量,網絡包含兩個隱藏層,每個隱藏層包含64個結點,最後的輸出層包含10個節點。

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

from tensorflow import keras
from tensorflow.keras import layers

# 定義輸入的是一個爲長度爲784的張量
inputs = keras.Input(shape=(784,), name='digits')
# 第1層包含64個節點,採用relu激活函數
x = layers.Dense(64, activation='relu', name='dense_1')(inputs)
# 第2層包含64個節點,採用relu激活函數
x = layers.Dense(64, activation='relu', name='dense_2')(x)
# 輸出層採用softmax函數進行處理,得到最終的預測結果
outputs = layers.Dense(10, activation='softmax', name='predictions')(x)
# 實例化模型
model = keras.Model(inputs=inputs, outputs=outputs)

# x_train y_train和 x_test y_test分別載入了 60,000 和 10,000 張大小爲 28*28 的手寫體數字圖片
# x爲輸入,y爲輸出
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# MNIST中的圖像默認爲uint8(0-255的數字)。以下代碼將其歸一化到0-1之間的浮點數
x_train = x_train.reshape(60000, 784).astype('float32') / 255
x_test = x_test.reshape(10000, 784).astype('float32') / 255
# 由於輸出經過softmax處理已經是0-1之間的浮點數,將其轉爲浮float32點數,統一浮點數
y_train = y_train.astype('float32')
y_test = y_test.astype('float32')

# 這裏相當於將訓練集分爲兩部分,一部分50000個用於訓練
# 一部分(10000個數據)被保留用於驗證
x_val = x_train[-10000:]
y_val = y_train[-10000:]
x_train = x_train[:-10000]
y_train = y_train[:-10000]

# 指定訓練配置(優化函數,損失函數,評估)
model.compile(optimizer=keras.optimizers.RMSprop(),  # Optimizer
              # Loss function to minimize
              loss=keras.losses.SparseCategoricalCrossentropy(),
              # List of metrics to monitor
              metrics=[keras.metrics.SparseCategoricalAccuracy()])

# 通過將數據切成大小爲64個批次,並反覆迭代來訓練整個數據集
print('開始導入數據,對創建的第一個模型進行訓練')
result = model.fit(x_train, y_train,
                   batch_size=64,
                   epochs=3,
                   # 在每次迭代中加入驗證集
                   validation_data=(x_val, y_val))

# history屬性能夠展現每次迭代(訓練集和驗證集)的交叉熵,以及準確率
print('\n result.history 字典內容 :', result.history)

# 使用訓練集對該函數模型進行評估,返回值的值爲交叉熵和準確率
print('\n 評估測試集的結果')
results = model.evaluate(x_test, y_test, batch_size=128)
print('測試集的交叉熵, 測試集的準確率:', results)

# 使用predict函數
# 根據測試集生成最後輸出層十個結點的預測概率
print('\n 經過模型訓練後,打印五個輸出概率的例子')
predictions = model.predict(x_test[:5])
print(predictions)
print('\n 樣例的形狀大小:', predictions.shape)
開始導入數據,對創建的第一個模型進行訓練
Train on 50000 samples, validate on 10000 samples
Epoch 1/3
50000/50000 [==============================] - 3s 61us/sample - loss: 0.3427 - sparse_categorical_accuracy: 0.9030 - val_loss: 0.1717 - val_sparse_categorical_accuracy: 0.9523
Epoch 2/3
50000/50000 [==============================] - 2s 48us/sample - loss: 0.1590 - sparse_categorical_accuracy: 0.9521 - val_loss: 0.1317 - val_sparse_categorical_accuracy: 0.9604
Epoch 3/3
50000/50000 [==============================] - 3s 61us/sample - loss: 0.1138 - sparse_categorical_accuracy: 0.9659 - val_loss: 0.1179 - val_sparse_categorical_accuracy: 0.9684

result.history 字典內容 : {'loss': [0.3426578821802139, 0.15900296208143233, 0.11379028077363967], 'sparse_categorical_accuracy': [0.90298, 0.95212, 0.96594], 'val_loss': [0.17171175315380097, 0.13174966387748718, 0.11790141086876392], 'val_sparse_categorical_accuracy': [0.9523, 0.9604, 0.9684]}

評估測試集的結果
0000/1 [=======================================]
試集的交叉熵, 測試集的準確率: [0.12084398788884282, 0.9635]

經過模型訓練後,打印五個輸出概率的例子
[[3.17133271e-07 2.01679086e-07 1.91767787e-04 8.21962079e-04
  1.81705997e-10 1.46002526e-06 7.39513561e-10 9.98966455e-01
  1.70740645e-06 1.61036896e-05]
 [1.10389031e-08 1.36430506e-04 9.99815166e-01 4.38110583e-05
  5.87256535e-13 1.62982772e-07 1.60874251e-07 2.57644578e-12
  4.31606895e-06 3.27467166e-13]
 [3.43061256e-05 9.73996937e-01 5.65588707e-03 1.16891600e-03
  8.60710279e-04 3.87584558e-04 2.77850602e-04 1.32217836e-02
  3.75740835e-03 6.38560799e-04]
 [9.99940038e-01 7.90213284e-10 2.84513317e-05 1.66102552e-07
  4.41276597e-08 2.12409418e-06 1.91769664e-06 1.08328541e-05
  2.55990198e-08 1.64497469e-05]
 [1.20625791e-05 7.93989301e-08 5.64708353e-05 3.75024320e-06
  9.80681360e-01 3.32376258e-05 1.15452185e-05 4.67143051e-04
  1.86698508e-05 1.87157020e-02]]

 樣例的形狀大小: (5, 10) 評估測試集的結果

後面的還沒復現,慢慢更新
參考資料
Tensorflow 深度學習算法原理與編程實戰
簡單粗暴 TensorFlow 2.0
Tensorflow官網

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