python - 值错误: setting an array element with a sequence when using feed_dict in TensorFlow

标签 python arrays numpy 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})

关于python - 值错误: setting an array element with a sequence when using feed_dict in TensorFlow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36758114/

相关文章:

python - 测试 dict 是否包含在 dict 中

python - 如何找到二维数组中每一行的最大值?

python - django-registration 无法为身份验证电子邮件设置 "from"电子邮件地址

转换数组以使用 malloc

java 两个线程操作同一个数组

java - java中如何从大于1D的数组中获取长度值?

python - 在python中没有负值的情况下进行插值

python - 计算 Pandas 数据框中 np.nan 的数量

python - 如何将以列表作为值的字典转换为具有单个值的字典列表?

python - 属性错误 : StringIO instance has no attribute 'fileno'