Борьба за сохранение и восстановление модели тензорного потока MNIST. Я хотел бы сохранить эту модель, чтобы я мог взять значения веса / сверточные выходные слои и наложить их поверх исходных входных изображений и особенно изображения, которое нужно классифицировать.
Я использовал "https://www.tensorflow.org/guide/saved_model" в качестве ссылки, но не могу заставить его работать.
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(
"MNIST_data/",
one_hot=True)
# Init weights
def initialize_weights(shape):
init_random_dist = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(init_random_dist)
# Init bias
def initialize_bias(shape):
init_bias_vals = tf.constant(0.1, shape=shape) # all 0.1 initially
return tf.Variable(init_bias_vals)
# CONV2D
def conv_2d(x, W):
return tf.nn.conv2d(
x,
W,
strides=[
1,
1,
1,
1],
padding='SAME')
# Pooling
def max_pool_2(x):
return tf.nn.max_pool(
x, ksize=[
1, 2, 2, 1], strides=[
1, 2, 2, 1], padding='SAME')
# Convolution layer
def convolutional_layer(input_x, shape):
W = initialize_weights(shape)
b = initialize_bias([shape[3]])
return tf.nn.relu(conv_2d(input_x, W) + b)
# Normal layer
def normal_full_layer(input_layer, size):
input_size = int(input_layer.get_shape()[1])
W = initialize_weights([input_size, size])
b = initialize_bias([size])
return tf.matmul(input_layer, W) + b
# Placeholders
x = tf.placeholder(tf.float32, shape=[None, 784])
y_true = tf.placeholder(tf.float32, shape=[None, 10])
# Layers
x_image = tf.reshape(x, [-1, 28, 28, 1])
# Convolutional layers
convo_1 = convolutional_layer(x_image, shape=[5, 5, 1, 32])
convo_1_pooling = max_pool_2(convo_1)
convo_2 = convolutional_layer(
convo_1_pooling, shape=[
5, 5, 32, 64]) # 5 by 5 patch, 64 features
convo_2_pooling = max_pool_2(convo_2)
convo_2_flat = tf.reshape(convo_2_pooling, [-1, 7 * 7 * 64])
full_layer_one = tf.nn.relu(normal_full_layer(convo_2_flat, 1024))
y_pred = normal_full_layer(full_layer_one, 10)
# Loss function
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(
labels=y_true, logits=y_pred))
# Optimizer
lr = 0.001
optimizer = tf.train.AdamOptimizer(learning_rate=lr)
train = optimizer.minimize(cross_entropy)
init = tf.global_variables_initializer()
epochs = 100
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
for i in range(epochs):
batch_x, batch_y = mnist.train.next_batch(50)
sess.run(
train,
feed_dict={
x: batch_x,
y_true: batch_y})
# Save the variables to disk.
save_path = saver.save(sess, "/tmp/model.ckpt")
Это попытка сохранить, в настоящее время выдается предупреждение «Нет переменных для сохранения».
# delete the current graph
tf.reset_default_graph()
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
# Restore variables from disk.
saver.restore(sess, "/tmp/model.ckpt")