2017-02-27 71 views
1

我實現了一個相對簡單的邏輯迴歸函數。我保存所有必要的變量,如重量,偏見,X,Y,等等,然後我跑訓練算法...如何在不同的輸入上使用訓練好的模型

# launch the graph 
with tf.Session() as sess: 

    sess.run(init) 

    # training cycle 
    for epoch in range(FLAGS.training_epochs): 
     avg_cost = 0 
     total_batch = int(mnist.train.num_examples/FLAGS.batch_size) 
     # loop over all batches 
     for i in range(total_batch): 
      batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size) 

      _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys}) 

      # compute average loss 
      avg_cost += c/total_batch 
     # display logs per epoch step 
     if (epoch + 1) % FLAGS.display_step == 0: 
      print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost)) 

    save_path = saver.save(sess, "/tmp/model.ckpt") 

該模型被保存,prediction和訓練模型的accuracy顯示...

# list of booleans to determine the correct predictions 
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) 
print(correct_prediction.eval({x:mnist.test.images, y:mnist.test.labels})) 

# calculate total accuracy 
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})) 

這是所有罰款和丹迪。但是,現在我希望能夠使用訓練好的模型來預測任何給定的圖像。例如,我想餵它的圖片說7,看看它預測它是什麼。

我有另一個模塊恢復模型。首先我們加載變量...

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) 

# tf Graph Input 
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784 
y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes 

# set model weights 
W = tf.Variable(tf.zeros([784, 10])) 
b = tf.Variable(tf.zeros([10])) 

# construct model 
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax 

# minimize error using cross entropy 
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices=1)) 
# Gradient Descent 
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(cost) 

# initializing the variables 
init = tf.global_variables_initializer() 

saver = tf.train.Saver() 

with tf.Session() as sess: 
    save.restore(sess, "/tmp/model.ckpt") 

這很好。現在我想比較一個圖像和模型,並得到一個預測。在本例中,我從測試數據集mnist.test.images[0]中獲取第一個圖像,並試圖將其與模型進行比較。

classification = sess.run(tf.argmax(pred, 1), feed_dict={x: mnist.test.images[0]}) 
print(classification) 

我知道這是行不通的。我得到錯誤...

ValueError: Cannot feed value of shape (784,) for Tensor 'Placeholder:0', which has shape '(?, 784)'

我對創意不知所措。這個問題相當長,如果不可能直接得到答案,可以參考我可能採取的一些步驟。

+0

我認爲你需要重塑你的圖像數組從(784,)到(1,784)。因爲784是單個特徵中的特徵,估計器需要形狀爲'(n_samples,n_features)'的數組 –

回答

1

您的輸入佔位符的大小必須爲(?, 784),問號的含義可能是可變大小,可能是批量大小。您正在輸入尺寸爲(784,)的輸入,該輸入在錯誤消息狀態下不起作用。

在你的情況中,在預測時間,批量大小僅有1,所以下面應該工作:

import numpy as np 
... 
x_in = np.expand_dims(mnist.test.images[0], axis=0) 
classification = sess.run(tf.argmax(pred, 1), feed_dict={x:x_in}) 

假定輸入圖像是作爲一個numpy的陣列。如果它已經是張量,則相應的功能是tf.expand_dims(..)

相關問題