张量(Tensor):
张量有多种. 零阶张量为 纯量或标量 (scalar) 也就是一个数值. 比如 [1]
一阶张量为 向量 (vector), 比如 一维的 [1, 2, 3]
二阶张量为 矩阵 (matrix), 比如 二维的 [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
以此类推, 还有 三阶 三维的 …
Tensorflow过程
Tensorflow 首先要定义神经网络的结构, 然后再把数据放入结构当中去运算和 training.
因为TensorFlow是采用数据流图(data flow graphs)来计算, 所以首先我们得创建一个数据流流图, 然后再将我们的数据(数据以张量(tensor)的形式存在)放在数据流图中计算. 节点(Nodes)在图中表示数学操作,图中的线(edges)则表示在节点间相互联系的多维数据数组, 即张量(tensor). 训练模型时tensor会不断的从数据流图中的一个节点flow到另一节点, 这就是TensorFlow名字的由来.
Session控制
Session
是 Tensorflow 为了控制,和输出文件的执行的语句. 运行 session.run()
可以获得你要得知的运算结果, 或者是你所要运算的部分.
import tensorflow as tf
# create two matrixes
matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1,matrix2)
因为 product
不是直接计算的步骤, 所以我们会要使用 Session
来激活 product
并得到计算结果. 有两种形式使用会话控制 Session
。
# method 1
sess = tf.Session()
result = sess.run(product)
# [[12]]
# method 2
with tf.Session() as sess:
result = sess.run(product)
# [[12]]
Variable变量
用 tf.Variable
定义变量,与python不同的是,必须先定义它是一个变量,它才是一个变量。
定义语法: state = tf.Variable()
初始值为0,还可以给它一个名字 counter:
state = tf.Variable(0, name='counter')
将 new_value 加载到 state 上,counter就被更新:
update = tf.assign(state, new_value)
完整变量:
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()
.
到这里变量还是没有被激活,需要再在 sess
里, sess.run(init)
, 激活 init
这一步.
# 如果定义 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):
sess.run(update)
print(sess.run(state))
注意:直接 print(state)
不起作用!!
一定要把 sess
的指针指向 state
再进行 print
才能得到想要的结果!
placeholder
placeholder
是 Tensorflow 中的占位符,暂时储存变量.从外部传入数据。
传输数据形式sess.run(***, feed_dict={input: **}).
import tensorflow as tf
#在 Tensorflow 中需要定义 placeholder 的 type ,一般为 float32 形式
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
# mul = multiply 是将input1和input2 做乘法运算,并输出为 output
ouput = tf.multiply(input1, input2)
传值的工作交给了 sess.run()
, 需要传入的值放在了feed_dict={}
并一一对应每一个 input
. placeholder
与 feed_dict={}
是绑定在一起出现的。
with tf.Session() as sess:
print(sess.run(ouput, feed_dict={input1: [7.], input2: [2.]}))
# [ 14.]