import torch
import torch.nn as nn
import numpy as np
x_train = [i for i in range(10)]
x_train = np.array(x_train, dtype=np.float32)
x_train.reshape(-1, 1)
y_train = [2 * i + 1 for i in range(10)]
y_train = np.array(y_train, dtype=np.float32)
y_train.reshape(-1, 1)
class MyModule(nn.Module):
def __int__(self, input_dim, output_dim):
super(MyModule, self).__int__()
self.linear = nn.Linear(1, 1)
def forward(self, x):
return self.linear(x)
# 定义网络结果,损失函数,优化器
if torch.cuda.is_available():
model = MyModule().cuda()
else:
model = MyModule()
lea = 0.0001
optimizer = torch.optim.SGD(model.parameters(), lr=lea)
criterion = nn.MSELoss()
epochs = 10
for epoch in range(epochs):
optimizer.zero_grad()
if torch.cuda.is_available():
inputs = torch.from_numpy(x_train).cuda()
labels = torch.from_numpy(y_train).cuda()
else:
inputs = torch.from_numpy(x_train)
labels = torch.from_numpy(y_train)
outs = model(x_train)
loss = criterion(labels, y_train)
loss.backward()
optimizer.step()
print('epoch {}\tloss {}'.format(epoch, loss))
pytorch版本 1.12.1+cu116
代码如上,优化器那行报错了,如下。
ValueError: optimizer got an empty parameter list