gpt4 book ai didi

python - 澄清 tf.Session() 范围 TensorFlow

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:03 25 4
gpt4 key购买 nike

我有一个 python 程序,我在其中定义了一个网络,并且像往常一样,我在我拥有的函数中训练它

with tf.Session() as sess:
...
for epoch in xrange(num_epochs):
...
for n in xrange(num_batches):
_, c = sess.run([optimizer, loss], feed_dict={....

在损失函数中,我必须做很多工作才能得到损失,特别是,我必须在张量中取最大值并用它来做一些事情。举个例子

values = tf.constant([0, 1, 2, 0, 2], dtype=tf.float32)
max_values = tf.reduce_max(values) # Tensor...
...

max_values 行中,如果我使用调试,它会说它是一个张量而不是一个值,所以如果我以这种方式更改我的代码,将在之前创建的 session 传递给函数一段代码

values = tf.constant([0, 1, 2, 0, 2], dtype=tf.float32)
max_values = sess.run(tf.reduce_max(values)) # 2.0
...

它有效。但是这个损失函数已经在一个 session 的范围内,所以我的问题是为什么结果是张量而不是数字?有没有办法在不将 session 传递给损失函数的情况下获取值?

最佳答案

根据documentation :

TensorFlow uses the tf.Session class to represent a connection between the client program---typically a Python program, although a similar interface is available in other languages---and the C++ runtime.

这意味着当您执行 values = tf.constant([0, 1, 2, 0, 2], dtype=tf.float32) 时,您只是将一个节点插入到您的 tensorflow 图!由于 Python 是用于低级 C++ 运行时的高级 API,因此您实际上需要一个 session 来在此低级运行时评估您的 Python 代码。

这就是为什么每次您需要计算或评估 Tensorflow 变量/方法/常量/等时,您都需要使用 tf.Session().run(yournode) 在 session 中运行它/p>

希望对你有帮助

关于python - 澄清 tf.Session() 范围 TensorFlow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52832497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com