使用 Keras 訓練

Python 的 TensorFlow 入門

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

訓練與評估總覽

  1. 載入並清理資料
  2. 定義模型
  3. 訓練並驗證模型
  4. 評估模型
Python 的 TensorFlow 入門

如何訓練模型

# Import tensorflow
import tensorflow as tf

# Define a sequential model
model = tf.keras.Sequential()
# Define the hidden layer
model.add(tf.keras.layers.Dense(16, activation='relu', input_shape=(784,)))
# Define the output layer
model.add(tf.keras.layers.Dense(4, activation='softmax'))
Python 的 TensorFlow 入門

如何訓練模型

# Compile model
model.compile('adam', loss='categorical_crossentropy')
# Train model
model.fit(image_features, image_labels)
Python 的 TensorFlow 入門

fit() 作業

  • 必要引數
    • features
    • labels
  • 多個選用引數
    • batch_size
    • epochs
    • validation_split
Python 的 TensorFlow 入門

批次大小與 epochs

圖示說明資料集如何被切成多個批次,這些批次合起來等於 1 個 epoch。

Python 的 TensorFlow 入門

執行驗證

圖片顯示資料集被分成訓練與驗證樣本。

Python 的 TensorFlow 入門

執行驗證

# Train model with validation split
model.fit(features, labels, epochs=10, validation_split=0.20)
Python 的 TensorFlow 入門

執行驗證

圖片顯示 10 個 epochs 的訓練與驗證結果。

Python 的 TensorFlow 入門

變更評估指標

# Recomile the model with the accuracy metric
model.compile('adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Train model with validation split
model.fit(features, labels, epochs=10, validation_split=0.20)
Python 的 TensorFlow 入門

變更評估指標

圖片顯示 10 個 epochs 的訓練與驗證結果。

Python 的 TensorFlow 入門

evaluation() 作業

圖片顯示資料集被分成訓練、驗證與測試樣本。

# Evaluate the test set
model.evaluate(test)
Python 的 TensorFlow 入門

一起來練習吧!

Python 的 TensorFlow 入門

Preparing Video For Download...