赞
踩
前言:本博客讲的比较基础,只适合刚入坑的小伙伴们阅读。
一.加载好数据
读者可以自己加载好任意数据集,笔者这里使用的是mnist数据集。
- '''
- 制作人:追天一方
- 功能:keras模型的保存方法示例
- 笔者水平有限错误之处请包容
- '''
- import os
- import tensorflow as tf
- from tensorflow import keras
-
- #示例数据集是mnist,只使用前一千个示例
- (train_images,train_labels),(test_images,test_labels)=tf.keras.datasets.mnist.load_data()
-
- #选取前一千个并且预处理
- train_labels=train_labels[:1000]
- test_labels=test_labels[:1000]
- train_images=train_images[:1000].reshape(-1,28*28)/255.0
- test_images=test_images[:1000].reshape(-1,28*28)/255.0

二.创建一个模型。
笔者创建了一个简单的模型,读者也可以根据自己的需求创造模型。
- #定义一个模型
- def create_model():
- model=tf.keras.models.Sequential([
- keras.layers.Dense(512,activation='relu',input_shape=(784,)),
- keras.layers.Dropout(0.2),
- keras.layers.Dense(10)
- ])
-
- model.compile(optimizer='adam',
- loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
- metrics=[tf.metrics.SparseCategoricalAccuracy()])
- return model
-
- #实列化模型
- model=create_model()
- #查看模型结构和参数
- print(model.summary())

三.保存模型
keras可以通过tf.keras.callbacks.ModelCheckpoint创建回调函数,然后将回调传入model.fit()函数当中,就可以实现间隔一定的训练批次保存模型或者模型权重,将tf.keras.callbacks.ModelCheckpoint函数中的save_weights_only参数设置为True表示只保存权重,反之则会保存整个模型。笔者代码示例是保存模型权重,如下:
- checkpoint_path2=r'.\model_test\cp-{epoch:04d}.ckpt'
- checkpoint_dir2=os.path.dirname(checkpoint_path2)
-
- batch_size=32
-
- #创建五个批次保存一次模型参数的回调
- cp_callback2=tf.keras.callbacks.ModelCheckpoint(
- filepath=checkpoint_path2,
- verbose=1,
- save_weights_only=True,
- save_freq=5*batch_size)
-
- #实例化模型
- model=create_model()
-
-
- #使用checkpoint_path保存模型权重
- model.save_weights(checkpoint_path2.format(epoch=0))
-
- model.fit(train_images,train_labels,epochs=20,callbacks=[cp_callback2],
- validation_data=(test_images,test_labels),verbose=0)
-
- # latest=tf.train.latest_checkpoint(checkpoint_dir2)
-
- #加载模型评估
- model=create_model()
- #加载权重
-
- model.load_weights(r'.\model_test\cp-0020.ckpt')
-
- #评估模型
- loss,acc=model.evaluate(test_images,test_labels,verbose=2)
- print("准确率:{:5.2f}%".format(100*acc))

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。