前言
刚入手深度学习,结合这几天看的视频与内容,将其整合成文章
提示:以下是本篇文章正文内容,下面案例可供参考
一、隐藏层函数
生成隐藏层函数 1.权重W,2.偏执b 3.激活函数。隐藏层输出为activate_function(wx+b)
def add_layer(inputs,in_size,out_size,activation_function=None):
Weights = tf.Variable(tf.random_normal(shape=[in_size,out_size]))
biases = tf.Variable(tf.zeros([1,out_size])+0.1)
Wx_b = tf.matmul(tf.cast(inputs,tf.float32),Weights)+biases
if activation_function==None:
outputs=Wx_b
else:
outputs = activation_function(Wx_b)
return outputs
二、生成二次函数与交叉损失函数
1.二次函数
代码如下(示例):
x_data = np.linspace(-1,1,300)[:,np.newaxis]
#在(-1,1)之间生成300个数据点,[300,1]
noise = np.random.normal(0,0.02,x_data.shape)
#利用np库 均值为0,方差为0.05 与x_data的大小相同
y_data = np.square(x_data)-0.5+noise
2.交叉损失函数
代码如下(示例)
在此过程中,如果你使用的是Tensorflow2.0需要将函数进行相应的变换
#定义占位符,更好的进行训练 定义shape 与 dtype
xs = tf.placeholder(shape=[None,1],dtype=tf.float32)
ys = tf.placeholder(shape=[None,1],dtype=tf.float32)
#添加隐藏层 和输出层
#l1 = add_layer(xs,1,10,activation_function=tf.nn.relu)
l1 = add_layer(xs,1,10,activation_function=tf.nn.sigmoid)
#print('l1:',l1)
prediction = add_layer(l1,10,1,activation_function=None)
#定义损失函数 按列求和 利用梯度下降算法使得loss最小
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
#train_step = train_step.minimize(loss)
三、训练数据与画图
在此过程中:1需要对变量进行激活,并对网络进行初始化
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
2.利用matplotlib库画图
fig =plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x_data,y_data)
plt.ion()
plt.show()
3,.训练与动态画图
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
fig =plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x_data,y_data)
plt.ion()
plt.show()
#进行训练
for i in range(2001):
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i%50==0:
print('step:',i,sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
#ax.lines.remove(lines[0])
try:
ax.lines.remove(lines[0])
except Exception:
pass
#先抹除再划线
prediction_value = sess.run(prediction,feed_dict={xs:x_data})
lines = ax.plot(x_data,prediction_value,'r-',lw=5)
#ax.lines.remove(lines[0])
plt.pause(0.2)
总结
本人还是一个新手,需要大家一起努力共同学习。