plt.plot(batch_x.data.numpy(), predict.squeeze(1).data.numpy())
时间: 2024-05-18 10:15:26 浏览: 93
这是一行用于绘制模型预测结果的代码,其中batch_x是模型输入的数据,predict是模型输出的预测结果。plt.plot()是一个绘图函数,可以用于绘制曲线图,其中第一个参数是x轴数据,第二个参数是y轴数据。在这里,batch_x.data.numpy()是将输入数据转换为numpy数组,predict.squeeze(1).data.numpy()是将输出结果的第一维压缩,然后再将其转换为numpy数组。
相关问题
import torch import matplotlib.pyplot as plt def features(x): x = x.unsqueeze(1) return torch.cat([x ** i for i in range(1, 5)], 1) x_weight = torch.Tensor([-1.13, -2.14, 3.15, -0.01]).unsqueeze(1) b = torch.Tensor([0.512]) def target(x): return x.mm(x_weight) + b.item() def get_batch_data(batch_size): batch_x = torch.rand(batch_size) features_x = features(batch_x) target_y = target(features_x) return features_x, target_y class PR(torch.nn.Module): def __init__(self): super(PR, self).__init__() self.poly = torch.nn.Linear(4, 1) def forward(self, x): return self.poly(x) epochs = 10000 batch_size = 32 model = PR() criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), 0.01) for i in range(epochs): batch_x, batch_y = get_batch_data(batch_size) out = model(batch_x) loss = criterion(out, batch_y) optimizer.zero_grad() loss.backward() optimizer.step() if(i % 100 == 0): print(f"Epoch:{i+1}/{epochs}, loss:{loss.item}") if(i%1000 == 0): predict = model(features(batch_x)) plt.plot(batch_x.data.numpy(), predict.squeeze().data.numpy(), "r") loss = criterion(predict, batch_y) plt.title(f"Loss:{loss.item()}") plt.xlabel("X") plt.ylabel("Y") plt.scatter(batch_x, batch_y) plt.show()哪里出错了
代码有一个小错误,第26行应该是`print(f"Epoch:{i+1}/{epochs}, loss:{loss.item()}")`,需要加上括号。另外,在第34行,应该是`loss = criterion(out, batch_y)`,而不是`loss = criterion(predict, batch_y)`。正确的代码如下所示:
```
import torch
import matplotlib.pyplot as plt
def features(x):
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, 5)], 1)
x_weight = torch.Tensor([-1.13, -2.14, 3.15, -0.01]).unsqueeze(1)
b = torch.Tensor([0.512])
def target(x):
return x.mm(x_weight) + b.item()
def get_batch_data(batch_size):
batch_x = torch.rand(batch_size)
features_x = features(batch_x)
target_y = target(features_x)
return features_x, target_y
class PR(torch.nn.Module):
def __init__(self):
super(PR, self).__init__()
self.poly = torch.nn.Linear(4, 1)
def forward(self, x):
return self.poly(x)
epochs = 10000
batch_size = 32
model = PR()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), 0.01)
for i in range(epochs):
batch_x, batch_y = get_batch_data(batch_size)
out = model(batch_x)
loss = criterion(out, batch_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if(i % 100 == 0):
print(f"Epoch:{i+1}/{epochs}, loss:{loss.item()}")
if(i%1000 == 0):
predict = model(features(batch_x))
plt.plot(batch_x.data.numpy(), predict.squeeze().data.numpy(), "r")
loss = criterion(out, batch_y)
plt.title(f"Loss:{loss.item()}")
plt.xlabel("X")
plt.ylabel("Y")
plt.scatter(batch_x, batch_y)
plt.show()
```
import torch import matplotlib.pyplot as plt def features(x): x = x.unsqueeze(1) return torch.cat([x ** i for i in range(1, 5)], 1) x_weight = torch.Tensor([-1.13, -2.14, 3.15, -0.01]).unsqueeze(1) b = torch.Tensor([0.512]) def target(x): return x.mm(x_weight) + b.item() def get_batch_data(batch_size): batch_x = torch.randon(batch_size) features_x = features(batch_x) target_y = target(features_x) return features_x, target_y class PR(torch.nn.Module): def __init__(self): super(PR, self).__init__() self.poly = torch.nn.Linear(4, 1) def forward(self, x): return self.poly(x) epochs = 10000 batch_size = 32 model = PR() criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), 0.01) for i in range(epochs): batch_x, batch_y = get_batch_data(batch_size) out = model(batch_x) loss = criterion(out, batch_y) optimizer.zero_grad() loss.backward() optimizer.step() if(epochs % 100 == 0): print(f"Epoch:{i+1}/{epochs}, loss:{loss.item}") if(i%1000 == 0): predict = model(features(batch_x)) plt.plot(batch_x.data.numpy(), predict.squeeze(1).data.numpy(), c="r") loss = criterion(predict, batch_y) plt.title(f"Loss:{loss.item}") plt.xlabel("X") plt.ylabel("Y") plt.scatter(batch_x, batch_y) plt.show()哪里要改
在代码中,有一些小错误:
1. `torch.randon`应该是`torch.rand`,生成随机数的函数名称写错了。
2. `loss.item` 应该是`loss.item()`,需要调用这个方法来得到损失值。
3. 在if语句中,应该是`i % 100 == 0`而不是`epochs % 100 == 0`,因为epochs是循环次数,不会改变,而i是当前循环的次数。
修改后的代码如下:
```
import torch
import matplotlib.pyplot as plt
def features(x):
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, 5)], 1)
x_weight = torch.Tensor([-1.13, -2.14, 3.15, -0.01]).unsqueeze(1)
b = torch.Tensor([0.512])
def target(x):
return x.mm(x_weight) + b.item()
def get_batch_data(batch_size):
batch_x = torch.rand(batch_size) # 将 torch.randon 改为 torch.rand
features_x = features(batch_x)
target_y = target(features_x)
return features_x, target_y
class PR(torch.nn.Module):
def __init__(self):
super(PR, self).__init__()
self.poly = torch.nn.Linear(4, 1)
def forward(self, x):
return self.poly(x)
epochs = 10000
batch_size = 32
model = PR()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), 0.01)
for i in range(epochs):
batch_x, batch_y = get_batch_data(batch_size)
out = model(batch_x)
loss = criterion(out, batch_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if(i % 100 == 0): # 将 epochs % 100 == 0 改为 i % 100 == 0
print(f"Epoch:{i+1}/{epochs}, loss:{loss.item()}")
if(i % 1000 == 0):
predict = model(features(batch_x))
plt.plot(batch_x.data.numpy(), predict.squeeze(1).data.numpy(), c="r")
loss = criterion(predict, batch_y)
plt.title(f"Loss:{loss.item()}")
plt.xlabel("X")
plt.ylabel("Y")
plt.scatter(batch_x, batch_y)
plt.show()
```
阅读全文