训练并评估用函数式API创建的模型,跟顺序模型的训练和评估基本一致:
- 载入并预处理数据
- 用compile方法配置模型:loss/optimizer/metrics
- 用fit方法训练模型,实现模型"适配"数据,返回训练损失值和指标值的记录
- 用evaluate方法在测试数据集上测试模型,返回 list:[loss, metrics]
完整范例代码如下所示:
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow import keras
# 创建层,将上一层传递进当前层
input = keras.Input(shape=(784,))
dense = layers.Dense(64,activation='relu')
x1 = dense(input)
x2 = layers.Dense(32, activation='relu')(x1)
output = layers.Dense(10)(x2)
# 通过输入\输出创建模型
model = keras.Model(inputs=input, outputs=output, name="Alex_Model")
# 查看模型摘要
model.summary()
# 载入并预处理数据
(x_train, y_train),(x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000,-1).astype("float32")/255.0
x_test = x_test.reshape(10000,-1).astype("float32")/255.0
# 用compile方法配置模型:loss/optimizer/metrics
model.compile(optimizer="rmsprop", loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=["accuracy"])
# 用fit方法训练模型,实现模型"适配"数据,返回训练损失值和指标值的记录
history = model.fit(x_train,y_train, batch_size=64, epochs=3, validation_split=0.2)
print(history.history.keys()) # dict_keys(['loss', 'accuracy', 'val_loss', 'val_accuracy'])
# 用evaluate方法在测试数据集上测试模型,返回 list:[loss, metrics]
test_scores = model.evaluate(x_test, y_test, verbose=2)
print("Test loss:", test_scores[0])
print("Test accuracy:", test_scores[1])
网友评论