常量计算
#小细节 可以更快import osos.environ['TF_CPP_MIN_LOG_LEVEL']='2'import tensorflow as tf#创建常量opm1 = tf.constant([[3,3]])m2 = tf.constant([[2],[3]])#创建矩阵乘法opproduct = tf.matmul(m1,m2)print(m1)print(m2)print(product)#也可以这样写with tf.Session() as sess: result = sess.run(product) print(result)
Tensor("Const:0", shape=(1, 2), dtype=int32)Tensor("Const_1:0", shape=(2, 1), dtype=int32)Tensor("MatMul:0", shape=(1, 1), dtype=int32)[[15]]
变量的使用
#小细节 可以更快import osos.environ['TF_CPP_MIN_LOG_LEVEL']='2'import tensorflow as tfx = tf.Variable([1,2])a = tf.constant([3,3])sub = tf.subtract(x,a)add = tf.add(x,a)#用于 初始化变量init = tf.global_variables_initializer()with tf.Session() as sess: #执行变量初始化 sess.run(init) res1 = sess.run(sub) res2 = sess.run(add) print(res1) print(res2)#创建变量 初始化为0cnt = tf.Variable(0,name='cnt')#加法opcntadd = tf.add(cnt,1)#赋值op,不能使用等号update = tf.assign(cnt,cntadd)init = tf.global_variables_initializer()with tf.Session() as sess: sess.run(init) for i in range(5): sess.run(update) print(sess.run(cnt))
[-2 -1][4 5]12345
feed和fetch
#小细节 可以更快import osos.environ['TF_CPP_MIN_LOG_LEVEL']='2'import tensorflow as tfinput1 = tf.constant(1)input2 = tf.constant(2)input3 = tf.constant(3)add = tf.add(input1,input2)mul = tf.multiply(add,input3)#fetch 用于同时执行多个opwith tf.Session() as sess: res = sess.run([add,mul]) print(res)#feed#占位符x1 = tf.placeholder(tf.int64)x2 = tf.placeholder(tf.int64)output = tf.add(x1,x2)#feed的数据以字典的形式传入with tf.Session() as sess: print(sess.run(output,feed_dict={x1:[11],x2:[2]}))
[3, 9][13]
简单线性拟合
import osimport tensorflow as tfimport numpy as npos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'# 随机生成100个点,样本数据x_data = np.random.rand(100)y_data = x_data * 0.1 + 0.2# 创建线性模型 y = k*x+bb = tf.Variable(0.)k = tf.Variable(0.)y = k * x_data + b# 二次代价函数loss = tf.reduce_mean(tf.square(y_data - y))# 定义一个梯度下降法来进行训练的优化器optimizer = tf.train.GradientDescentOptimizer(0.2)# 最小化代价函数train = optimizer.minimize(loss)init = tf.global_variables_initializer()with tf.Session() as sess: sess.run(init) for step in range(400): sess.run(train) if step % 50 == 0: print(step, sess.run([k, b]))
0 [0.056841929, 0.10133078]50 [0.10317788, 0.19820875]100 [0.10106816, 0.19939792]150 [0.10035903, 0.19979763]200 [0.10012068, 0.19993198]250 [0.10004056, 0.19997714]300 [0.10001365, 0.1999923]350 [0.10000461, 0.1999974]
计算x^y
import osimport tensorflow as tfos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'x = tf.placeholder(dtype=tf.int64, name='x')y = tf.placeholder(dtype=tf.int64, name='y')ans = tf.pow(x, y);sess = tf.Session()sess.run(tf.global_variables_initializer())for i in range(10): print('%d' % sess.run(ans, feed_dict={x: 2, y: i}))
1
2 4 8 16 32 64 128 256 512