一个预测sin函数的pytorch程序,主要用来研究模拟的深度学习层数和宽度对准确性影响。lstm以前预测也还可以,如果用sin作为激活函数理论上可以模拟任何函数,包括周期函数。主要是受到傅里叶启发,大家研究看看,记得要写好出处,我也能得点流量。这样lstm是不是要淘汰了?
import numpy as np
import torch
import matplotlib.pyplot as plt
import matplotlib
from torch.optim.lr_scheduler import ReduceLROnPlateau,CosineAnnealingWarmRestarts
from torchsummary import summary
#---------------参数设置------------------
N=1000 #数据量
learning_rate=0.1
my_repeat=1000
D_in,HH,D_out=1,10,1
#--------------------------------
def myfunc(x):
y=np.sin(x)+1 #y是x相对应的正弦值
##y=np.power(x,2) #y是x相对应的值
##y=0.1*x*x*x-7*x+23
#y=np.log(x)
return y
Pi=3.14
device=torch.device("cuda")
x=np.linspace(0,3.14*20,N).reshape(-1,1) #x=0到100的N个数
y=myfunc(x)
xx=torch.Tensor(x.copy()) #转为Tensor
yy=torch.Tensor(y.copy())
class mySin(torch.nn.Module):#sin激活函数
def __init__(self):
super().__init__()
def forward(self,x):
x=x.sin()
return x
class mymodel (torch.nn.Module):
def makedense(self,myinput,myoutput):#用函数创建重复的层
dense=torch.nn.Sequential(
torch.nn.Linear(myinput,myoutput),
mySin(),#自定义激活函数
#torch.nn.Sigmoid(),
## torch.nn.Dropout(p=0.002)
)
return dense
def __init__(self,D_in,HH,D_out):
super().__init__()
self.dense_input=self.makedense(D_in,HH)
## self.dense_11=self.makedense(HH,HH)
##
## self.dropout=torch.nn.functional.dropout
##
## self.dense_out=self.makedense(HH,D_out)
##
## self.dropout=torch.nn.functional.dropout
self.lin=torch.nn.Linear(HH,1)
def forward(self,x):
out=self.dense_input(x)
##
out=self.lin(out)
self.out=out
return out
def printp(self): #显示所有参数
for para in self.parameters():
print("para:=",para)
model=mymodel(D_in,HH,D_out)
#------------------
model=model.to(device) #数据以及模型搬到gpu
model.printp() #显示所有参数
xx=xx.to(device)
yy=yy.to(device)
#------------------
loss_fn=torch.nn.MSELoss()
optimizer=torch.optim.Adam(model.parameters(),lr=learning_rate)
#scheduler = ReduceLROnPlateau(optimizer, 'min',factor=0.5, patience=4, verbose=True)
scheduler = CosineAnnealingWarmRestarts(optimizer,T_0=5,T_mult=1)
for it in range(my_repeat):
y_pred=model(xx)#传入一批数据
loss=loss_fn(y_pred,yy)
#model.zero_grad()
optimizer.zero_grad()
loss.backward()
optimizer.step()
#scheduler.step(it)
#model.zero_grad()
if it % (my_repeat // 100) ==0 :print(it,"loss:=",loss)
#-----------------训练好了,下面预测--------------------------
x=np.linspace(-3.14*10,3.14*20,N).reshape(-1,1) #x=0到100的N个数
xx=torch.Tensor(x.copy()).to(device) #转为Tensor
yy_pre=model(xx).to("cpu") #训练好预测
yy_pre=np.array(yy_pre.data)
yy_pre.reshape(-1)
plt.plot(x,yy_pre,'g-s')
y=myfunc(x) #计算x相对应的精确值numpy运算
plt.plot(x,y+0.5,'b-s')
#plt.show()
plt.pause(1)