简体   繁体   English

ValueError:尺寸必须相等,但对于'MatMul_1'(op:'MatMul'),输入形状为784和500:[?,784],[500,500]

[英]ValueError: Dimensions must be equal, but are 784 and 500 for 'MatMul_1' (op: 'MatMul') with input shapes: [?,784], [500,500]

I'm new to tensorflow and I'm following a tutorial by sentdex. 我是tensorflow的新手,我正在遵循sentdex的教程。 I keep on getting the error - 我继续得到错误 -

ValueError: Dimensions must be equal, but are 784 and 500 for 
'MatMul_1' (op: 'MatMul') with input shapes: [?,784], [500,500].

The snippet where I believe is causing the issue is - 我认为造成这个问题的片段是 -

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

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

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

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

return output

Although I'm a noob and may be wrong. 虽然我是一个菜鸟,但可能是错的。 My entire code is - 我的整个代码是 -

mnist = input_data.read_data_sets("/tmp/ data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')


def neural_network_model(data):
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784, 
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(data, hidden_2_layer['weights']), 
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)

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

output = tf.add(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(mnist.train.num_examples / batch_size)):
            epoch_x, epoch_y = mnist.train.next_batch(batch_size)
            _, 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)

Please help. 请帮忙。 By the way, I'm running on Mac in a virtual environment with Python 3.6.1 and Tensorflow 1.2. 顺便说一句,我在Python 3.6.1和Tensorflow 1.2的虚拟环境中运行Mac。 And I am using the IDE Pycharm CE. 我正在使用IDE Pycharm CE。 If any of that information is useful. 如果任何该信息有用。

The problem is that you are referencing data instead of l1 . 问题是您引用的是data而不是l1 Instead of 代替

l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']), 
                      hidden_2_layer['biases'])

your code should read 你的代码应该阅读

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

and ditto for l3 . l3同上。 Instead of 代替

l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']), 
                      hidden_3_layer['biases'])

you should have 你应该有

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

The following code ran without error for me: 以下代码运行时没有错误:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

def print_shape(obj):
    print(obj.get_shape().as_list())

def neural_network_model(data):
    hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
                                                               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]))}
    print_shape(data)
    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
                hidden_1_layer['biases'])
    print_shape(l1)
    l1 = tf.nn.relu(l1)
    print_shape(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.add(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(mnist.train.num_examples / batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ValueError:尺寸必须相等,但对于'Mul'(op:'Mul'),输入形状为784和500:[?,784],[784,500] - ValueError: Dimensions must be equal, but are 784 and 500 for 'Mul' (op: 'Mul') with input shapes: [?,784], [784,500] 尺寸必须相等,但对于输入形状为[1,15],[1,500]的'MatMul_1'(op:'MatMul'),尺寸应为15和1 - Dimensions must be equal, but are 15 and 1 for 'MatMul_1' (op: 'MatMul') with input shapes: [1,15], [1,500] ValueError:尺寸必须相等,但输入形状为[?,64],[4 ,?]的'MatMul'(op:'MatMul')的尺寸必须为64和4 - ValueError: Dimensions must be equal, but are 64 and 4 for 'MatMul' (op: 'MatMul') with input shapes: [?,64], [4,?] Tensorflow引发“尺寸必须相等,但输入形状为[0,100],[0,100]的'MatMul'(op:'MatMul')的尺寸必须为100和0。” - Tensorflow throws “Dimensions must be equal, but are 100 and 0 for 'MatMul' (op: 'MatMul') with input shapes: [0,100], [0,100].” python numpy ValueError:shapes(171,)和(784,500)未对齐:171 - python numpy ValueError:shapes (171,) and (784,500) not aligned: 171 尺寸必须相等,但对于输入形状为 [128,1]、[64,128] 的 'sampled_softmax_loss/MatMul'(操作:'MatMul')为 1 和 128 - Dimensions must be equal, but are 1 and 128 for 'sampled_softmax_loss/MatMul' (op: 'MatMul') with input shapes: [128,1], [64,128] ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') with input shape: [2], [2,3] - ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') with input shapes: [2], [2,3] 尺寸必须相等 Tensorflow 'MatMul' - Dimensions must be equal Tensorflow 'MatMul' 如何解决“hape必须排名2但是'MatMul_4'(op:'MatMul')排名为0的输入形状:[],[3]。” - how to fix “hape must be rank 2 but is rank 0 for 'MatMul_4' (op: 'MatMul') with input shapes: [], [3].” 形状必须为2级,但输入形状为[100,100],[?, 15,100]的'MatMul_46'(op:'MatMul')的等级为3 - Shape must be rank 2 but is rank 3 for 'MatMul_46' (op: 'MatMul') with input shapes: [100,100], [?,15,100]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM