安装
https://www.tensorflow.org/install/pip?hl=zh_cn
这里我用的是virtualenv
常量, 张量, 会话, 图
import tensorflow as tf
# 常量
m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.], [2.]])
result = tf.matmul(m1, m2)
with tf.Session() as sess:
print(sess.run(result))
with tf.Session().as_default():
print(result.eval())
sess = tf.Session()
print(sess.run(result))
print(result.eval(session=sess))
sess.close()
变量
变量(tf.Variable
)用于保存和更新神经网络中的参数
变量的声明函数是一个运算, 输出结果是一个张量, 所以变量是一种特殊的张量
变量定义时只是给了初始化方法, 但并未真正运行此方法, 使用前需要线初始化
# 声明
w = tf.Variable([[2, 3],[3, 2]], name='w')
# 赋值
w.assign(w+w)
# 初始化
# 全部初始化, 自动处理
v = tf.Variable([1, 2])
init = tf.global_variables_initializer()
with tf.Session().as_default():
init.run()
print(v.eval())
# 单独
v.initialized_value()
import tensorflow as tf
v = tf.Variable(tf.truncated_normal([2, 4]))
w = tf.Variable(v.initialized_value()*2.0)
init = tf.global_variables_initializer()
with tf.Session().as_default():
init.run()
print(v.eval())
print(w.eval())
-
TensorFlow一些常用随机数生成函数和常数生成函数
前向传播算法
LaTex矩阵
$$ \left\{ \begin{matrix} 1 & 2\\ 2 & 3 \end{matrix} \right\} \tag{1} $$
$\left\{
\begin{matrix}
1 & 2\\
2 & 3\\
\end{matrix}
\right\}$
前向传播算法


其中$W^{(1)}$ 表示第一层节点的参数, $W^{(1)} _{1,1}$ 表示链接$x _1$和$a _{11}$的参数
-
用矩阵运算表示为: $$ W^{(1)} = \left\{ \begin{matrix} W^{(1)} _{1,1} & W^{(1)} _{1,2} & W^{(1)} _{1,3} \\ W^{(1)} _{2,1} & W^{(1)} _{2,2} & W^{(1)} _{2,3} \end{matrix} \right\} \\ \left\{\begin{matrix}a _{11} & a _{12} & a _{13}\end{matrix}\right\} = xW^{(1)} = \left\{ \begin{matrix} x_1 & x_2 \end{matrix} \right\} \left\{ \begin{matrix} W^{(1)} _{1,1} & W^{(1)} _{1,2} & W^{(1)} _{1,3} \\ W^{(1)} _{2,1} & W^{(1)} _{2,2} & W^{(1)} _{2,3} \end{matrix} \right\} \\ \cdots $$
-
TensorFlow程序:
a = tf.matmul(x, w1) y = tf.matmul(a, w2)
反向传播算法
反向传播算法是最常用的神经网络优化算法


每次迭代选取一小部分数据(batch), 然后通过前向传播得到预测结果, 计算预测答案与实际答案之间的差距, 最后基于预测与真实的差距, 反向传播算法会相应更新神经网络参数的值, 使得在这个batch上神经网络模型的预测结果与真实答案更接近
placeholder
迭代中使用的数据如果用常量(tf.constant
)来表示的话, 每个常量都会在计算图中增加以一个节点, 效率低.
应该使用tf.placeholder
来提供输入数据, 其相当定义了一个位置, 其中的数据在程序运行过程中指定
import tensorflow as tf
# 声明一个placeholder
x = tf.placeholder(tf.float32, shape=(1, 2), name="input")
with tf.Session() as sess:
# 调用时提供一个feed_dict给出每一个需要用到的placeholder取值
print(sess.run(x, feed_dict={x:[[1.0, 2.0]]}))
损失函数
损失函数用于刻画预测值与真实值的差距
完整神经网络样例程序
import tensorflow as tf
from numpy.random import RandomState
batch_size = 8
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
x = tf.placeholder(tf.float32, shape=(None, 2), name='x-input')
y_ = tf.placeholder(tf.float32, shape=(None, 1), name='y-input')
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
cross_entropy = -tf.reduce_mean(
y_*tf.log(tf.clip_by_value(y, 1e-10, 1.0))
)
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)
rdm = RandomState(1)
dataset_size = 128
X = rdm.rand(dataset_size, 2)
Y = [[int(x1+x2<1)] for (x1, x2) in X]
with tf.Session() as sess:
init_op = tf.initialize_all_variables()
sess.run(init_op)
print(sess.run(w1))
print(sess.run(w2))
STEPS = 5001
for i in range(STEPS):
start = (i*batch_size)%dataset_size
end = min(start+batch_size, dataset_size)
sess.run(train_step, feed_dict={x: X[start:end], y_:Y[start:end]})
if(i%1000 == 0):
total_cross_entropy = sess.run(
cross_entropy, feed_dict={x:X, y_:Y})
print("{} step(s): {}".format(i, total_cross_entropy))
print("w1=", sess.run(w1))
print("w2=", sess.run(w2))
print("w1*w2", sess.run(tf.matmul(w1, w2)))