# x = x + y
add_op = x.assign(x + y)
# y = y / 2
div_op = y.assign(y / 2)
t1需要打开会话执行计算图
with tf. Session() as sess: # 打开会话
sess.run(tf.global_variables_initializer()) # 初始会话
for iteration in range(50):
sess.run(add_op)
sess.run(div_op)
print(x.eval()) # x为variable对象,用eval函数调取真实值 或者:sess.eval(x)
tensorflow2
导包看版本
import tensorflow as tf
print(tf.__version__)
定义变量
x = tf.constant(0.)
y = tf.constant(1.)
直接执行操作,无需开启会话
for iteration in range(50):
x = x + y
y = y / 2
print(x) # 产生x为tf.Tensor
print(x.numpy())# 用numpy将格式转换为正常实数