2016-10-13 3 views
0

Я использую тензорный поток для обучения мини-модели и ее сохранения. Но я не использую его. Это код поезда и сохранить модельКак сохранить и использовать министрую тензорного потока

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: имя Тензор «х» не найден в контрольных файлов ./model/minist_softmax.ckpt

ответ

0

Графы как для сохраненной и восстановленной модели должны быть одинаковыми. На самом деле, попробуйте использовать код для модели поезда, но вместо init = tf.initialize_all_variables() и последующего обучения просто верните модель.

0

Вот что я делаю, предполагая, что ваш код работает для обучения инициализированной сети и только сбой при попытке загрузить как сохраненный. Не проверял, но проверить блок если (загрузка):

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)) 
0

удалить ниже кода восстановления моделируют

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

редактировать код в восстановлении модели

predictions = sess.run(y, feed_dict={x: data}) 

может это сделать.

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