# 3.7    常量与变量

**1.4.1** **常量 Constant**

常量指在运行过程中不会改变的值，在TensorFlow中无需进行初始化操作。

创建语句：

Constant\_name = tf.constant(value)

常量在TensorFlow中一般被用于设置训练步数、训练步长和训练轮数等超参数，此类参数在程序执行过程中一般不需要被改变，所以一般被设置为常量。

**1.4.2** **变量 Variable**

变量是指在运行过程中会改变的值，在TensorFlow中需要进行初始化操作。

创建语句：

name\_variable = tf.Variable(value, name)

**注意：V是大写字母**

个别变量初始化：

init\_op = name\_variable.initializer()

使用TensorFlow编写一个简单的神经网络一般会用到几十个变量，若编写大型的神经网络，往往会使用到成千上万个变量。若每个变量定义完都要初始化未免太过繁琐，所以TensorFlow有提供所有变量初始化的语句。\
&#x20;  所有变量初始化：

init\_op = tf.global\_variables\_initializer()

![图3-10 变量的初始化](/files/-L_XdzQ3Gg2X4V4MBGeg)

如图10所示，初始化函数也需要调用会话进行执行。TensorFlow中定义的每个变量都要进行初始化，不然会报错。

## > 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

{% code title="1.py" %}

```python
node1 = tf.Variable(3.0,tf.float32,name="node1")
node2 = tf.Variable(4.0,tf.float32,name="node2")
result = tf.add(node1, node2, name='add')

sess = tf.Session()

#变量初始化
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(result))
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://minghuiwu.gitbook.io/tfbook/di-san-zhang-mo-dao-bu-wu-kan-chai-gong-tensorflow-ji-chu/di-san-zhang-tensorflow-ji-chu/3.7-chang-liang-yu-bian-liang.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
