tensorflow 已经将加减乘除等各种常见算术运算封装成了函数,需要时,直接调用相应函数即可。
1.四则运算
代码:
import tensorflow as tf
tf.compat.v1.disable_eager_execution() # 保证sess.run()能够正常运行
data1 = tf.constant(10.2, dtype=tf.float32) # 声明常量
data2 = tf.Variable(2.0, name="var") # 声明变量
dataAdd = tf.add(data1, data2) # 加
dataSub = tf.subtract(data1, data2) # 减
dataMul = tf.multiply(data1, data2) # 乘
dataDiv = tf.divide(data1, data2) # 除
init = tf.compat.v1.global_variables_initializer() # 初始化变量
with tf.compat.v1.Session() as sess: # 使用Session会话执行各种操作
sess.run(init)
print("data1", sess.run(data1), "data2", sess.run(data2))
print("add", sess.run(dataAdd))
print("sub", sess.run(dataSub))
print("mul", sess.run(dataMul))
print("div", sess.run(dataDiv))
输出结果: