我正在改编这个教程,以便在自己的图像集上训练卷积神经网络。
因此,我创建了这个函数来尝试获取批次,尽管它还没有创建批次:
def training_batch(batch_size): images = trainpaths for i in range(len(images)): # 将路径转换为图像 image = mpimg.imread(images[i]) images[i] = image # 创建批次 X, Y = images, trainlabels return X, Y
这个函数在这里被调用:
def optimize(num_iterations): global total_iterations for i in range(total_iterations, total_iterations + num_iterations): # 获取一批训练示例。 # x_batch 现在保存一批图像,而 # y_true_batch 是这些图像的真实标签。 x_batch, y_true_batch = training_batch(train_batch_size) # 将批次放入字典中,使用 TensorFlow 图中的占位符变量的正确名称。 feed_dict_train = {x: x_batch, y_true: y_true_batch} # 使用这批训练数据运行优化器。 # TensorFlow 将 feed_dict_train 中的变量 # 分配给占位符变量,然后运行优化器。 session.run(optimizer, feed_dict=feed_dict_train) (...)
问题是,如果我运行这段代码,我会得到
Traceback (most recent call last): File "scr.py", line 405, in <module> optimize(1) File "scr.py", line 379, in optimize session.run(optimizer, feed_dict=feed_dict_train) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 905, in run run_metadata_ptr) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1116, in _run str(subfeed_t.get_shape())))ValueError: Cannot feed value of shape (2034, 218, 178, 3) for Tensor u'x:0', which has shape '(?, 116412)'
有人能解释一下如何修复这个问题吗?
回答:
添加以下代码行:
x_batch = x_batch.reshape((-1, 218 * 178 * 3))
应该可以解决这个问题。然而,由于您正在构建卷积神经网络,您无论如何都需要图像的空间信息。因此,我建议您将 x
占位符的形状更改为 (None, 218, 178, 3)
,而不是 (None, 116412)
。在这种情况下,x_batch
的转换将不再必要。