我在使用一些关于卷积神经网络的MNIST教程来开发自己的网络,用于将15×15的图像分类到两个类别之一。
在定义卷积网络时,我遇到了一个无效参数错误,但我无法找出问题出在哪里。以下是我用来定义卷积网络的代码:
def convolutional_neural_network(x):
weights = {'W_conv1':tf.Variable(tf.random_normal([5,5,1,32])),
'W_conv2':tf.Variable(tf.random_normal([5,5,32,64])),
'W_fc':tf.Variable(tf.random_normal([3*3*64,1024])),
'out':tf.Variable(tf.random_normal([1024, n_classes]))}
biases = {'b_conv1':tf.Variable(tf.random_normal([32])),
'b_conv2':tf.Variable(tf.random_normal([64])),
'b_fc':tf.Variable(tf.random_normal([1024])),
'out':tf.Variable(tf.random_normal([n_classes]))}
x = tf.reshape(x, shape=[-1, 15, 15, 1])
conv1 = tf.nn.relu(conv2d(x, weights['W_conv1']) + biases['b_conv1'])
conv1 = maxpool2d(conv1)
conv2 = tf.nn.relu(conv2d(conv1, weights['W_conv2']) + biases['b_conv2'])
conv2 = maxpool2d(conv2)
fc = tf.reshape(conv2,[-1, 3*3*64])
fc = tf.nn.relu(tf.matmul(fc, weights['W_fc'])+biases['b_fc'])
fc = tf.nn.dropout(fc, keep_rate)
output = tf.matmul(fc, weights['out'])+biases['out']
return output
抛出的错误如下所示:
Traceback (most recent call last):
File "/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1323, in _do_call
return fn(*args)
File "/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1302, in _run_fn
status, run_metadata)
File "/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 4096 values, but the requested shape requires a multiple of 576
[[Node: Reshape_1 = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](MaxPool_1, Reshape_1/shape)]]
我能看到tf.reshape()
请求一个大小为576的张量,但我不知道大小为4096的张量是从哪里来的。
回答:
你没有展示你是如何具体执行卷积和池化的,但很可能在conv2d
中使用了strides=[1, 1, 1, 1]
,在maxpool2d
中使用了strides=[1, 2, 2, 1]
,并且在两者中都使用了padding='SAME'
。
在这种情况下,conv1
张量的形状是(?, 8, 8, 32)
,因此conv2
张量的形状是(?, 4, 4, 64)
,而不是(?, 3, 3, 64)
。当你传递一个批次大小等于4时,tensorflow尝试将(4, 4, 4, 64)
重塑为[-1, 3*3*64]
并失败了——这就是4096的来源。
解决方案是使用conv2.shape[1] * conv2.shape[2] * conv2.shape[3]
代替硬编码的3*3*64
,这样代码对输入图像大小以及卷积和池化设置的变化更加健壮。