搭建一个简单的神经网络

”’def add_layer():最基础的四个参数:输入值,输入的大小,输出的大小和激励函数,激励函数可以自己添加,也可以不使用激励函数。”’

def add_layer(inputs,in_size,out_size,activation_function=None):

接下来我们定义weight和biases

weight=tf.Variable(tf.random_normal([in_size,out_size]))
'''如果在前向传播中,需要对weigjt加入正则化,可以这么表示
w=tf.Variable(tf.random_normal([shape],dtpye=tf.float32))
tf.add_to_collection(losses'.tf.contrib.layer.l2_regularizer(regularizer)(w))#给每个W加一个权重,可以减小误差,防止过拟合,regulaizer表示数字'''
biases=tf.Variable(tf.zero[1,out_size]+0.1)

机器学习中biases的值不推荐为0

Wx_plus_b=tf.matmul(iinput,weight)+biases
if activation_function is None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
return putputs

#搭建好一个普通的神经网络后,我们先构建好我们的train data,本次的traindata使用的是莫烦构建的数据集,构建好的x与y并不是严格的一元二次的函数关系,看起来更加真实

x_data=np.linspace’(-1,1,300,dtype=tf.float32)[;,np.newaxis]
noise=tf.random_normal([x_data.shape],dtype=tf.float32)
y_data=np.square(x_data)-0.5+noise

#我们使用占位符来表示我们神经网络的输入和输出
xs=tf.placeholder(tf.float32,[None,1])
#参数输入的格式为tf.float32,和数据的格式,None表示输入多少都可以,因为只有一个特征,所以是1
ys=tf.placeholder(tf.float32,[None,1])

'''一般计算神经网络的层数都是从隐藏层+输出层,输入层一般表示一组数据或者一组图片之类的东西'''
l=add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction=add_layer(l1,10,1,activatin_function=None)

#计算损失函数
loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))

train_step=tf.train.GradientDescentOptimizer(0.1).minmize(loss)

#对变量的初始化

init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
step=1000#我们把训练步数设置为1000
for i in range(step):
sess.run(train_stpe,feed_dict={xs:x_data,ys_y_data})
if i%50==0:
print(sess.run(loss,feed_dict={xs:x_data,ys_y_data}))
#根据我的观察,哪里用到了xs与ys,哪里就需要feed喂一下数据

总结:这是一个最普通的神经网络,其中数据都是自己生成的,如果需要优化的话,loss的学习率可以用指数衰减学习率(学习率随着训练轮数变化而动态更新)以及正则化的方法来防止过拟合现象的发生

猜你喜欢

转载自blog.csdn.net/hanrui4721960/article/details/80700743
今日推荐