2017-04-18 6 views
1

나는 약 92 %의 정확도로 MNIST 데이터 분류를위한 간단한 모델을 가지고있다.단순한 MNIST 데이터 모델로의 Tensorflow 전달 이미지

숫자로 이미지를 제공하고 해당 숫자의 출력으로 레이블을 얻을 수있는 방법이 있는지 알고 싶습니다. 이미지는 미리 정의 된 이미지가 아닌 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의 형식이 동일해야한다는

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

주를 수행하여 새로운 이미지로 제공하는 라벨을 얻을 수 있습니다 batch_x 현재 new_image을 크기 1의 배치로 생각하면 batch_x이 2D 인 경우 new_image도 2D (모양 1 x 784) 여야합니다.

batch_x의 이미지를 사전 처리 (예 : 정규화) 한 경우 new_image과 동일한 작업을 수행해야합니다.

위의 코드와 동일한 코드를 사용하여 여러 이미지의 라벨을 동시에 가져올 수도 있습니다. new_image을 여러 이미지의 일부 2D 배열 new_images으로 바꿉니다.

+0

내 코드 바로 아래에서 대답의 코드 줄을 추가해야합니다. 여기서 new_image는 테스트하려는 이미지의 경로가되며 batch_x의 이미지와 크기가 같아야합니다. –

+0

예, 루프를 (범위 (epoch) 범위 (training_epochs)) 종료 한 후 "with tf.Session() as sess :"와 함께 추가하십시오. –

관련 문제