import torch
x1, x2 = torch.Tensor([0.5]), torch.Tensor([0.3])
y1, y2 = torch.Tensor([0.23]), torch.Tensor([-0.07])
print("=====输入值:x1, x2;真实输出值:y1, y2=====")
print(x1, x2, y1, y2)
w1, w2, w3, w4, w5, w6, w7, w8 = torch.Tensor([0.2]), torch.Tensor([-0.4]), torch.Tensor([0.5]), torch.Tensor(
[0.6]), torch.Tensor([0.1]), torch.Tensor([-0.5]), torch.Tensor([-0.3]), torch.Tensor([0.8]) # 权重初始值
w1.requires_grad = True
w2.requires_grad = True
w3.requires_grad = True
w4.requires_grad = True
w5.requires_grad = True
w6.requires_grad = True
w7.requires_grad = True
w8.requires_grad = True
def sigmoid(z):
a = 1 / (1 + torch.exp(-z))
return a
def forward_propagate(x1, x2):
in_h1 = w1 * x1 + w3 * x2
out_h1 = sigmoid(in_h1) # out_h1 = torch.sigmoid(in_h1)
in_h2 = w2 * x1 + w4 * x2
out_h2 = sigmoid(in_h2) # out_h2 = torch.sigmoid(in_h2)
in_o1 = w5 * out_h1 + w7 * out_h2
out_o1 = sigmoid(in_o1) # out_o1 = torch.sigmoid(in_o1)
in_o2 = w6 * out_h1 + w8 * out_h2
out_o2 = sigmoid(in_o2) # out_o2 = torch.sigmoid(in_o2)
print("正向计算:o1 ,o2")
print(out_o1.data, out_o2.data)
return out_o1, out_o2
def loss_fuction(x1, x2, y1, y2): # 损失函数
y1_pred, y2_pred = forward_propagate(x1, x2) # 前向传播
loss = (1 / 2) * (y1_pred - y1) ** 2 + (1 / 2) * (y2_pred - y2) ** 2 # 考虑 : t.nn.MSELoss()
print("损失函数(均方误差):", loss.item())
return loss
def update_w(w1, w2, w3, w4, w5, w6, w7, w8):
# 步长
step = 1
w1.data = w1.data - step * w1.grad.data
w2.data = w2.data - step * w2.grad.data
w3.data = w3.data - step * w3.grad.data
w4.data = w4.data - step * w4.grad.data
w5.data = w5.data - step * w5.grad.data
w6.data = w6.data - step * w6.grad.data
w7.data = w7.data - step * w7.grad.data
w8.data = w8.data - step * w8.grad.data
w1.grad.data.zero_() # 注意:将w中所有梯度清零
w2.grad.data.zero_()
w3.grad.data.zero_()
w4.grad.data.zero_()
w5.grad.data.zero_()
w6.grad.data.zero_()
w7.grad.data.zero_()
w8.grad.data.zero_()
return w1, w2, w3, w4, w5, w6, w7, w8
if __name__ == "__main__":
print("=====更新前的权值=====")
print(w1.data, w2.data, w3.data, w4.data, w5.data, w6.data, w7.data, w8.data)
for i in range(1):
print("=====第" + str(i) + "轮=====")
L = loss_fuction(x1, x2, y1, y2) # 前向传播,求 Loss,构建计算图
L.backward() # 自动求梯度,不需要人工编程实现。反向传播,求出计算图中所有梯度存入w中
print("tgrad W: ", round(w1.grad.item(), 2), round(w2.grad.item(), 2), round(w3.grad.item(), 2),
round(w4.grad.item(), 2), round(w5.grad.item(), 2), round(w6.grad.item(), 2), round(w7.grad.item(), 2),
round(w8.grad.item(), 2))
w1, w2, w3, w4, w5, w6, w7, w8 = update_w(w1, w2, w3, w4, w5, w6, w7, w8)
print("更新后的权值")
print(w1.data, w2.data, w3.data, w4.data, w5.data, w6.data, w7.data, w8.data)
运行结果(10轮):
====第9轮===== 正向计算:o1 ,o2 tensor([0.4047]) tensor([0.3507]) 损失函数(均方误差): 0.10375461727380753 grad W: -0.02 -0.0 -0.01 -0.0 0.02 0.06 0.02 0.05 更新后的权值 tensor([0.3425]) tensor([-0.4540]) tensor([0.5855]) tensor([0.5676]) tensor([-0.2230]) tensor([-1.2686]) tensor([-0.5765]) tensor([0.1418]) Process finished with exit code 0二、对比【作业3】和【作业2】的程序,观察两种方法结果是否相同?如果不同,哪个正确?
两种方法结果不同,作业三PyTorch版正确。
三、【作业2】程序更新(保留【作业2中】的错误答案,留作对比。新程序到作业3。)【作业二】结果:
【作业三】结果:
【作业二】修改后代码:
import numpy as np
def sigmoid(z):
a = 1 / (1 + np.exp(-z))
return a
def forward_propagate(x1, x2, y1, y2, w1, w2, w3, w4, w5, w6, w7, w8):
in_h1 = w1 * x1 + w3 * x2
out_h1 = sigmoid(in_h1)
in_h2 = w2 * x1 + w4 * x2
out_h2 = sigmoid(in_h2)
in_o1 = w5 * out_h1 + w7 * out_h2
out_o1 = sigmoid(in_o1)
in_o2 = w6 * out_h1 + w8 * out_h2
out_o2 = sigmoid(in_o2)
print("正向计算:o1 ,o2")
print(round(out_o1, 5), round(out_o2, 5))
error = (1 / 2) * (out_o1 - y1) ** 2 + (1 / 2) * (out_o2 - y2) ** 2
print("损失函数:均方误差")
print(round(error, 5))
return out_o1, out_o2, out_h1, out_h2
def back_propagate(out_o1, out_o2, out_h1, out_h2):
# 反向传播
d_o1 = out_o1 - y1
d_o2 = out_o2 - y2
# print(round(d_o1, 2), round(d_o2, 2))
d_w5 = d_o1 * out_o1 * (1 - out_o1) * out_h1
d_w7 = d_o1 * out_o1 * (1 - out_o1) * out_h2
# print(round(d_w5, 2), round(d_w7, 2))
d_w6 = d_o2 * out_o2 * (1 - out_o2) * out_h1
d_w8 = d_o2 * out_o2 * (1 - out_o2) * out_h2
# print(round(d_w6, 2), round(d_w8, 2))
d_w1 = (d_w5 + d_w6) * out_h1 * (1 - out_h1) * x1
d_w3 = (d_w5 + d_w6) * out_h1 * (1 - out_h1) * x2
# print(round(d_w1, 2), round(d_w3, 2))
d_w2 = (d_w7 + d_w8) * out_h2 * (1 - out_h2) * x1
d_w4 = (d_w7 + d_w8) * out_h2 * (1 - out_h2) * x2
# print(round(d_w2, 2), round(d_w4, 2))
print("反向传播:误差传给每个权值")
print(round(d_w1, 5), round(d_w2, 5), round(d_w3, 5), round(d_w4, 5), round(d_w5, 5), round(d_w6, 5),
round(d_w7, 5), round(d_w8, 5))
return d_w1, d_w2, d_w3, d_w4, d_w5, d_w6, d_w7, d_w8
def update_w(w1, w2, w3, w4, w5, w6, w7, w8):
# 步长
step = 5
w1 = w1 - step * d_w1
w2 = w2 - step * d_w2
w3 = w3 - step * d_w3
w4 = w4 - step * d_w4
w5 = w5 - step * d_w5
w6 = w6 - step * d_w6
w7 = w7 - step * d_w7
w8 = w8 - step * d_w8
return w1, w2, w3, w4, w5, w6, w7, w8
if __name__ == "__main__":
w1, w2, w3, w4, w5, w6, w7, w8 = 0.2, -0.4, 0.5, 0.6, 0.1, -0.5, -0.3, 0.8
x1, x2 = 0.5, 0.3
y1, y2 = 0.23, -0.07
print("=====输入值:x1, x2;真实输出值:y1, y2=====")
print(x1, x2, y1, y2)
print("=====更新前的权值=====")
print(round(w1, 2), round(w2, 2), round(w3, 2), round(w4, 2), round(w5, 2), round(w6, 2), round(w7, 2),
round(w8, 2))
for i in range(1000):
print("=====第" + str(i) + "轮=====")
out_o1, out_o2, out_h1, out_h2 = forward_propagate(x1, x2, y1, y2, w1, w2, w3, w4, w5, w6, w7, w8)
d_w1, d_w2, d_w3, d_w4, d_w5, d_w6, d_w7, d_w8 = back_propagate(out_o1, out_o2, out_h1, out_h2)
w1, w2, w3, w4, w5, w6, w7, w8 = update_w(w1, w2, w3, w4, w5, w6, w7, w8)
print("更新后的权值")
print(round(w1, 2), round(w2, 2), round(w3, 2), round(w4, 2), round(w5, 2), round(w6, 2), round(w7, 2),
round(w8, 2))
【作业二】修改后结果:
四、对比【作业2】与【作业3】的反向传播的实现方法。总结并陈述。
【作业二】链式法则手动计算反向传播过程中各参数梯度
【作业三】利用PyTorch包含的Tensor数据结构,梯度可以自动进行计算,效率比链式求导高很多。
五、激活函数Sigmoid用PyTorch自带函数torch.sigmoid(),观察、总结并陈述。Sigmoid函数公式:
,相应的
图形为:
替换后函数:
def forward_propagate(x1, x2):
in_h1 = w1 * x1 + w3 * x2
out_h1 = torch.sigmoid(in_h1)
in_h2 = w2 * x1 + w4 * x2
out_h2 = torch.sigmoid(in_h2)
in_o1 = w5 * out_h1 + w7 * out_h2
out_o1 = torch.sigmoid(in_o1)
in_o2 = w6 * out_h1 + w8 * out_h2
out_o2 = torch.sigmoid(in_o2)
print("正向计算:o1 ,o2")
print(out_o1.data, out_o2.data)
return out_o1, out_o2
结果:
正向计算:o1 ,o2 tensor([0.4047]) tensor([0.3507]) 损失函数(均方误差): 0.10375461727380753 grad W: -0.02 -0.0 -0.01 -0.0 0.02 0.06 0.02 0.05 更新后的权值 tensor([0.3425]) tensor([-0.4540]) tensor([0.5855]) tensor([0.5676]) tensor([-0.2230]) tensor([-1.2686]) tensor([-0.5765]) tensor([0.1418]) Process finished with exit code 0
Sigmoid函数的优点: Sigmoid的取值范围在(0, 1),而且是单调递增,比较容易优化. Sigmoid求导比较容易,可以直接推导得出。
Sigmoid函数的缺点:计算量大,容易产生梯度消失,对于深度网络训练不太适合。
六、激活函数Sigmoid改变为Relu,观察、总结并陈述。Relu公式如下:
0) & end{matrix}right." src="https://private.codecogs.com/gif.latex?f%28x%29%3Dmax%280%2C%20x%29%3D%5Cleft%5C%7B%5Cbegin%7Bmatrix%7D%200%20%26%20%28x%20%5Cleqslant%200%29%26%20%5C%5C%20x%20%26%20%28x%20%3E%200%29%20%26%20%5Cend%7Bmatrix%7D%5Cright." />
图形图像:
替换后:
def forward_propagate(x1, x2):
in_h1 = w1 * x1 + w3 * x2
out_h1 = torch.relu(in_h1)
in_h2 = w2 * x1 + w4 * x2
out_h2 = torch.relu(in_h2)
in_o1 = w5 * out_h1 + w7 * out_h2
out_o1 = torch.relu(in_o1)
in_o2 = w6 * out_h1 + w8 * out_h2
out_o2 = torch.relu(in_o2)
print("正向计算:o1 ,o2")
print(out_o1.data, out_o2.data)
return out_o1, out_o2
结果:
正向计算:o1 ,o2 tensor([0.1807]) tensor([0.]) 损失函数(均方误差): 0.0036630069371312857 grad W: -0.01 0.0 -0.01 0.0 -0.02 0.0 0.0 0.0 更新后的权值 tensor([0.3877]) tensor([-0.4000]) tensor([0.6126]) tensor([0.6000]) tensor([0.5074]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000]) Process finished with exit code 0
Relu函数的优点:有效的缓解了梯度消失问题, 对神经网络可以使用稀疏表达,对于无监督学习,也能获得很好的效果
Relu函数的缺点:在训练过程中容易出现神经元失望,之后梯度永远为0的情况。比如一个特别大的梯度结果神经元之后,我们调整权重参数,就会造成这个ReLU神经元对后来来的输入永远都不会被激活,这个神经元的梯度永远都会是0,造成不可逆的死亡。
七、损失函数MSE用PyTorch自带函数 t.nn.MSELoss()替代,观察、总结并陈述。MSE是逐元素计算的,计算公式为:
替换后:
def loss_fuction(x1, x2, y1, y2): # 损失函数
y1_pred, y2_pred = forward_propagate(x1, x2) # 前向传播
loss_f = torch.nn.MSELoss()
y_pred = torch.cat((y1_pred, y2_pred), dim=0)
y = torch.cat((y1, y2), dim=0)
loss = loss_f(y_pred,y)
print("损失函数(均方误差):", loss.item())
return loss
适合以输入为条件的目标数据正态分布在平均值附近,并且对异常值进行额外惩罚很重要的情况
八、损失函数MSE改变为交叉熵,观察、总结并陈述。交叉熵(Cross Entropy):表示两个概率分布之间的距离。交叉熵越大,两个概率分布距离越远,两个概率分布越相异;交叉熵越小,两个概率分布距离越近,两个概率分布越相似。
替换后:
def loss_fuction(x1, x2, y1, y2): # 损失函数
y1_pred, y2_pred = forward_propagate(x1, x2) # 前向传播
loss_f = torch.nn.CrossEntropyLoss
y_pred = torch.cat((y1_pred, y2_pred), dim=0)
y = torch.cat((y1, y2), dim=0)
loss = loss_f(y_pred,y)
print("损失函数(均方误差):", loss.item())
return loss
九、改变步长,训练次数,观察、总结并陈述。
1、步长为1,1轮
=====第0轮===== 正向计算:o1 ,o2 tensor([0.4769]) tensor([0.5287]) 损失函数(均方误差): 0.2097097933292389 grad W: -0.01 0.01 -0.01 0.01 0.03 0.08 0.03 0.07 更新后的权值 tensor([0.2084]) tensor([-0.4126]) tensor([0.5051]) tensor([0.5924]) tensor([0.0654]) tensor([-0.5839]) tensor([-0.3305]) tensor([0.7262]) Process finished with exit code 0
2、步长为10,1轮
=====第0轮===== 正向计算:o1 ,o2 tensor([0.4769]) tensor([0.5287]) 损失函数(均方误差): 0.2097097933292389 grad W: -0.01 0.01 -0.01 0.01 0.03 0.08 0.03 0.07 更新后的权值 tensor([0.2842]) tensor([-0.5261]) tensor([0.5505]) tensor([0.5244]) tensor([-0.2463]) tensor([-1.3387]) tensor([-0.6049]) tensor([0.0616]) Process finished with exit code 0
3、 步长为1,10轮
=====第9轮===== 正向计算:o1 ,o2 tensor([0.4109]) tensor([0.3647]) 损失函数(均方误差): 0.11082295328378677 grad W: -0.02 0.0 -0.01 0.0 0.03 0.06 0.02 0.05 更新后的权值 tensor([0.3273]) tensor([-0.4547]) tensor([0.5764]) tensor([0.5672]) tensor([-0.1985]) tensor([-1.2127]) tensor([-0.5561]) tensor([0.1883]) Process finished with exit code 0
4、步长为10,10轮
=====第9轮===== 正向计算:o1 ,o2 tensor([0.2363]) tensor([0.0734]) 损失函数(均方误差): 0.010307400487363338 grad W: -0.0 -0.0 -0.0 -0.0 0.0 0.01 0.0 0.01 更新后的权值 tensor([0.9458]) tensor([-0.2734]) tensor([0.9475]) tensor([0.6759]) tensor([-0.8954]) tensor([-2.9388]) tensor([-1.1210]) tensor([-1.2041]) Process finished with exit code 0
步长越长,训练次数越多,则损失函数越小。
十、权值w1-w8初始值换为随机数,对比【作业2】指定权值结果,观察、总结并陈述。权重换为随机数后,均方误差会变小
十一、全面总结反向传播原理和编码实现,认真写心得体会。反向传播可以看做是关口之间在通过梯度信号相互通信,只要让它们的输入沿着梯度方向变化,无论它们自己的输出值在何种程度上升或降低,都是为了让整个网络的输出值更高。梯度下降就是在计算出损失函数对权重的偏导数:梯度后,沿着损失函数下降最快的方向更新权重值以降低损失函数值,从而提升模型的准确率。梯度下降法是通用的优化算法,反向传播法是梯度下降法在深度神经网络上的具体实现方式。PyTorch中封装了诸如损失函数等很多好用的计算函数,很大的方便了编程检查修改,减少出错。激活函数能使得神经网络的每层输出结果变得非线性化,
参考文章:
http://t.csdn.cn/nhrgthttp://t.csdn.cn/nhrgtpytorch的nn.MSELoss损失函数 - Picassooo - 博客园MSE是mean squared error的缩写,即平均平方误差,简称均方误差。 MSE是逐元素计算的,计算公式为: 旧版的nn.MSELoss()函数有reduce、size_average两个参https://www.cnblogs.com/picassooo/p/13591663.html



