2017-04-18 57 views
1

我有簡單的MNIST數據分類模型,準確率在92%左右。Tensorflow將圖像傳遞給簡單的MNIST數據模型

我想知道是否有任何方法可以用數字提供圖像並獲取該數字的輸出標籤?圖像可以來自mnist測試數據,而不是自定義圖像,只是爲了避免圖像預處理?以下是我的模型的代碼。

感謝

import tensorflow as tf 

#reset graph 
tf.reset_default_graph() 

#constants 
learning_rate = 0.5 
batch_size = 100 
training_epochs = 5 
logs_path = "/tmp/mnist/2" 

#load mnist data set 
from tensorflow.examples.tutorials.mnist import input_data 
mnist = input_data.read_data_sets('MNIST_data', one_hot=True) 

with tf.name_scope('inputs'): 
    x = tf.placeholder(tf.float32, shape=[None,784], name = "image-input") 
    y_= tf.placeholder(tf.float32, shape=[None, 10], name = "labels-input") 
#weights 
with tf.name_scope("weights"): 
    W = tf.Variable(tf.zeros([784,10])) 
#biases 
with tf.name_scope("biases"): 
    b= tf.Variable(tf.zeros([10])) 

#Activation function softmax 
with tf.name_scope("softmax"): 
    #y is prediction 
    y = tf.nn.softmax(tf.matmul(x,W) +b) 

#Cost function 
with tf.name_scope('cross_entropy'): 
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1])) #???? 

#Define Optimizer 
with tf.name_scope('train'): 
    train_optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) 

#Accuracy 
with tf.name_scope('Accuracy'): 
    correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) 
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) 

tf.summary.scalar("cost",cross_entropy) 
tf.summary.scalar("accuracy",accuracy) 
#Merge all summaries into a single "operation" which will be executed in a session 
summary_op = tf.summary.merge_all() 

with tf.Session() as sess: 
    #initialize variables before using them 
    sess.run(tf.global_variables_initializer()) 
    #log writer object 
    # writer = tf.train.SummaryWriter(logs_path, graph=tf.get_default_graph()) 
    writer = tf.summary.FileWriter(logs_path,graph=tf.get_default_graph()) 
    #training cycles 
    for epoch in range(training_epochs): 
     #number of batches in one epoch 
     batch_count = int(mnist.train.num_examples/batch_size) 
     for i in range(batch_count): 
      batch_x, batch_y = mnist.train.next_batch(batch_size) 
      _,summary = sess.run([train_optimizer,summary_op], feed_dict={x: batch_x, y_:batch_y}) 
      writer.add_summary(summary,epoch * batch_count + i) 
     if epoch % 5 == 0: 
      print("Epoch: ",epoch) 
    print("Accuracy: ",accuracy.eval(feed_dict={x: mnist.test.images,y_:mnist.test.labels})) 
    print("Done") 

回答

1

你訓練的網絡後,就可以得到該網絡通過做

new_image_label= sess.run(y, feed_dict={x: new_image}) 

注意的new_image格式應該是一樣給人以全新的形象標籤截至batch_x。考慮將new_image作爲批量大小1,因此如果batch_x是2D,則new_image也應該是2D(形狀1的784)。

此外,如果您對batch_x中的圖像執行了一些預處理(例如標準化),則需要使用new_image執行相同的操作。

您也可以使用與上面相同的代碼同時獲取多張圖片的標籤。只需將new_image替換爲幾張圖像的一些二維陣列new_images

+0

所以就在我的代碼下面,我應該從你的答案中添加一行代碼,其中new_image將作爲我想測試的圖像的路徑,並且必須與batch_x中的圖像具有相同的大小? –

+0

是的,只需在循環結束後(在範圍(training_epochs)中的epoch)結束後,將其添加到「with tf.Session()as sess:」中 –