问题遇到的现象和发生背景
我按照书上教程用python中的pytorch框架写了一个神经网络代码,但是一直报错优化器参数为空列表,代码和书上的一模一样,不知道哪里出来问题,希望各位能帮帮忙,代码和报错如下:
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
# 数据准备
x = torch.unsqueeze(torch.linspace(-np.pi,np.pi,100),dim=1)
y = torch.sin(x) + 0.5 * torch.rand(x.size())
# 构建网络
class Net(nn.Module):
def __int__(self):
super(Net,self).__init__()
self.predict = nn.Sequential(
nn.Linear(1,10),
nn.ReLU(),
nn.Linear(10,1)
)
def forward(self,x):
prediction = self.predict(x)
return prediction
# 设置优化器和损失函数
net = Net()
optimizer = torch.optim.SGD(net.parameters(),lr=0.05)
loss_function = nn.MSELoss
plt.ion()
# 训练网络
for epoch in range(1000):
out = net(x)
loss = loss_function(out,y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 25 == 0:
plt.cla()
plt.scatter(x,y)
plt.plot(x,out.data.numpy,c="r",lw=5)
plt.text(0.5,0,f"loss={loss}",fontdict={"size":20,"color":"red"})
plt.pause(0.1)
plt.show()
plt.ioff()
plt.show()
运行结果及报错内容
Traceback (most recent call last):
File "E:\PythonLearning\nn_regression.py", line 36, in <module>
optimizer = torch.optim.SGD(net.parameters(),lr=0.05)
File "D:\ProgramData\Anaconda3\lib\site-packages\torch\optim\sgd.py", line 101, in __init__
super(SGD, self).__init__(params, defaults)
File "D:\ProgramData\Anaconda3\lib\site-packages\torch\optim\optimizer.py", line 49, in __init__
raise ValueError("optimizer got an empty parameter list")
ValueError: optimizer got an empty parameter list
谢谢大家