使用 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 入门

批量大小与 epoch

该图展示如何将数据集划分为批次,所有批次合起来构成一个 epoch。

Python 中的 TensorFlow 入门

执行验证

图示将数据集划分为训练集和验证集。

Python 中的 TensorFlow 入门

执行验证

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

执行验证

图示 10 个 epoch 的训练与验证结果。

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 个 epoch 的训练与验证结果。

Python 中的 TensorFlow 入门

evaluation() 操作

图示将数据集划分为训练集、验证集和测试集。

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

Vamos praticar!

Python 中的 TensorFlow 入门

Preparing Video For Download...