TensorFlow训练模型的时候,我们习惯把训练的模型,保存下来。不然谁想把自己训练了几天的模型,每次都重新开始训练。但是在加载自己已经训练好的模型,容易出现以下的问题提示,看了下其他博客的解决方案,并没有解决:
Traceback (most recent call last):
File "D:\研究生资料\tensorflow\未命名0.py", line 10, in <module>
new_model =tf.keras.models.load_model('D:\研究生资料\tensorflow\tf_cnn_model')
File "D:\Program Files (x86)\ANACONDA\lib\site-packages\tensorflow\python\keras\saving\save.py", line 146, in load_model
return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
File "D:\Program Files (x86)\ANACONDA\lib\site-packages\tensorflow\python\keras\saving\hdf5_format.py", line 200, in load_model_from_hdf5
f = h5py.File(filepath, mode='r')
File "D:\Program Files (x86)\ANACONDA\lib\site-packages\h5py\_hl\files.py", line 408, in __init__
swmr=swmr)
File "D:\Program Files (x86)\ANACONDA\lib\site-packages\h5py\_hl\files.py", line 173, in make_fid
fid = h5f.open(name, flags, fapl=fapl)
File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py\h5f.pyx", line 88, in h5py.h5f.open
OSError
runfile('D:/研究生资料/tensorflow/未命名0.py', wdir='D:/研究生资料/tensorflow')
Traceback (most recent call last):
File "D:\研究生资料\tensorflow\未命名0.py", line 10, in <module>
new_model =tf.keras.models.load_model('D:\研究生资料\tensorflow\tf_cnn_model\cp.hdf5')
File "D:\Program Files (x86)\ANACONDA\lib\site-packages\tensorflow\python\keras\saving\save.py", line 146, in load_model
return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
File "D:\Program Files (x86)\ANACONDA\lib\site-packages\tensorflow\python\keras\saving\hdf5_format.py", line 200, in load_model_from_hdf5
f = h5py.File(filepath, mode='r')
File "D:\Program Files (x86)\ANACONDA\lib\site-packages\h5py\_hl\files.py", line 408, in __init__
swmr=swmr)
File "D:\Program Files (x86)\ANACONDA\lib\site-packages\h5py\_hl\files.py", line 173, in make_fid
fid = h5f.open(name, flags, fapl=fapl)
File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py\h5f.pyx", line 88, in h5py.h5f.open
OSError
如果你使用的函数模型保存格式没错(一般是:hdf5),文件没有出错的话,那么就是你的路径格式不对。
比如说你写成:
new_model =tf.keras.models.load_model('D:\研究生资料\tensorflow\tf_cnn_model\cp.hdf5')
就需要改成:
new_model =tf.keras.models.load_model('D:/研究生资料/tensorflow/tf_cnn_model/cp.hdf5')
然后我的模型就成功加载进来了,并运行成功的:
10000/10000 [==============================] - 4s 418us/sample - loss: 0.0430 - acc: 0.9864
在这里补充一下,这里我是这样储存模型的,保存文件格式为:hdf5),这里不能把文件格式改为:cpt
#把最有最优算的参数
check_path = 'D:/研究生资料/tensorflow/tf_cnn_model/cp.hdf5'
# period 每隔5epoch保存一次
save_model_cb = tf.keras.callbacks.ModelCheckpoint(
check_path, save_weights_only=False, verbose=1, period=1)
补充一下,大家如果有兴趣可以看一下加载模型的完整代码:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('D:\Program Files (x86)\ANACONDA\Minist_data', one_hot = False)
new_model =tf.keras.models.load_model('D:/研究生资料/tensorflow/tf_cnn_model/cp.hdf5')
new_model.evaluate(mnist.test.images.reshape(10000,28,28,1)
, mnist.test.labels)
训练模型的完整代码:
import tensorflow as tf
from tensorflow.keras import layers ,models
from tensorflow.examples.tutorials.mnist import input_data
#读取模型
mnist = input_data.read_data_sets('D:\Program Files (x86)\ANACONDA\Minist_data', one_hot = False)
#创建网络
model = models.Sequential()
#第一个卷积层 28x28x1 change to 24x24x32
model.add(layers.Conv2D(32,kernel_size = [5,5],activation='relu',input_shape=(28,28,1)))
#第一个池化层层24x24x32 change to 12x12x32
model.add(layers.MaxPooling2D([2,2]))
#第二个卷积层 12x12x32 change to 8x8x64
model.add(layers.Conv2D(64,kernel_size = [5,5],activation='relu'))
#第二个池化层 8x8x64 change to 4x4x64
model.add(layers.MaxPooling2D([2,2]))
#全连接层 4*4*64(每一个特征图4*4,共有64个),变化成一行4*4*64,便于全连接
model.add(layers.Flatten())
#这个就是全连接层的计算 [1,4x4x64] change to [1, 1024]
model.add(layers.Dense(1024,activation = 'relu'))
model.add(layers.Dense(10, activation = 'softmax'))
# [1,1024] change to [1, 10]
model.summary()
#把最有最优算的参数
check_path = 'D:/研究生资料/tensorflow/tf_cnn_model/cp.hdf5'
# period 每隔5epoch保存一次
save_model_cb = tf.keras.callbacks.ModelCheckpoint(
check_path, save_weights_only=False, verbose=1, period=1)
#设置模型的优化类型
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
#填充数据,总共循环10次
model.fit(mnist.train.images.reshape((55000,28,28,1)),mnist.train.labels, epochs = 10, callbacks = [save_model_cb])
#根据算的权值,计算准确率
test_loss, test_acc = model.evaluate(mnist.test.images.reshape(10000,28,28,1)
, mnist.test.labels)
print('\n')
print('测试集的准确率:')
print("准确率: %.4f,共测试了%d张图片 " % (test_acc,len(mnist.test.images)))
#初始化
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)