我有一个 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>
希望对你有帮助
