【问题标题】:Tensor flow error while trying to print a basic numeric addition尝试打印基本数字加法时出现Tensorflow错误
【发布时间】:2016-07-01 21:54:17
【问题描述】:
import tensorflow as tf

x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')

model = tf.initialize_all_variables()

with tf.Session() as session:
    session.run(model)
    print(session.run(y))

此代码生成错误提示 Type Error: List of tensors when single tensor expected

可能是什么问题???

系统详情:Virtualbox:Ubuntu 16.04 xenial,张量流 0.9.0,python-3.5

【问题讨论】:

  • 我无法重现您的问题 --- 您的代码适用于我并打印“40”。您是否有机会使用交互式 Python 环境?如果是这样,也许尝试重新启动 Python?
  • 不,我没有使用交互式 Python 环境,我使用“Sublime”作为核心编辑器,除此之外没有什么不同。我已将文件保存为“tensor_test.py”,当张量源处于活动状态时,我使用基本命令“python tensor_test.py”在终端中运行它。

标签: python-3.x ubuntu tensorflow


【解决方案1】:

您似乎缺少 tensorflow 的概念方面。 首先让我从一个代码示例开始 将张量流导入为 tf

x = tf.constant(35, name='x')
y = tf.Variable(5, name='y')
add = tf.add(x,y)
update = tf.assign(y,add)

model = tf.initialize_all_variables()

with tf.Session() as session:
    session.run(model)
    print(session.run(y))
    print(session.run([add,y]))
    print(session.run([update,y]))
    print(session.run([update,y]))

这将打印以下内容

5
40 5
40 40
75 75

那么发生了什么?首先,x 和 y 不是 35 和 5。它们是 tensorflow 对象,包含数据,可以与 tensorflow 图进行交互。 x 是一个常量,当 tensorflow 请求时,它会为图形提供 35 的值,但它不等于 35。y 是一个变量,可以在 tensorflow 运行时为其赋值并更新。

在您的示例中,您将 y 的值设置为初始值为 x + 5 的变量,但 x 不是 35。x 是一个 tensorflow 对象。

在上面的示例中,我们将值 5 分配给变量 y。当我们运行会话并获得 y 的值时,它是 5。当我们获得 add 的值时,它是 35+5 但 y 没有改变。当我们执行 update 时,我们发现 y 的值已经更新为 40。最后,当我们再次更新时,我们看到 y 再次增加了 35,现在是 75。

我希望这能解释经典 python 变量和常量与 tensorflow 变量和常量之间的区别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多