ValueError:无法输入形状的值,但是形状看起来不错

时间:2019-03-19 09:11:47

标签: python-3.x tensorflow neural-network

我从彩色图像(尺寸100 * 100)中得到一些矩阵,尝试运行神经网络时出现错误:

def simple_nn(X_training, Y_training, X_test, Y_test):
    input = 100*100*3
    batch_size = 25 #not used
    X = tf.placeholder(tf.float32, [1, 100, 100, 3])
    W = tf.Variable(tf.zeros([input, 2]))
    b = tf.Variable(tf.zeros([2]))

    init = tf.global_variables_initializer()
    # model
    Y = tf.nn.softmax(tf.matmul(tf.reshape(X, [-1, input]), W) + b)
    # placeholder for correct labels
    Y_ = tf.placeholder(tf.float32, [None, 2])

    # loss function
    cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y))

    # % of correct answers found in batch
    is_correct = tf.equal(tf.argmax(Y,1), tf.argmax(Y_,1))
    accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))

    optimizer = tf.train.GradientDescentOptimizer(0.003)
    train_step = optimizer.minimize(cross_entropy)
    sess = tf.Session()
    sess.run(init)

    for i in range(len(X_training)):
        # st = batch_size * i
        # end = st + batch_size - 1
        batch_X, batch_Y = X_training[i], Y_training[i]
        train_data={X: batch_X, Y_: batch_Y}

        sess.run(train_step, feed_dict=train_data)

        a,c = sess.run([accuracy, cross_entropy], feed_dict=train_data)

        # success on test data ?
    test_data={X: X_test, Y_: Y_test}
    a,c = sess.run([accuracy, cross_entropy], feed=test_data)

我的错误:

Traceback (most recent call last):
  File "neural_net.py", line 90, in <module>
    simple_nn(X_training, Y_training, X_test, Y_test)
  File "neural_net.py", line 71, in simple_nn
    sess.run(train_step, feed_dict=train_data)
  File "/home/.../venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
    run_metadata_ptr)
  File "/home/.../venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1128, in _run
    str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (100, 100, 3) for Tensor 'Placeholder:0', which has shape '(1, 100, 100, 3)'

我不明白为什么会收到此错误,因为我的批次大小为1,所以我不知道如何更改形状来解决此错误。 如果我替换了这一行:

X = tf.placeholder(tf.float32, [1, 100, 100, 3])

通过这个(没有“ 1”):

X = tf.placeholder(tf.float32, [1, 100, 100, 3])

我收到此错误:

ValueError: Cannot feed value of shape (2,) for Tensor 'Placeholder_1:0', which has shape '(?, 2)'

1 个答案:

答案 0 :(得分:0)

我解决了(哑巴)问题,我替换了:

batch_X, batch_Y = X_training[i], Y_training[i]

通过此:

batch_X, batch_Y = [X_training[i]], [Y_training[i]]

所以我的批次中还有一个维度