【问题标题】:ValueError: Cannot feed value of shape (3375, 50, 50, 2) for Tensor 'Reshape:0', which has shape '(?, 5000)'ValueError:无法为具有形状“(?,5000)”的张量“重塑:0”提供形状(3375、50、50、2)的值
【发布时间】:2017-11-22 19:03:03
【问题描述】:

我正在学习 TensorFlow。以下是我使用 TensorFlow 进行 MLP 的代码。我遇到了一些数据维度不匹配的问题。

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
wholedataset = np.load('C:/Users/pourya/Downloads/WholeTrueData.npz')
data = wholedataset['wholedata'].astype('float32')
label = wholedataset['wholelabel'].astype('float32')
height = wholedataset['wholeheight'].astype('float32')
print(type(data[20,1,1,0]))

learning_rate = 0.001
training_iters = 5
display_step = 20
n_input = 3375

X = tf.placeholder("float32")
Y = tf.placeholder("float32")
weights = {
    'wc1': tf.Variable(tf.random_normal([3, 3, 2, 1])),
    'wd1': tf.Variable(tf.random_normal([3, 3, 1, 1]))
}
biases = {
    'bc1': tf.Variable(tf.random_normal([1])),
    'out': tf.Variable(tf.random_normal([1,50,50,1]))
}
mnist= data

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 2
batch_size = 100

x = tf.placeholder('float', shape = [None,50,50,2])
shape = x.get_shape().as_list()
dim = np.prod(shape[1:])
x_reshaped = tf.reshape(x, [-1, dim])

y = tf.placeholder('float', shape= [None,50,50,2])
shape = y.get_shape().as_list()
dim = np.prod(shape[1:])
y_reshaped = tf.reshape(y, [-1, dim])

def neural_network_model(data):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([5000, 
                       n_nodes_hl1])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}

    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, 
                       n_nodes_hl2])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}

    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, 
                       n_nodes_hl3])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}

    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, 
                    n_classes])),
                    'biases':tf.Variable(tf.random_normal([n_classes])),}
    l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']), 
        hidden_1_layer['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']), 
        hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']), 
        hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3,output_layer['weights']) + output_layer['biases']

    return output
def train_neural_network(x):
    prediction = neural_network_model(x)

    cost = tf.reduce_mean( 
      tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 10
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(n_input/batch_size)):
                epoch_x = wholedataset['wholedata'].astype('float32')
                epoch_y = wholedataset['wholedata'].astype('float32')

                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: 
                   epoch_y})
                epoch_loss += c

            print('Epoch', epoch, 'completed out 
            of',hm_epochs,'loss:',epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy:',accuracy.eval({x:mnist.test.images, 
        y:mnist.test.labels}))

train_neural_network(x)

我收到以下错误:

ValueError: Cannot feed value of shape (3375, 50, 50, 2) for Tensor 'Reshape:0', which has shape '(?, 5000)'

有谁知道我的代码有什么问题,我该如何解决? 数据值为 (3375, 50, 50, 2)

感谢大家的意见!

【问题讨论】:

    标签: tensorflow python-3.5


    【解决方案1】:

    我认为问题在于您对占位符和重塑使用相同的变量名x,在行中

    x = tf.placeholder('float', shape = [None,50,50,2])
    

    x = tf.reshape(x, [-1, dim])
    

    这样当你

    feed_dict={x: your_val}
    

    您正在输入重塑操作的输出。

    你应该有不同的名字,例如

    x_placeholder = tf.placeholder('float', shape = [None,50,50,2])
    x_reshaped = tf.reshape(x, [-1, dim])
    

    然后

    feed_dict={x_placeholder: your_val}
    

    【讨论】:

    • @Poetro 我已经完成了 chenges,但我遇到了另一个错误。 " ValueError: 形状必须为 2 级,但对于输入形状为 [?,50,50,2], [5000,500] 的 'MatMul' (op: 'MatMul') 为 4 级。"
    • 在其余代码中,您应该将x 替换为x_reshaped,或者将x_reshaped 重命名为x...
    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 2018-04-05
    • 2018-08-03
    • 2018-12-15
    • 2020-11-18
    • 1970-01-01
    • 2019-07-23
    • 2023-03-19
    相关资源
    最近更新 更多