本节内容:
- 创建图,启动图
- 变量
- Fetch and Feed
- tensorflow简单示例
import tensorflow as tf m1 = tf.constant([[3,3]]) m2 = tf.constant([[2],[3]]) product = tf.matmul(m1,m2) print(product) Tensor("MatMul_1:0", shape=(1, 1), dtype=int32) sess = tf.Session() result = sess.run(product) print(result) sess.close() #[[15]] with tf.Session() as sess: result = sess.run(product) print(result) #[[15]]
import tensorflow as tf x = tf.Variable([1,2]) a = tf.constant([3,3]) sub = tf.subtract(x,a) add = tf.add(x,sub) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print(sess.run(sub)) print(sess.run(add)) #[-2 -1] #[-1 1]
state = tf.Variable(0,name=\'counter\') new_value = tf.add(state,1) update = tf.assign(state,new_value) init = tf.global_variables_initializer() with tf.Session() as sess: print(sess.run(init)) print(sess.run(state)) for _ in range(5): sess.run(update) print(sess.run(state))
###
None 0 1 2 3 4 5 ###
Fetch:在会话里面同时执行多个op,得到运行的结果
import tensorflow as tf input1 = tf.constant(3.0) input2 = tf.constant(2.0) input3 = tf.constant(5.0) add = tf.add(input2,input3) mul = tf.multiply(input1,add) with tf.Session() as sess: print(sess.run([mul,add])) #[21.0, 7.0]
Feed:便于为操作赋值
import tensorflow as tf input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) out = tf.multiply(input1,input2) with tf.Session() as sess: print(sess.run(out,feed_dict={input1:[2.0],input2:[8.0]})) #[16.]
import tensorflow as tf import numpy as np x_data = np.random.rand(100) y_data = x_data*0.1 + 0.2 b = tf.Variable(0.) k = tf.Variable(0.) y = x_data*k + b loss = tf.reduce_mean(tf.square(y_data-y)) optimizer = tf.train.GradientDescentOptimizer(0.2)#0.2的学习率 train = optimizer.minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(201): sess.run(train) if i%20 == 0: print(i,sess.run([k,b])) ### 0 [0.046911635, 0.097727574] 20 [0.09816256, 0.20087942] 40 [0.0989946, 0.20048131] 60 [0.09944985, 0.20026337] 80 [0.09969897, 0.20014411] 100 [0.099835284, 0.20007886] 120 [0.09990986, 0.20004314] 140 [0.09995068, 0.2000236] 160 [0.099973015, 0.20001292] 180 [0.09998523, 0.20000707] 200 [0.09999191, 0.20000388] ###