You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow调用sess.run()触发ValueError的技术咨询

解决TensorFlow矩阵乘法的ValueError问题

嘿,我来帮你排查这个错误~你遇到的ValueError: setting an array element with a sequence,核心原因是你给feed_dict传入了TensorFlow的Variable对象,但feed_dict需要的是实际的数值数组(比如numpy数组或Python列表),而不是计算图里的节点。

错误原因拆解

你定义的test["A"]和test["B"]是tf.Variable类型,它们是TensorFlow计算图中的节点,并不是真正存储数值的数组。当你直接把它们塞进feed_dict时,TensorFlow无法把这些节点转换成numpy数组,所以抛出了错误。

两种解决方案

方案1:修正feed_dict的用法(保留placeholder)

如果你想继续用placeholder,需要先通过sess.run()获取变量的实际数值,再传入feed_dict。另外还要注意类型匹配——你的placeholder是float64,但tf.random_normal默认是float32,最好统一类型避免潜在问题:

import tensorflow as tf

x = tf.placeholder(tf.float64)
y = tf.placeholder(tf.float64)
# 指定random_normal的dtype和placeholder一致
test = {
    "A": tf.Variable(tf.random_normal([20, 20], dtype=tf.float64)),
    "B": tf.Variable(tf.random_normal([20, 20], dtype=tf.float64))
}
math_stuff = tf.matmul(x, y)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # 先获取变量的实际数值
    a_val, b_val = sess.run([test["A"], test["B"]])
    # 把数值传入feed_dict
    print(sess.run(math_stuff, feed_dict={x: a_val, y: b_val}))

方案2:简化代码(去掉不必要的placeholder)

其实你本来就是用变量来做矩阵乘法,完全不需要placeholder,直接用变量计算更简洁:

import tensorflow as tf

test = {
    "A": tf.Variable(tf.random_normal([20, 20])),
    "B": tf.Variable(tf.random_normal([20, 20]))
}
# 直接用变量执行矩阵乘法
math_stuff = tf.matmul(test["A"], test["B"])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(math_stuff))

这样运行后就能正常输出20×20矩阵相乘的结果啦~

内容的提问来源于stack exchange,提问作者Tissuebox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:31:24