Mnist训练时ValueError错误

关于ValueError: Dimensions must be equal, but are 784 and 10 for ‘mul’ (op: ‘Mul’) with input shapes: [?,784], [784,10].错误

今天在用MNIST数据集进行简单的分类训练时,遇到了这个问题,搞了一会,知道错误在哪,特地写一下心得注明一下。
以下是修改错误之前的源码

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

#加载数据集
mnist = input_data.read_data_sets('D:\Programming Files\学习\Pycharm\PycharmWorkspace\MNIST_data',one_hot=True)
#设定批次大小
batch_size = 100
#计算批次数量
n_batch = mnist.train.num_examples // batch_size

#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])

#创建简单的不含隐藏层的神经网络
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
W_plus_b = tf.matmul(x*W)+b
prediction = tf.nn.softmax(W_plus_b)

#定义二次代价损失函数
loss = tf.reduce_mean(tf.square(y-prediction))
#使用梯度下降
optimizer = tf.train.GradientDescentOptimizer(0.2)
#最小化损失函数
train = optimizer.minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

#将结果存到布尔型列表里
accuracy_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax表示返回一维张量最大值的位置
#计算准确率
accuracy = tf.reduce_mean(tf.cast(accuracy_prediction,tf.float32))     #cast将前者转换为float类型变量

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)      #batch_xs每次获得batch_size大小图片,batch_ys获得标签
            sess.run(train,feed_dict={x:batch_xs,y:batch_ys})

        #每一轮输出准确率
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print('Iter:'+str(epoch)+' accuracy:'+str(acc))`

运行时出现了如下错误:

ValueError: Dimensions must be equal, but are 784 and 10 for 'mul' (op: 'Mul') with input shapes: [?,784], [784,10].

错误原因是在创建不含隐藏层的简单神经网络时tf.matmul()的参数传递问题,正确的应为 tf.matmul(x,W),而不是tf.matmul(x*W)
另外,在StackoverFlow中也给出了这种可能错误:误使用tf.multiply() 造成,详细点我

猜你喜欢

转载自blog.csdn.net/jerry_kuan/article/details/81292421