Session
会话持有并管理tensorflow程序运行时的所有资源
session 是 Tensorflow 为了控制,和输出文件的执行的语句. 运行 session.run() 可以获得你要得知的运算结果。
import tensorflow as tf
import numpy as np
#定义常量矩阵
matrix1 = tf.constant([[3, 4]])
matrix2 = tf.constant([[5], [5]])
result = tf.matmul(matrix1,matrix2)
#使用上下文管理器方式不需要写sess.close()函数
with tf.Session() as sess:
print(sess.run(result))
Variable
import tensorflow as tf
import numpy as np
#定义变量和常量
state = tf.Variable(0, name='counter')
one = tf.constant(1)
# 定义加法步骤 (注: 此步并没有直接计算)
new_value = tf.add(one, state)
# 将 State 更新成 new_value
update = tf.assign(state, new_value)
#激活所有变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))
#输出:
#1
#2
#3
PlaceHolder
placeholder 是 Tensorflow 中的占位符,暂时储存变量.
Tensorflow 如果想要从外部传入data, 那就需要用到 tf.placeholder(), 然后以这种形式传输数据 sess.run(***, feed_dict={input: **}).
需要传入的值放在了feed_dict={} 并一一对应每一个 input. placeholder 与 feed_dict={} 是绑定在一起出现的。
Tensorflow 如果想要从外部传入data, 那就需要用到 tf.placeholder(), 然后以这种形式传输数据 sess.run(***, feed_dict={input: **}).
需要传入的值放在了feed_dict={} 并一一对应每一个 input. placeholder 与 feed_dict={} 是绑定在一起出现的。
import tensorflow as tf
#需要定义placeholder的type,一般为float32
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: [8.]}))
56.
import tensorflow as tf
#需要定义placeholder的type,一般为float32
input1 = tf.placeholder(tf.float32, [2, 2])
input2 = tf.placeholder(tf.float32, [2, 2])
output = tf.multiply(input1, input2)
with tf.Session() as sess:
print(sess.run(output, feed_dict={input1: [[1, 2], [3, 4]], input2: [[2, 9], [5, 6]]}))
[[ 2. 18.]
[ 15. 24.]]