地址:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/
代码地址:https://github.com/MorvanZhou/tutorials/tree/master/tensorflowTUT
Tensorflow 6 Session 会话控制 :
Session的两种打开模式
import tensorflow as tf
# create two matrixes
matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1,matrix2)
# method 1
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
# [[12]]
# method 2
with tf.Session() as sess:
result2 = sess.run(product)
print(result2)
# [[12]]
product一开始只是被定义而已,但是在Tensorflow里面,每次都要run才能使它激活运行,
用with的方式使用Session的话,不用手动close
Tensorflow 7 Variable 变量
import tensorflow as tf
state = tf.Variable(0, name='counter')
# 定义常量 one
one = tf.constant(1)
# 定义加法步骤 (注: 此步并没有直接计算)
new_value = tf.add(state, one)
# 将 State 更新成 new_value
update = tf.assign(state, new_value)
必须要进行初始化!!!
init = tf.initialize_all_variables()
若要运行init,依然需要Session激活,若要输出里面的值,也要用sess指针指向
# 如果定义 Variable, 就一定要 initialize
# init = tf.initialize_all_variables() # tf 马上就要废弃这种写法
init = tf.global_variables_initializer() # 替换成这样就好
# 使用 Session
with tf.Session() as sess:
sess.run(init)
for _ in range(3<