tensorflow四则运算
-
运算实现
import tensorflow as tf data1 = tf.constant(6) data2 = tf.constant(2) dataAdd = tf.add(data1,data2)#加 dataMul = tf.multiply(data1,data2)#乘 dataSub = tf.subtract(data1,data2)#减 dataDiv = tf.divide(data1,data2)#除 #as后面sess代替tf.Session() with tf.Session() as sess: print('加法运算结果为:') print(sess.run(dataAdd)) print('乘法运算结果为:') print(sess.run(dataMul)) print('减法运算结果为:') print(sess.run(dataSub)) print('除法运算结果为:') print(sess.run(dataDiv)) print('end!')
结果:
加法运算结果为: 8 乘法运算结果为: 12 减法运算结果为: 4 除法运算结果为: 3.0 end!
-
别的运算
import tensorflow as tf data1 = tf.constant(6) data2 = tf.Variable(2) dataAdd = tf.add(data1,data2) dataCopy = tf.assign(data2,dataAdd)# 复制dataAdd ->data2 data2=8 dataMul = tf.multiply(data1,data2) dataSub = tf.subtract(data1,data2) dataDiv = tf.divide(data1,data2) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print('sess.run(dataAdd):',sess.run(dataAdd)) print('sess.run(dataMul):',sess.run(dataMul)) print('sess.run(dataSub):',sess.run(dataSub)) print('sess.run(dataDiv):',sess.run(dataDiv)) print('sess.run(dataCopy):',sess.run(dataCopy))#8->data2 print('dataCopy.eval():',dataCopy.eval())#8+6->14->data = 14不用session使用.eval()实质是获取默认session print('end!') print('tf.get_default_session()',tf.get_default_session().run(dataCopy))