验证函数中张量的值

时间:2016-06-19 05:19:33

标签: tensorflow

我正在为MNIST输入创建一个深度学习完全连接的NN。我有一个函数(它采用占位符输入)

# Create model                                                                                                                
def multilayer_perceptron(x, activation_fn, weights, biases, dbg=False):
    layerDatas = OrderedDict()
    # get each layer data                                                                                                     
    prev = x
    for i in range(len(weights)-1):
        weight = weights.items()[i][1]
        bias = biases.items()[i][1]
        var = 'layer_' + str(i+1)
        layerData = tf.add(tf.matmul(prev, weight), bias)
        layerData = activation_fn(layerData)
        prev = layerData
        layerDatas[var] = layerData

    # output layer with linear function, using the last layer output value                                                    
    val = tf.matmul(prev, weights['out'])
    out_layer = tf.matmul(prev, weights['out']) + biases['out']
    print x.eval() # debug the data
    return out_layer

在权重和偏见中采用多个层。我用

调用主程序
sess = tf.InteractiveSession() # start a session                                                                          

print 'Data', n_input, n_classes
print 'Train', train_set_x.shape, train_set_y.shape

(weights, biases) = createWeightsBiases(layers, n_input, n_classes, dbg)

# tf Graph input                                                                                                          
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])

# Construct model                                                                                                         
pred = multilayer_perceptron(x, activation_fn, weights, biases, dbg)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Initializing the variables                                                                                              
init = tf.initialize_all_variables()

done_looping = False

display_step = 1

# Add ops to save and restore all the variables.                                                                          
saver = tf.train.Saver()

# Launch the graph                                                                                                        
sess.run(init)

# Training cycle
epochs = 1000                                                                                                       
for epoch in range(epochs):
    avg_cost = 0.
    total_batch = int(len(train_set_x)/batch_size)
    print 'Batch', total_batch, batch_size
    # Loop over all batches                                                                                               
    for i in range(total_batch):
        batch_x = train_set_x[i * batch_size: (i + 1) * batch_size]
        batch_y = train_set_y[i * batch_size: (i + 1) * batch_size]                                                                                         
        # Run optimization op (backprop) and cost op (to get loss value)                                                  
        _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
        # Compute average loss                                                                                            
        avg_cost += c / total_batch
    # Display logs per epoch step                                                                                         
    if epoch % display_step == 0:
        print "Epoch:", '%04d' % (epoch+1), "cost=", \
            "{:.9f}".format(avg_cost)
print "Optimization Finished!"

# Test model                                                                                                              
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))

# Calculate accuracy                                                                                                      
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print "Accuracy:", accuracy.eval({x: valid_set_x, y: valid_set_y})

当我尝试在polygon_perceptron函数中打印张量时,我遇到了

崩溃
tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

我很感激帮助解决这个问题。

1 个答案:

答案 0 :(得分:2)

您无法评估占位符。相反,您可以使用适当的值为占位符提供图表,然后仅提取内容(这是您为图表提供的值)。

因此,请从print x.eval() # debug the data函数中删除multilayer_perceptron行。

要检查占位符的值,您必须提供它并提取您只需要它的值(旁注:它没用)。 如果你真的想这样做,那就是:

placeholder_value = sess.run(x, feed_dict={x: [1,2,3,4]})
print placeholder_value

它将打印值[1,2,3,4]