Python tensorflow:分析图像时,对于Tensor',无法提供形状值(1296000,);占位符:0';,其形状为';(?,1296000)和#x27;

Python tensorflow:分析图像时,对于Tensor',无法提供形状值(1296000,);占位符:0';,其形状为';(?,1296000)和#x27;,python,tensorflow,Python,Tensorflow,我正在使用tensorflow构建一个多层感知器网络,基于 重点是训练图像识别特定模式 我使用的图像是1440*900,坐标指向这些模式(这可能不是最好的方法,但实际上只是一个测试) 运行代码时,我出现以下错误: #python multilayer_perceptron.py WARNING:tensorflow:From multilayer_perceptron.py:119: softmax_cross_entropy_with_logits (from tensorflow.pyt

我正在使用tensorflow构建一个多层感知器网络,基于

重点是训练图像识别特定模式 我使用的图像是1440*900,坐标指向这些模式(这可能不是最好的方法,但实际上只是一个测试)

运行代码时,我出现以下错误:

#python multilayer_perceptron.py

WARNING:tensorflow:From multilayer_perceptron.py:119: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.
Instructions for updating:

Future major versions of TensorFlow will allow gradients to flow
into the labels input on backprop by default.

See @{tf.nn.softmax_cross_entropy_with_logits_v2}.

2018-06-07 11:29:14.144489: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
current batch :  [195330 195330 195330 ... 155252 155252 155252] [ 90.5 312.5]
Traceback (most recent call last):
  File "multilayer_perceptron.py", line 141, in <module>
    Y: batch_y})
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 900, in run
    run_metadata_ptr)
  File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1111, in _run
    str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1296000,) for Tensor 'Placeholder:0', which has shape '(?, 1296000)'

我不知道这个错误意味着什么,也不知道如何解决它

您正在用形状
(1296000)
馈送单个元素,这是一个一维张量。 您的占位符(通常在每个tensorflow输入中)是一批元素

因此,您必须为网络提供一个
(批量大小,X)
张量。如果要一次馈送一个元素,可以使用numpy将张量重塑为所需的形状(标签张量的推理也是如此):


您的代码缺少创建
会话
并实际运行图表的部分。错误来自
sess.run()
行,您的输入数据有问题。发布您的所有代码,我们无法帮助您完成此处的内容好的,很抱歉,我添加了整个代码好的,您的解决方案似乎运行良好。但是如果我理解正确的话,我可以把一个步骤的一批训练对象传递给会议吗?我是否应该创建一个大小为batch\u size的numpy.array并用训练对象填充它?是的,您不仅可以而且应该通过一批训练对象。这将大大加快您的训练过程(并使您的损失波动更小,因此您将更快地收敛)好吧!我应该把整个训练集放在一个批次里吗?如果它适合记忆,为什么不呢。但您必须找到正确的折衷办法(有时使用的批处理太大,只会导致收敛速度慢,而没有任何其他改进)
# Network Parameters 
n_hidden_1 = 10 #256 # 1st layer number of neurons
n_hidden_2 = 10 #256 # 2nd layer number of neurons
#each image has been flattened and converted to a 1-D numpy array of 1440*900
n_input = INPUT_SIZE # img size
n_classes = 2 # coordinates of where to click

# tf Graph input
X = tf.placeholder("float", [None, n_input]) #n_input is size of input which is 784 pixels
Y = tf.placeholder("float", [None, n_classes])  # n_classes is size of output which is 10 digits here so why float and not bool ?

# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}

biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}


# Create model
def multilayer_perceptron(x):
    # Hidden fully connected layer with 256 neurons
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    # Hidden fully connected layer with 256 neurons
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    # Output fully connected layer with a neuron for each class
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

# Construct model
logits = multilayer_perceptron(X)

# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Initializing the variables
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(len(train_data)/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            #batch_x, batch_y = mnist.train.next_batch(batch_size)
            batch_x = train_data[i] # numpy.array of 1-D image
            batch_y = train_labels[i] # numpy.array of coords of where to click
            print("current batch : ", batch_x, batch_y)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], 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
    pred = tf.nn.softmax(logits)  # Apply softmax to logits
    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: mnist.test.images, Y: mnist.test.labels}))
        _, c = sess.run([train_op, loss_op], feed_dict={
                         X: np.expand_dims(batch_x, axis=0),
                         Y: np.expand_dims(batch_y, axis=0)})