0

현재 TensorFlow의 초보자입니다. MNIST 세트를 사용하여 모델을 교육했으며 지금은 숫자로 사진을 만들었으므로 정밀도를 테스트하려고합니다.NIST의 TensorFlow로 예측 한 Dillema 세트

x = tf.placeholder(tf.float32, shape=[None, 784]) 
y_ = tf.placeholder(tf.float32, shape=[None, 10]) 
sess = tf.InteractiveSession() 
def weight_variable(shape): 
initial = tf.truncated_normal(shape, stddev=0.1) 
return tf.Variable(initial) 

def bias_variable(shape): 
    initial = tf.constant(0.1, shape=shape) 
    return tf.Variable(initial) 

#stride 1 and 0 padding 
def conv2d(x, W): 
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 

#pooling over 2x2 
def max_pool_2x2(x): 
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 
        strides=[1, 2, 2, 1], padding='SAME') 

W_conv1 = weight_variable([5, 5, 1, 32]) 
b_conv1 = bias_variable([32]) 
x_image = tf.reshape(x, [-1,28,28,1]) 
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 
h_pool1 = max_pool_2x2(h_conv1) 
# Second Layer 
W_conv2 = weight_variable([5, 5, 32, 64]) 
b_conv2 = bias_variable([64]) 
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 
h_pool2 = max_pool_2x2(h_conv2) 
#Fully connected layer 
W_fc1 = weight_variable([7 * 7 * 64, 1024]) 
b_fc1 = bias_variable([1024]) 
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 
keep_prob = tf.placeholder(tf.float32) 
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 
#Readout layer 
W_fc2 = weight_variable([1024, 10]) 
b_fc2 = bias_variable([10]) 

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 

cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) 
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) 
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
sess.run(tf.global_variables_initializer()) 
for i in range(200): 
    batch = mnist.train.next_batch(50) 
    if i%100 == 0: 
     train_accuracy = accuracy.eval(feed_dict={ 
     x:batch[0], y_: batch[1], keep_prob: 1.0}) 
     print("step %d, training accuracy %g"%(i, train_accuracy)) 
    train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) 

# Here is my custom dataset 

custom_data=GetDataset() 

print sess.run(y_conv,feed_dict={x: custom_data}) 

그것은 내 사용자 데이터와 예측을 만들기위한 올바른 구문되지 않습니다 : 나는이 내 모델이 얼마나 일 TensorFlow에서 을 작업의 구문이나 이해를 생각? 나는 여기서 뭔가를 놓치고 있니? 내 데이터 세트 MNIST에서와 동일한 형식으로되어 있지만 예측 만드는 방법에 대한 올바른 구문 찾을 수 있습니다

print sess.run(y_conv,feed_dict={x: custom_data}) 

감사합니다 어떤 도움을 많이!

답변

0

y_conv은 권장 사항을 작성하는 데 필요한 정보를 제공합니다. 당신은 아마도 데이터가 그 텐서에서 취하는 형태를 이해하지 못하고있을 것입니다.

cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) 
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 

참고가 softmax_cross_encropy_with_logits 방법에 y_conv을 통과 : 코드에서

당신은 손실 기능과 최적화가 있습니다. 이 시점에서 y_conv은 비 눈금 번호입니다. 음수 값은 음수 클래스를 나타내고 양수 값은 양수 클래스를 나타냅니다.

softmax은 모든 출력에 대해 확률 분포로 변환합니다. 특히 모든 출력을 [0,1] 범위로 변환합니다. 교차 엔트로피는 오류를 계산합니다 (교차 엔트로피는 [0,1] 범위의 값을 가정합니다).

그것은 당신이 다음이 softmax를 사용하는 경우 간단하게, 실제로 예측을 계산 다른 텐서를 작성하는 것이 일반적이다 : 당신이 레이블을 통해 예측 확률 분포를 줄 것이다

prediction = tf.softmax(y_conv) 

. sess.run 단계에서 텐서를 요청하십시오.

가장 가능성이 높은 클래스를 신경 쓰는 경우 최대 값은 y_conv입니다. 이 진술이 사실이라면 확률 분포가 아닌 결과를 산출하기 위해 약간 더 조정 된 tf.nn.sigmoid_cross_entropy_with_logits으로 실험하고 싶을 수도 있습니다 (단일 클래스 예측에서는 약간 더 좋고 다중 클래스 예측에서는 필수).

+0

안녕하세요, David, 빠르고 명시적인 대답에 감사드립니다. 불행하게도, 이것은 아무런 효과가없는 것 같습니다. 코드에 다음 줄을 추가했습니다. 내 코드의 sess.run 줄 앞에 "prediction = tf.nn.softmax (y_conv)"가 표시되고 "print_direct = {x : mnist.test.images }) "예측 오류를 인쇄하려고 끝에 끝에"InvalidArgumentError (위의 traceback 참조) : dtype float을 사용하여 자리 표시 자 텐서 'Placeholder_40'의 값을 입력해야합니다. \t [[Node : Placeholder_40 = Placeholder [dtype = DT_FLOAT, shape = [], _device = "/ job : localhost/replica : 0/task : 0/cpu : 0"]()]] " – Vlad

+0

다른 문제는 데이터를 전달할 자리 표시 자입니다. 그리고 당신은 그것에게 데이터를 공급하지 않습니다. 오류 메시지가 올바른 위치를 가리킬 수 있도록 이름을 먼저 지정하십시오. 라벨이 어딘가에서 사용되고있는 것 같습니다. 요청한 OP가 친구가 아니라면 자리 표시자를 먹일 필요는 없지만주의하지 않은 의존성을 갖는 것은 쉽습니다. –

+0

오류를 발견했습니다. 데이빗 감사합니다. – Vlad