环境:Win10下ANACONDA3,py3.6,TF1.2.1
TF基本组成:
- Tensor
- Constant
- Session
- Placeholder
- Variable
Tensor
TensorFlow 程序使用 tensor 数据结构来代表所有的数据, 操作间传递的数据都是 tensor.
一个tensor 看作是一个 n 维的数组或列表. 一个 tensor 包含一个静态类型 rank, 和 一个 shape.
Constant
常量,像下面这样可以创建常量矩阵tensor
import tensorflow as tf
m1 = tf.constant([[2, 2]])
m2 = tf.constant([[3],
[3]])
Session
dot_operation = tf.matmul(m1, m2)
tensorflow中,要做一个矩阵乘法,不会在像上面这样写完之后变直接成返回值
此时dot_operation是不能当作一个变量使用的,它是一个节点,待启动
sess = tf.Session()
result = sess.run(dot_operation)
print(result)
sess.close()
如上创建一个会话之后,使用 run(dot_operation) 才会启动dot_operation节点执行运算并返回计算值
session(会话)使用完后记得使用 close() 释放,若不想释放可以用with使用:
with tf.Session() as sess:
result_ = sess.run(dot_operation)
print(result_)
Placeholder
使用占位符,可以让你在创建节点时不用输入确定tensor
在使用会话启动节点时给进参数
import tensorflow as tf
x1 = tf.placeholder(dtype=tf.float32, shape=None)
y1 = tf.placeholder(dtype=tf.float32, shape=None)
z1 = x1 + y1
x2 = tf.placeholder(dtype=tf.float32, shape=[2, 1])
y2 = tf.placeholder(dtype=tf.float32, shape=[1, 2])
z2 = tf.matmul(x2, y2)
with tf.Session() as sess:
z1_value, z2_value = sess.run(
[z1, z2], # run them together
feed_dict={
x1: 1, y1: 2,
x2: [[2], [2]], y2: [[3, 3]]
})
print(z1_value)
print(z2_value)
Variable
使用TF时,每个tensor可以是变量,需像下面这样定义
import tensorflow as tf
var = tf.Variable(0) #创建变量var
add_operation = tf.add(var, 1) #加法节点
update_operation = tf.assign(var, add_operation) #赋值节点
变量要经过初始化才能使用
with tf.Session() as sess:
# 经过初始化之后才能使用
sess.run(tf.global_variables_initializer())
for _ in range(3):
sess.run(update_operation)
print(sess.run(var))