ValueError with' MatMul'在张量流中

时间:2017-06-14 15:29:20

标签: python tensorflow

我是Tensorflow的新手。我刚开始从 TensorFlow官方网站开始研究这台机器学习技术。我正在尝试实施 Softmax回归,但是会出现以下错误。

  

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

以下是完整的代码:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)

x=tf.placeholder(tf.float32,[None,784])
W=tf.Variable(tf.zeros([10,784]))
b=tf.Variable(tf.zeros([10]))
y=tf.nn.softmax(tf.matmul(x,W)+b)

y_=tf.placeholder(tf.float32,[None,10])
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess=tf.InteractiveSession()
tf.global_variables_initializer().run()

for _ in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

以下是我得到的输出:

enter image description here

提前致谢。

1 个答案:

答案 0 :(得分:1)

请注意,对于x的定义,一个训练样本将是一个向量(x1,....,x784),x的行数由样本数给出一批。考虑到这一点,“有趣”维度是列数,而不是人们可能期望的行数。因此,向量x从左侧乘以权重矩阵W,从而得到形状向量(num_samples_per_batch,10)。要从左侧执行此乘法,您必须按如下方式切换W的参数:

W=tf.Variable(tf.zeros([784,10]))

顺便说一句:tf.nn.softmax_cross_entropy_with_logits()需要未缩放的日志记录(https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits),因此在使用此选项之前不应执行tf.nn.softmax()。因此,我认为改变

会更好
y=tf.nn.softmax(tf.matmul(x,W)+b)

y=tf.matmul(x,W)+b

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

correct_prediction = tf.equal(tf.argmax(tf.nn.softmax(y),1), tf.argmax(y_,1))

这是修改的例子:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)

x=tf.placeholder(tf.float32,[None,784])
W=tf.Variable(tf.zeros([784, 10]))
b=tf.Variable(tf.zeros([10]))
# y=tf.nn.softmax(tf.matmul(x,W)+b)
y = tf.matmul(x,W) + b

y_=tf.placeholder(tf.float32,[None,10])
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess=tf.InteractiveSession()
tf.global_variables_initializer().run()

for _ in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(tf.nn.softmax(y),1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))