看了老是 记不住, 总结一下,似乎是清晰了不少
简单的前向神经网络
1 输入
输入有两种方案定义, 一是 使用 常量定义一个输入,
x = tf.constant([[0.7, 0.9]])
实际训练和推断时, 输入数据很多,所以使用常量的开销就非常大
所以提供了 第二种 方案, 即 placeholder , 定义一个位置, 需要填充输入数据时, 往 这个位置 填充即可
x = tf.placeholder(tf.float32, shape=(1, 2), name=“input”)
2 权重变量
w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2= tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
3 前向网络
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
注意: x 既可以是 某个常量,也可以是 某个 placeholder
4 建立会话
sess = tf.Session()
5 初始化变量的两种方法
一
init_op = tf.global_variables_initializer() //初始化所有变量
sess.run(init_op)
二
sess.run(w1.initializer)
sess.run(w2.initializer)
6 运行: 将会话 和 网络输出 关联起来
sess.run(y) // 使用常量提供输入
或者
sess.run(y, feed_dict={x: [[0.7,0.9],[0.1,0.4],[0.5,0.8]]}) // 使用placeholder提供输入
完整神经网络样例程序
1 定义权重和输入
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’)
2 定义前向传播过程
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
y = tf.sigmoid(y)
3 定义损失函数和 优化算法
cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0))
+ (1 - y_) * tf.log(tf.clip_by_value(1 - y, 1e-10, 1.0)))
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)
4 获取输入数据
这一步 要么是训练数据 要么 是处于测试目的,构造一些
5 创建一个会话 来 执行 整个训练过程
with tf.Session() as sess:
for i in range(STEPS):
sess.run([train_step, y, y_], feed_dict={x: X[start:end], y_: Y[start:end]})
total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_: Y}) // 这个调用是看当前的损失函数情况
隐含层 Demo
def inference(input_tensor, weights1, biases1, weights2, biases2):
layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)
return tf.matmul(layer1, weights2) + biases2
Tensorflow API
tf.where(tf.greater(y, y_), (y - y_) * loss_more, (y_ - y) * loss_less)
类似 C 语言的 条件表达式, 三个输入
tf.train.exponential_decay(0.1, global_step, 100, 0.96, staircase=True)
指数衰减的学习率
每训练100次, 学习率乘以 0.96
tf.contrib.layers.l2_regularizer(lambda1)(var)
对var 计算正则项,避免 过拟合
tf.train.ExponentialMovingAverage(0.99, step)
滑动平均模型
训练时: 不断保持和 更新 各个 参数 滑动平均值(也就是影子变量)
验证和测试时: 参数(比如权重)的值 使用滑动平均值
变量管理
with tf.variable_scope(“foo”):
v = tf.get_variable(“v”, [1], initializer=tf.constant_initializer(1.0))
在名字为 foo的名字空间内 创建名字为 v 的变量
with tf.variable_scope(“foo”, reuse=True):
此时 tf.get_variable 获取已经创建的变量, 如果不存在,那么报错
with tf.variable_scope(“foo”, reuse=None):
with tf.variable_scope(“foo”, reuse=False):
此时 tf.get_variable 创建新的变量, 如果同名变量存在, 那么报错