模块化的神经网络八股实践
模块的神经网络八股实践基本上分为三步:1.生成数据集。2.钱箱传播模块。3.反向传播模块。这三个模块中每个模块分割为一个文件。如下的一个例子。数据集为GeneralDatas.py 前项传播模块为forward.py 反向传播为backward.py
#coding=utf-8
#GeneralDatas.py
# 用 300 x个符合正态分布的点 X[x0, x1]作为数据集,根据点 X[x0, x1]计算生成标注 Y_,将数据集
# 标注为红色点和蓝色点。
# 标注规则为:当 x0^2 + x1^2 < 2 时,y_=1,标注为红色;当 x0^2 + x1^2 ≥ 2 时,y_=0,标注为蓝色。
import numpy as np
import matplotlib.pyplot as plt
BATCH_SIZE=30
seed = 2
def generalData():
#基于seed产生随机数
rdm = np.random.RandomState(seed)
#随机数返回300行2列的矩阵,表示
X = rdm.randn(300,2)
#从这个300行2列的矩阵中取出一行,判断如果两个坐标的平方和小于2,给Y值赋值为1,其余赋值为0
#Y_作为输入数据集的标签(正确答案)
Y_ = [int(x0*x0 + x1*x1 < 2) for (x0,x1) in X]
#遍历Y中的每个元素,1赋值red,其余赋值为blue,这样就可以可视化的显示人可以直观的得到区分
Y_C = [['red' if y else 'blue'] for y in Y_]
#对数据集X和Y进行Shape整理,第一个元素为-1表示,随第二个参数计算得到,第二个元素表述n行多少列,把X整理为n行2列的,把Y整理为n行1列的
X = np.vstack(X).reshape(-1,2)
Y_ = np.vstack(Y_).reshape(-1,1)
# print X
# print Y_
# print Y_C
#用plt.scatter画出数据集X各行中的0列元素和第一列的元素点,即(X0,X1),用各行Y_C对应的值标识颜色
# plt.scatter(X[:,0],X[:,1],c = np.squeeze(Y_C))
# plt.show()
return X,Y_,Y_C
if __name__ == '__main__':
generalData()
#coding=utf-8
#forward.py
import tensorflow as tf
#定义神经网络的输入
def get_weight(shape,regularizer):
w = tf.Variable(tf.random_normal(shape),dtype=tf.float32)
tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))
return w
def get_bias(shape):
b = tf.Variable(tf.constant(0.01,shape=shape))
return b
def forward(x,regularizer):
w1 = get_weight([2,11],regularizer)
b1 = get_bias([11])
y1 = tf.nn.relu(tf.matmul(x,w1) + b1)
w2 = get_weight([11,1],regularizer)
b2 = get_bias([1])
y = tf.matmul(y1,w2) + b2
return y
#coding=utf-8
#backword.py
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import GeneralDatas
import forward as FW
STEPS = 40000
BATCH_SIZE = 30
LEARNING_RATE_BASE=0.001
LEARNING_RATE_DECAY=0.999
REGULARIZER = 0.01
def backword():
x = tf.placeholder(tf.float32,shape=(None,2))
y_ = tf.placeholder(tf.float32,shape=(None,1))
X,Y_,Y_C = GeneralDatas.generalData()
print X
print Y_
print Y_C
y = FW.forward(x,REGULARIZER)
global_step = tf.Variable(0,trainable=False)
learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,global_step,300/BATCH_SIZE,LEARNING_RATE_DECAY,staircase=True)
loss_mse = tf.reduce_mean(tf.square(y-y_))
loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))
#定义反向传播方法:包含正则化的
train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total)
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
for i in range(STEPS):
start = (i * BATCH_SIZE) % 300
end = start + BATCH_SIZE
sess.run(train_step,feed_dict={x:X[start:end],y_:Y_[start:end]})
if i % 2000 == 0:
loss_v = sess.run(loss_total,feed_dict={x:X,y_:Y_})
print "After %d steps ,loss is:%f"%(i,loss_v)
xx,yy = np.mgrid[-3:3:0.01,-3:3:0.01]
grid = np.c_[xx.ravel(),yy.ravel()]
probs = sess.run(y,feed_dict={x:grid})
probs = probs.reshape(xx.shape)
plt.scatter(X[:,0],X[:,1],c=np.squeeze(Y_C))
plt.contour(xx,yy,probs,levels=[0.5])
plt.show()
if __name__ == '__main__':
backword()
每一个模块都是一个文件所描述,最终运行backward.py后产生的结果为一张图片中,用线连接起来红点和蓝点的分界线。可以自行运行代码所展示。