接着上一篇文章,这次使用随机梯度下降法调整参数完成反向传播
flexible transmitter (南大周志华团队Shao-Qun Zhang, Zhi-Hua Zhou)中sin信号模拟python代码
import numpy as np
import matplotlib.pyplot as plt # 导入 matplotlib 包的 pyplot 模块,并简写为 plt
# 生成数据
x=np.array(range(300))
# x
y=np.sin(x*2/3*np.pi)
# y
# 设置初始参数
w=-1.142
v=-0.1929
m=-0.25
#初始化记忆单元m,以便于后面查看m随时间的变化情况
hm=np.zeros(len(y))
# 迭代次数计数
j=0
# 初始化损失
totolloss=10000
# 当损失小于70或者迭代超过1000次时停止迭代
while((totolloss>70)&(j<1000)):
# 遍历数据集
for i in range(len(y)-1):
# 随机梯度下降
# 前向传播
pre[i+1]=np.tanh(w*y[i]-v*m)
real[i+1]=np.tanh(w*y[i]-v*m)
# 计算损失
loss = np.square(pre[i+1]-y[i+1])/2
# 计算梯度
dw=(pre[i+1]-y[i+1])*(1-np.square(np.tanh(real[i+1])))*y[i]
dv=(pre[i+1]-y[i+1])*(1-np.square(np.tanh(real[i+1])))*(-m)
# 更新参数
w=w-0.001*dw
v=v-0.001*dv
m=np.tanh(w*y[i]+v*m)
hm[i+1]=m
# 迭代次数计数
j=j+1
# 每迭代100次输出一次总损失和参数值
if j%100==0:
totolloss=np.sum(np.square(y-pre))
print(totolloss,w,v)
绘制拟合效果图
plt.plot(x[:60],y[:60])
plt.plot(x[:60],pre[:60])
plt.show()
绘制记忆单元m和真实信号的时序图
plt.plot(x[:60],y[:60])
plt.plot(x[:60],hm[:60])
plt.show()
文章链接如下
[1]: https://arxiv.org/pdf/2004.03839.pdf
[2]:flexible transmitter (南大周志华团队Shao-Qun Zhang, Zhi-Hua Zhou)中sin信号模拟python代码