基础¶
Session¶
Session的运行方式¶
import tensorflow as tf
matrix1 = tf.constant([[3, 3]])
matrix2 = tf.constant([[2],
[2]])
# matrix multiply np.dot(m1, m2)
product = tf.matmul(matrix1, matrix2)
# # 运行会话的方式
# # method 1
# sess = tf.Session()
# result = sess.run(product)
# print(result)
# sess.close()
# method 2
with tf.Session() as sess:
# 会话每run一次, 运行一次
result2 = sess.run(product)
print(result2)
Variable¶
import tensorflow as tf
state = tf.Variable(0, name='counter')
# print(state.name)
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
# 如果有定义变量, 就必须使用如下语句, 并且如下使用 sess.run(init) 进行初始化
# init = tf.initialize_all_variables() , 后续版本要求使用 tf.global_variables_initializer() 代替
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))
placeholder¶
占位符, 运行的时候, 再传入输入的值
import tensorflow as tf
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
print(sess.run(output, feed_dict={input1: [7.], input2: [2.]}))