ValueError: setting an array element with a sequence when using feed_dict in TensorFlow

ValueError: setting an array element with a sequence when using feed_dict in TensorFlow

我正在尝试在执行训练时提供包含正确标签的张量。

整个训练数据集的正确标签包含在一个从 numpy 数组转换而来的张量中:

numpy_label = np.zeros((614,5),dtype=np.float32)

for i  in range(614):
    numpy_label[i,label_numbers[i]-1] = 1

# Convert to tensor
y_label_all = tf.convert_to_tensor(numpy_label,dtype=tf.float32)

我为每个批次的正确标签设置了一个占位符:

images_per_batch = 5
y_label = tf.placeholder(tf.float32,shape=[images_per_batch,5])

在每个训练步骤中,我将 y_label_all 的相应部分切片为 y_ 并希望将其作为 y_label:

提供
for step in range(100):

    # Slice correct labels for current batch
    y_ = tf.slice(y_label_all,[step,0],[images_per_batch,5])

    # Train
    _, loss_value = sess.run([train_step,loss],feed_dict={y_label:y_})

这会产生错误:

_, loss_value = sess.run([train_step,loss],feed_dict={y_label:y_})
  File "/usr/local/lib/python2.7/dist-    packages/tensorflow/python/client/session.py", line 357, in run
np_val = np.array(subfeed_val, dtype=subfeed_t.dtype.as_numpy_dtype)
ValueError: setting an array element with a sequence.

变量的形状 y_y_label:

#y_: 
Tensor("Slice:0", shape=TensorShape([Dimension(5), Dimension(5)]), dtype=float32)

#y_label: 
Tensor("Placeholder:0", shape=TensorShape([Dimension(5), Dimension(5)]), dtype=float32)

我不明白这是怎么回事?显然这与 numpy 有关 - 但现在我已将 numpy 数组转换为张量,这会影响什么吗?

非常感谢您的帮助和见解。谢谢!

问题是 feed_dict 必须与 numpy 数组兼容。

你的代码会产生这样的结果

np.array(<tf.Tensor 'Slice_5:0' shape=(5, 5) dtype=float32>, dtype=np.float32)

上面的神秘错误在 numpy 中失败。要修复它,您需要将 Tensor 转换为 numpy,如下所示

for step in range(100):

    # Slice correct labels for current batch
    y_ = tf.slice(y_label_all,[step,0],[images_per_batch,5])
    y0 = sess.run([y_])

    # Train
    _, loss_value = sess.run([train_step,loss],feed_dict={y_label:y0})