2017-02-27 14 views
1

私は比較的簡単なロジスティック回帰関数を実装しました。表示されている...異なる入力で訓練されたモデルを使用する方法

# 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を私はそのようなその他の重み、バイアス、X、Y、として必要なすべての変数を保存し、その後、私は学習アルゴリズムを実行します...

# 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") 

これは良いです。今私は1つのイメージをモデルと比較し、予測をしたいと思います。この例では、最初の画像をテストデータセット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(..)です。

関連する問題