tesnorflow2.0模型的加载训练和保存

import tensorflow as tf
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
# matplotlib inline
(train_image, train_label),(test_image,test_label)=tf.keras.datasets.fashion_mnist.load_data()
train_image = train_image/255
test_image = test_image/255


model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))
model.summary()

model.compile(optimizer='adam',
             loss='sparse_categorical_crossentropy',
             metrics=['acc','mse'])
model.fit(train_image, train_label, verbose=2,epochs=2,validation_split=0.3)


model.evaluate(test_image, test_label, verbose=2)

# 保存模型
model.save('my_model.h5')


# 加载模型
new_model = tf.keras.models.load_model('my_model.h5')
# 查看模型配置
new_model.summary()



# 保存路径
checkpoint_path = 'cp.ckpt'
# 定义回调函数,可以查看里面的参数说明,这里仅保存权重
cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
                                                 save_weights_only=True)
model_cp = tf.keras.Sequential()
model_cp.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model_cp.add(tf.keras.layers.Dense(128, activation='relu'))
model_cp.add(tf.keras.layers.Dense(10, activation='softmax'))
model_cp.compile(optimizer='adam',
                 loss='sparse_categorical_crossentropy',
                 metrics=['acc'])
model_cp.fit(train_image, train_label, verbose=2,epochs=3, callbacks=[cp_callback],validation_split=0.3)
model.evaluate(test_image, test_label, verbose=2)

你可能感兴趣的:(tesnorflow2.0模型的加载训练和保存)