import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
"""
1.改变初始化的方式
采用的是MSRA初始化:服从动态方差的独立高斯分布(0,np.sqrt(2/n)),
n代表的就是前一层的输入的节点。
如果采用全0的初始化,又用relu函数激活会导制准确率很低大概10%左右(具体解释根据反向传播)
"""
def get_weight(shape, stddev):
return tf.Variable(tf.truncated_normal(shape=shape, stddev=stddev, mean=0, seed=1))
def get_bias(shape):
return tf.Variable(tf.constant(0.01, shape=shape))
"""
2.激活函数
relu函数更利于反向传播
"""
def activation(x):
return tf.nn.relu(x)
"""
3.改变隐层的数量
第一个隐层的神经元的个数和输入的维数差不多
第二个隐层根据具体的情况而定。
"""
def forward(x):
w_1 = get_weight([784, 100], np.sqrt(2/784))
b_1 = get_bias([100])
y_1 = activation(tf.matmul(x, w_1)+ b_1)
w_2 = get_weight([100, 10], np.sqrt(2/100))
b_2 = get_bias([10])
y_2 = tf.matmul(y_1, w_2)+b_2
return w_1, w_2, y_2
def backward():
init_learning_rate = 1e-2
data_dir = "./mnist/input_data"
mnist = input_data.read_data_sets(data_dir, one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
w_1,w_2,y_2 = forward(x)
# div就是求两个数的商
epoch_steps = tf.to_int64(tf.div(60000, tf.shape(x)[0]))
# 记录当前共运行了多少轮
global_step = tf.train.get_or_create_global_step()
current_epoch = global_step//epoch_steps
decay_times
搭建神经网络之手写体识别
最新推荐文章于 2024-11-02 22:27:28 发布