tensorflow保存模型的几种方法
tensorflow保存模型的几种方法_zmlovelx(帅得不敢出门 程序员群31843264)-CSDN博客
tensorflow中的检查点checkpoint详解(二)——以tensorflow1.x 的模型保存与恢复为主
tensorflow中的检查点checkpoint详解(二)——以tensorflow1.x 的模型保存与恢复为主_MIss-Y的博客-CSDN博客tensorflow模型保存(三)——tensorflow1.x版本的savedmodel格式的模型保存与加载
tensorflow模型保存(三)——tensorflow1.x版本的savedmodel格式的模型保存与加载_MIss-Y的博客-CSDN博客
https://zhuanlan.zhihu.com/p/113734249
https://github.com/tensorflow/docs/blob/master/site/en/r1/guide/saved_model.md
测试用例:
tensorflow/4_convolutions.ipynb at r1.12 · tensorflow/tensorflow · GitHub
例子中的数据
pickle_file = 'notMNIST.pickle'
从另外一个地方下载,是python2生成的
noob/notMNIST.pickle at master · StryxZilla/noob · GitHub
我修改了代码以适配python3
我环境是tensorflow2.3
训练,保存模型的代码:
from __future__ import print_function
import os
import cv2
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
# 通过python3读取python2的pickle
# https://stackoverflow.com/questions/50283123/python-3-pickle-load-from-python-2
# https://docs.python.org/3/library/pickle.html#pickle.load
# https://docs.python.org/3/library/pickle.html
save = pickle.load(f, fix_imports=True, encoding="latin1")
#save = pickle.load(f)
train_dataset = save['train_dataset']
train_labels = save['train_labels']
valid_dataset = save['valid_dataset']
valid_labels = save['valid_labels']
test_dataset = save['test_dataset']
test_labels = save['test_labels']
del save # hint to help gc free up memory
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)
image_size = 28
num_labels = 10
num_channels = 1 # grayscale
import numpy as np
def reformat(dataset, labels):
dataset = dataset.reshape((-1, image_size, image_size, num_channels)).astype(np.float32)
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
return dataset, labels
train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)
def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))/ predictions.shape[0])
batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
graph = tf.Graph()
with graph.as_default():
# Input data.
# 对输入层起个好名字
tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels), name='input_image')
tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels), name='input_label')
#tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels))
#tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
tf_valid_dataset = tf.constant(valid_dataset)
tf_test_dataset = tf.constant(test_dataset)
# Variables.
layer1_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.1))
layer1_biases = tf.Variable(tf.zeros([depth]))
layer2_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth, depth], stddev=0.1))
layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))
layer3_weights = tf.Variable(tf.truncated_normal([image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))
layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))
layer4_weights = tf.Variable(tf.truncated_normal([num_hidden, num_labels], stddev=0.1))
layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
# Model.
def model(data):
conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer1_biases)
conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer2_biases)
shape = hidden.get_shape().as_list()
reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
return tf.matmul(hidden, layer4_weights) + layer4_biases
# 对输出层起个好名字
#return tf.matmul(hidden, layer4_weights, name='output') + layer4_biases
# Training computation.
logits = model(tf_train_dataset)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))
# Optimizer.
optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)
# Predictions for the training, validation, and test data.
train_prediction = tf.nn.softmax(logits)
valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
test_prediction = tf.nn.softmax(model(tf_test_dataset))
num_steps = 301
with tf.Session(graph=graph) as session:
'''
模型保存方式1
tf.train.Saver()
https://blog.csdn.net/qq_27825451/article/details/105819752
https://blog.csdn.net/qq_27825451/article/details/105505033
https://blog.csdn.net/qq_27825451/article/details/105866464
https://zhuanlan.zhihu.com/p/113734249
https://github.com/tensorflow/docs/blob/master/site/en/r1/guide/saved_model.md
一定要在
graph = tf.Graph()之后使用该方法,不然会抛出异常
'''
saver = tf.train.Saver()
save_path_root = "/home/ninghua/深度学习/特征点检测/SuperPoint/superpoint/inference/result"
tf.global_variables_initializer().run()
print('Initialized')
for step in range(num_steps):
offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
batch_labels = train_labels[offset:(offset + batch_size), :]
feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
m_input = [tf_train_dataset, tf_train_labels]
m_output = logits
_, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)
if (step % 50 == 0):
print('Minibatch loss at step %d: %f' % (step, l))
print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))
print('Validation accuracy: %.1f%%' % accuracy(valid_prediction.eval(), valid_labels))
if step in [300, 600, 900]:
#save_path = saver.save(sess=session, save_path=os.path.join(save_path_root, "ynhmodel.ckpt"), global_step=step)
#网络只需要保存一个
save_path = saver.save(sess=session, save_path=os.path.join(save_path_root, "ynhmodel.ckpt"),
global_step=step,
write_meta_graph=False)
print("model has saved, saved in path: {}".format(save_path))
print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))
'''
模型保存方式2
'''
tf.train.write_graph(graph_or_graph_def=session.graph_def, logdir=os.path.join(save_path_root, "ynh_write_graph"),
name="mymodel.pb", as_text=False)
'''
模型保存方式3
'''
tf.saved_model.simple_save(session, os.path.join(save_path_root, "ynh_simple_save"),
inputs={"input_image:0": m_input[0], "input_label:0": m_input[1]}, outputs={"add_3:0": m_output})
'''
模型保存方式4 其实和3实现方式一模一样
'''
from tensorflow.python.saved_model import builder
from tensorflow.python.framework import ops
from tensorflow.python.saved_model import builder
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.saved_model import signature_def_utils
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.util.tf_export import tf_export
signature_def_map = {
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
signature_def_utils.predict_signature_def(inputs={"input_image:0": m_input[0], "input_label:0": m_input[1]},
outputs={"add_3:0": m_output})
}
builder = builder.SavedModelBuilder(os.path.join(save_path_root, "ynh_simple_save2"))
builder.add_meta_graph_and_variables(
session,
tags=[tag_constants.SERVING],
signature_def_map=signature_def_map,
assets_collection=ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS),
legacy_init_op=None,
clear_devices=True)
builder.save()
测试,打印网络参数,载入网络的代码:
from __future__ import print_function
import os
import cv2
import numpy as np
# 测试环境 tensorflow-2.3
# tensorflow 1.0
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# tensorflow 2.0
#import tensorflow as tf
save_path_root = "/home/ninghua/code/deepglint/HSR/hsr_tools/tensorflow_test/result"
save_path = os.path.join(save_path_root, "ynhmodel.ckpt-300")
'''
001
# 查看模型中所有的Tensor的数据,这里的默认的all_tensor=True
'''
from tensorflow.python.tools import inspect_checkpoint as chkp
chkp.print_tensors_in_checkpoint_file(save_path, tensor_name='', all_tensors=True)
#print(chkp.print_tensors_in_checkpoint_file(save_path, tensor_name='', all_tensors=True))
'''
002
# 查看其中的某一个张量,此时的all_tensors=False
'''
# 获取最后保存的一个checkpoint,返回的是最后一个checkpoint的文件路径
model_file = tf.train.latest_checkpoint(save_path_root)
print(model_file)
print(chkp.print_tensors_in_checkpoint_file(model_file, tensor_name="Variable_7", all_tensors=False))
with tf.Session() as sess:
#或者tf.global_variables_initializer().run()
sess.run(tf.global_variables_initializer())
# 通过meta文件,加载模型结构,返回的是一个saver对象
saver = tf.train.import_meta_graph(os.path.join(save_path_root, "ynhmodel.ckpt-300.meta"))
# 载入模型参数
saver.restore(sess, os.path.join(save_path_root, "ynhmodel.ckpt-300"))
# 获取当前图,为了后续训练时恢复变量
gragh = tf.get_default_graph()
# 得到当前图中所有变量的名称
tensor_name_list = [tensor.name for tensor in gragh.as_graph_def().node]
for k in tensor_name_list:
print(k)
# image_size = 28
# num_labels = 10
# num_channels = 1 # grayscale
# batch_size = 1
# patch_size = 5
# depth = 16
# num_hidden = 64
# graph = tf.Graph()
# with graph.as_default():
# # Input data.
# tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels))
# # Variables.
# layer1_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.1))
# layer1_biases = tf.Variable(tf.zeros([depth]))
# layer2_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth, depth], stddev=0.1))
# layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))
# layer3_weights = tf.Variable(tf.truncated_normal([image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))
# layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))
# layer4_weights = tf.Variable(tf.truncated_normal([num_hidden, num_labels], stddev=0.1))
# layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
# # Model.
# def model(data):
# conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
# hidden = tf.nn.relu(conv + layer1_biases)
# conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
# hidden = tf.nn.relu(conv + layer2_biases)
# shape = hidden.get_shape().as_list()
# reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
# hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
# return tf.matmul(hidden, layer4_weights) + layer4_biases
from six.moves import cPickle as pickle
pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
# 通过python3读取python2的pickle
# https://stackoverflow.com/questions/50283123/python-3-pickle-load-from-python-2
# https://docs.python.org/3/library/pickle.html#pickle.load
# https://docs.python.org/3/library/pickle.html
save = pickle.load(f, fix_imports=True, encoding="latin1")
#save = pickle.load(f)
train_dataset = save['train_dataset']
train_labels = save['train_labels']
valid_dataset = save['valid_dataset']
valid_labels = save['valid_labels']
test_dataset = save['test_dataset']
test_labels = save['test_labels']
del save # hint to help gc free up memory
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)
image_size = 28
num_labels = 10
num_channels = 1 # grayscale
import numpy as np
def reformat(dataset, labels):
dataset = dataset.reshape((-1, image_size, image_size, num_channels)).astype(np.float32)
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
return dataset, labels
train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)
with tf.Session() as sess:
#或者tf.global_variables_initializer().run()
sess.run(tf.global_variables_initializer())
# 通过meta文件,加载模型结构,返回的是一个saver对象
saver = tf.train.import_meta_graph(os.path.join(save_path_root, "ynhmodel.ckpt-300.meta"))
# 载入模型参数
saver.restore(sess, os.path.join(save_path_root, "ynhmodel.ckpt-300"))
# 获取当前图,为了后续训练时恢复变量
graph = tf.get_default_graph()
# 获取模型的输入名称
input_img_tensor = graph.get_tensor_by_name('model_input:0') #从模型中获取输入的那个节点
# 获取模型的输出名称
model_y = graph.get_tensor_by_name('Variable_7:0')
batch_data = train_dataset[0, :, :, :]
batch_labels = train_labels[0, :]
# 测试模型
result = sess.run(model_y, feed_dict={input_img_tensor: batch_data}) # 需要的就是模型预测值model_Y,这里存为result