Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Tensorflow tf.变量无法执行加法_Tensorflow - Fatal编程技术网

Tensorflow tf.变量无法执行加法

Tensorflow tf.变量无法执行加法,tensorflow,Tensorflow,我可以使用常量执行加法,但不能通过tf.Variable执行加法 当我使用常量进行加法时,下面的代码运行良好 import tensorflow as tf a = tf.constant(5) b = tf.constant(6) sess = tf.Session() result = sess.run(a + b) print(result) 但当我尝试使用tf.Variable时,它不起作用,下面是我的代码 import tensorflow as tf a = tf.Varia

我可以使用常量执行加法,但不能通过tf.Variable执行加法

当我使用常量进行加法时,下面的代码运行良好

import tensorflow as tf

a = tf.constant(5)
b = tf.constant(6)

sess = tf.Session()
result = sess.run(a + b)
print(result)
但当我尝试使用tf.Variable时,它不起作用,下面是我的代码

import tensorflow as tf

a = tf.Variable(5)
b = tf.Variable(6)

sess = tf.Session()
result = sess.run(a + b)
print(result)

有人能帮我吗?谢谢

首先需要初始化变量:

import tensorflow as tf
​
a = tf.Variable(5)
b = tf.Variable(6)
​    ​
sess = tf.Session()
初始化变量:

sess.run(tf.global_variables_initializer())     

result = sess.run(a + b)

print(result)
11


您可以阅读有关变量初始化的更多信息,其中指出与tf.Tensor对象不同,tf.variable存在于单个session.run调用的上下文之外。因此,在使用变量之前,必须对其进行初始化。初始化是特定于会话的,这意味着无论何时启动新会话,并且要使用这些变量,都必须首先初始化它们。

您需要首先初始化变量:

import tensorflow as tf
​
a = tf.Variable(5)
b = tf.Variable(6)
​    ​
sess = tf.Session()
初始化变量:

sess.run(tf.global_variables_initializer())     

result = sess.run(a + b)

print(result)
11


您可以阅读有关变量初始化的更多信息,其中指出与tf.Tensor对象不同,tf.variable存在于单个session.run调用的上下文之外。因此,在使用变量之前,必须对其进行初始化。初始化是特定于会话的,这意味着无论何时启动新会话,并且要使用这些变量,都必须首先对它们进行初始化。

谢谢,但是您能否告诉我这一行将执行什么操作sess.run(tf.global\u variables\u initializer())。如果你能简单地解释一下就好了。谢谢您可以阅读这里的内容,它表示与tf.Tensor对象不同,tf.Variable存在于单个session.run调用的上下文之外。因此,在使用变量之前,必须对其进行初始化。。初始化是特定于会话的,这意味着无论何时启动新会话,并且想要使用这些变量,都必须首先对它们进行初始化。谢谢,但是您能否告诉我这一行将执行什么操作sess.run(tf.global\u variables\u initializer())。如果你能简单地解释一下就好了。谢谢您可以阅读这里的内容,它表示与tf.Tensor对象不同,tf.Variable存在于单个session.run调用的上下文之外。因此,在使用变量之前,必须对其进行初始化。。初始化是特定于会话的,这意味着无论何时启动新会话,并且想要使用这些变量,都必须首先初始化它们。