在学习pytorch训练回归模型时出现报错
NotImplementedError Traceback (most recent call last)
Input In [86], in <cell line: 26>()
29 labels = torch.from_numpy(y_train).to(device)
31 optimizer.zero_grad()
---> 33 outputs = model(inputs)
35 loss = criterion(outputs, labels)
37 loss.backward()
File C:\Users\anaconda\envs\woniu\lib\site-packages\torch\nn\modules\module.py:1110, in Module._call_impl(self, *input, **kwargs)
1106 # If we don't have any hooks, we want to skip the rest of the logic in
1107 # this function, and just call forward.
1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1109 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1110 return forward_call(*input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []
File C:\Users\anaconda\envs\woniu\lib\site-packages\torch\nn\modules\module.py:201, in _forward_unimplemented(self, *input)
190 def _forward_unimplemented(self, *input: Any) -> None:
191 r"""Defines the computation performed at every call.
192
193 Should be overridden by all subclasses.
(...)
199 registered hooks while the latter silently ignores them.
200 """
--> 201 raise NotImplementedError
NotImplementedError:
#woniu是我组建的虚拟环境
import torch
import torch.nn as nn
import numpy as np
x_values = [i for i in range(11)]
x_train = np.array(x_values , dtype = np.float32)
x_train = x_train.reshape(-1, 1)
x_train.shape
y_values = [2*i+1 for i in x_values]
y_train = np.array(y_values , dtype = np.float32)
y_train = y_train.reshape(-1, 1)
y_train.shape
class LinearRegressionModel(nn.Module):
def __init__(self, input_dim, output_dim):
super(LinearRegressionModel, self).__init__()
self.Linear = nn.Linear(input_dim, output_dim)
def forward(self, x):
out = self.linear(x)
return out
input_dim = 1
output_dim = 1
model = LinearRegressionModel(input_dim, output_dim)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
criterion = nn.MSELoss()
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
epochs = 1000
for epoch in range(epochs):
epoch += 1
inputs = torch.from_numpy(x_train).to(device)
labels = torch.from_numpy(y_train).to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if epoch%50 == 0:
print('epoch{},loss{}'.format(epoch, loss.item()))
没有头绪,在学习视频中别人可以训练成功
成功执行
好像还是数据的问题
你的报错信息呢?