执行sess.run()ValueError时出错:使用序列设置数组元素

时间:2019-04-04 10:45:48

标签: python-3.x tensorflow neural-network numpy-ndarray

当我尝试运行训练步骤时,会生成此错误。该数据集是来自Kaggle的MNIST数据集。我正在使用神经网络来预测手写数字:

输入数据:[33600, 784]重塑为[784, 33600]

神经网络架构:

1层具有784 relu的W1 1000
第2层的W2 1000 x 1000 relu
第3层具有W3 500 x 1000 relu
第4层具有W4 200 x 500 relu
第5层具有W5 10 x 200和softmax
没有偏见

代码:

print(X_train[:, 0].reshape(-1, 1).shape,"   ",y_train[:,0].reshape(-1,1).shape)`

输出:(784, 1) (10, 1)

代码:

X, Y = tf.placeholder(tf.float32,[784, None]), tf.placeholder(tf.float32,[10, None])

logits = forward_propagation(X, parameters)

cost = compute_cost(logits, Y)
optimizer = tf.train.AdamOptimizer(learning_rate=1e-3).minimize(cost)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    _,c = sess.run([optimizer,cost], feed_dict= {X:X_train[:,0].reshape(-1,1),
                                                 Y:y_train[:, 0].reshape(-1,1)})
print(c)

输出:

ValueError         Traceback (most recent call 
last)
<ipython-input-41-f78f499b0606> in <module>()
8 with tf.Session() as sess:
9     sess.run(tf.global_variables_initializer())
---> 10     _,c = sess.run([optimizer,cost], feed_dict= 
{X:np.asarray(X_train), Y:np.asarray(y_train)})
11 print(c)

.......
.......

ValueError: setting an array element with a sequence.

如果可以,请更正代码。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。正如在许多其他类似问题的答案中提到的那样,问题通常与提供给feed_dict的数组的形状和类型有关。 我的主要重点只是X:X_train [:,0] .reshape(-1,1),但它是正确的形状和类型。错误发生在Y:y_train [:, 0] .reshape(-1,1)中。我无法检测到此错误,因为我在y_train上应用了one_hot_encoding,但是在转换后忘记使用.toarray()方法。因此y_train的形状看似正确,但实际上是错误的。

在经历了许多类似的问题后,作为一般建议,我想彻底检查馈入feed_dict的数组的形状,类型和内容。