简单神经网络train and test详解(双层)
【 The latest data : 2018/05/01 】Yuchen
1. NN模型如下
神经网络整体架构内容可参考之前的云笔记《06_神经网络整体架构》
http://note.youdao.com/noteshare?id=2c27bbf6625d75e4173d9fcbeea5e8c1&sub=7F4BC70112524F9289531EC6AE435E14
其中,
n是指的样本数
Mnist数据集 784是28×28×1 灰度图 channel = 1
wb是指的权重参数
输出的是10分类的得分值,也可以接softmax分类器
out是L2层和输出层之间的关系
256 128 10是指的神经元数量
2. 构造参数
函数构造
3. Code
1. 网络模型架构搭建
导入相应数据
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import input_data
mnist = input_data.read_data_sets('data/', one_hot=True)
network topologies
# 网络拓扑 network topologies
# layer中神经元数量
n_hidden_1 =256
n_hidden_2 =128
# 输入数据的像素点 28x28x1
n_input =784
# 10分类
n_classes =10
input and output
x = tf.placeholder("float",[None,n_input])
y = tf.placeholder("float",[None,n_classes])
network parameters
# network parameters
# 方差
stddev =0.1
# random_normal 高斯初始化
weights ={
'w1': tf.Variable(tf.random_normal([n_input,n_hidden_1],stddev=stddev)),
'w2': tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2],stddev=stddev)),
'out': tf.Variable(tf.random_normal([n_hidden_2,n_classes],stddev=stddev))
}
# 对于 b 零值初始化也可以
biases ={
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
print("Network Ready")
output
NetworkReady
可以看到网络模型架构搭建成功
2.训练网络模型
定义前向传播函数
# 定义前向传播函数
def multilayer_perceptron(_X, _weights, _biases):
# 之所以加 sigmoid 是因为每一个 hidden layer 都有一个非线性函数
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1']))
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weights['w2']), _biases['b2']))
return(tf.matmul(layer_2, _weights['out'])+ _biases['out'])
反向传播
(1)将前向传播预测值
# prediction
pred = multilayer_perceptron(x, weights, biases)
(2)定义损失函数
# 首先定义损失函数 softmax_cross_entropy_with_logits 交叉熵函数
# 交叉熵函数的输入有 pred : 网络的预测值 (前向传播的结果)
# y : 实际的label值
# 将两参数的一系列的比较结果,除以 batch 求平均之后的 loss 返回给 cost 损失值
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
(3)梯度下降最优化
optm = tf.train.GradientDescentOptimizer(learning_rate =0.001).minimize(cost)
(4)精确值
具体解释详见上一篇笔记《06_迭代完成逻辑回归模型》
corr = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accr = tf.reduce_mean(tf.cast(corr,"float"))
(5)初始化
# initializer
init = tf.global_variables_initializer()
print("Function ready")
output
Function ready
可以看出传播中的参数和优化模型搭建成功
3. Train and Test
training_epochs =20
# 每次 iteration 的样本
batch_size =100
# 每四个 epoch 打印一次结果
display_step =4
# lanch the graph
sess = tf.Session()
sess.run(init)
# optimize
for epoch in range(training_epochs):
# 初始,平均 loss = 0
avg_cost =0
total_batch =int(mnist.train.num_examples/batch_size)
# iteration
for i in range(total_batch):
# 通过 next_batch 返回相应的 batch_xs,batch_ys
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
feeds ={x: batch_xs, y: batch_ys}
sess.run(optm, feed_dict = feeds)
avg_cost += sess.run(cost, feed_dict = feeds)
avg_cost = avg_cost / total_batch
# display
if(epoch+1)% display_step ==0:
print("Epoch: %03d/%03d cost: %.9f "%(epoch, training_epochs, avg_cost))
feeds ={x: batch_xs, y: batch_ys}
train_acc = sess.run(accr, feed_dict = feeds)
print("train accuracy: %.3f"%(train_acc))
feeds ={x: mnist.test.images, y: mnist.test.labels}
test_acc = sess.run(accr, feed_dict = feeds)
print("test accuracy: %.3f"%(test_acc))
print("optimization finished")
output
Epoch:003/020 cost:2.273774184
train accuracy:0.250
test accuracy:0.197
Epoch:007/020 cost:2.240329206
train accuracy:0.270
test accuracy:0.311
Epoch:011/020 cost:2.203503076
train accuracy:0.370
test accuracy:0.404
Epoch:015/020 cost:2.161286944
train accuracy:0.490
test accuracy:0.492
Epoch:019/020 cost:2.111541148
train accuracy:0.410
test accuracy:0.534
optimization finished
20个batch每个batch 100个样本,每隔4个batch打印一次
处理器:Intel Core i5-6200U CPU @ 2.30GHz 2.04GHz
04 epoch:train+test, cost_time: 25’40”
08 epoch:train+test, cost_time: 50’29”
12 epoch:train+test, cost_time: 74’42”
16 epoch:train+test, cost_time: 98’63”
20 epoch:train+test, cost_time: 121’49”
想要更完整代码或者跟作者交流,请留言头条号。加入我们的社群。



4000520066 欢迎批评指正
All Rights Reserved 新浪公司 版权所有