输出的y_test不受x_test控制
时间: 2024-02-02 12:05:23 浏览: 60
您是对的,我犯了一个错误。对于单个测试样本,您需要将其包装在一个张量中,即`x_test = torch.Tensor([4.0])`,而不是`x_test = torch.Tensor([[4]])`。因为`torch.Tensor()`期望一个可迭代对象作为输入,所以我们使用方括号`[]`将单个值包装起来。
请修改代码如下:
```python
import torch
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[2.0], [4.0], [6.0]])
class linearModel(torch.nn.Module):
def __init__(self):
super(linearModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_hat = self.linear(x)
return y_hat
model = linearModel()
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(100):
y_predict = model(x_data)
loss = criterion(y_predict, y_data)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print('Epoch:', epoch, 'Loss:', loss.item())
x_test = torch.Tensor([4.0])
y_test = model(x_test)
print('Prediction:', y_test.item())
```
现在,代码应该可以正确输出给定测试数据`x_test`的预测值`y_test`。非常抱歉给您带来的困扰。
阅读全文