如何保存和使用tensorflow minist模型

时间:2016-10-13 10:38:57

标签: tensorflow

我使用tensorflow来训练一个minist模型并保存它。但我不使用它。 这是火车和保存模型的代码

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data_2/", one_hot=True)
print("Download Done!")

x = tf.placeholder(tf.float32, [None, 784])

# paras
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])

# loss func
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

# init
init = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init)

# train 
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

print("Accuarcy on Test-dataset: ", sess.run(accuracy, feed_dict={x:        mnist.test.images, y_: mnist.test.labels}))

# save model 
saver = tf.train.Saver()
save_path = saver.save(sess, "./model/minist_softmax.ckpt")
print("Model saved in file: ", save_path)

这是恢复模式的代码

# -*- coding: UTF-8 -*-  
from PIL import Image
from numpy import *
import tensorflow as tf

filename = './img/test.jpg';
im=Image.open(filename)
img = array(im.convert("L")) 
data = img.ravel()

xData = tf.Variable(data, name="x")

saver = tf.train.Saver()
init_op = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init_op)
    save_path = "./model/minist_softmax.ckpt"
    saver.restore(sess, save_path)
    print("Model restored.")
    print(sess.run(xData))

然后我收到错误。

NotFoundError:Tensor name" x"在检查点文件中找不到./model/minist_softmax.ckpt

4 个答案:

答案 0 :(得分:0)

保存和恢复模型的图表应该相同。实际上,尝试使用火车模型的代码,但不是init = tf.initialize_all_variables()和后续培训,只需恢复模型。

答案 1 :(得分:0)

这就是我的工作,假设您的代码用于训练初始化网络,并且只有在您尝试加载为已保存的网络时才会失败。未经测试,但请检查阻止 if(loading):

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data_2/", one_hot=True)
print("Download Done!")

x = tf.placeholder(tf.float32, [None, 784])

# paras
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])

# loss func
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
saver = tf.train.Saver()
# init

sess = tf.Session()
loading = False #first run False. Subsequent runs change to True. Personally I try to load and if it fails ask if it should initialise a new one.
if (loading) :
   #no need to initialise when loading. 
   save_path = "./model/minist_softmax.ckpt"
   saver.restore(sess,save_path)
else :
  init = tf.initialize_all_variables()
  sess.run(init)

# train 
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

print("Accuarcy on Test-dataset: ", sess.run(accuracy, feed_dict={x:        mnist.test.images, y_: mnist.test.labels}))

# save model 
saver = tf.train.Saver()
save_path = "./model/minist_softmax.ckpt"
saver.restore(sess, save_path)
print("Model restored.")
print(sess.run(xData))

答案 2 :(得分:0)

删除还原模型中的以下代码

<com.github.pinball83.maskededittext.MaskedEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    app:mask="xxx-xxx-xx-xx"
    app:notMaskedSymbol="x"
    app:maskIconColor="@color/colorPrimary" />

编辑恢复模型中的代码

xData = tf.Variable(data, name="x")

可以做到。

答案 3 :(得分:0)

恢复模型的完整代码是:

test_minist_softmax.py

# -*- coding: UTF-8 -*-  
from PIL import Image
from numpy import *
import tensorflow as tf
import sys

if len(sys.argv) < 2 :
    print('argv must at least 2. you give '+str(len(sys.argv)))
    sys.exit()
filename = sys.argv[1]
im=Image.open(filename)
img = array(im.resize((28, 28), Image.ANTIALIAS).convert("L"))
data = img.reshape([1, 784])

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

saver = tf.train.Saver()
init_op = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init_op)
    save_path = "./model/minist_softmax.ckpt"
    saver.restore(sess, save_path)
    predictions = sess.run(y, feed_dict={x: data})
    print(predictions[0]);

您可以使用此命令运行它。

python test_minist_softmax.py ./img/test_1.jpg