Tensorflow2.0学习(1): Tensorflow1与Tensorflow2的简单区别

实例:1 + 1/2 + 1/2^2 + 1/2^3 + … + 1/2^50

tensorflow1

  • 导包,看版本
import tensorflow as tf
print(tf.__version__)
  • 定义变量
x = tf.Variable(0.)
y = tf.Variable(1.)
  • 定义计算图
# 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将格式转换为正常实数
发布了35 篇原创文章 · 获赞 3 · 访问量 2513

猜你喜欢

转载自blog.csdn.net/Smile_mingm/article/details/104473902