plt.scatter(test_target_tensor.numpy(), final_output.numpy())
时间: 2024-02-23 10:58:28 浏览: 59
这行代码使用了Matplotlib库中的scatter函数,用于画散点图。其中,test_target_tensor和final_output都是Numpy数组,分别表示测试集的目标值和模型预测值。通过将这两个数组作为函数的输入,可以画出目标值和预测值之间的散点图。
```python
import matplotlib.pyplot as plt
# 画散点图
plt.scatter(test_target_tensor.numpy(), final_output.numpy())
# 设置图表标题和轴标签
plt.title('目标值 vs 预测值')
plt.xlabel('目标值')
plt.ylabel('预测值')
# 显示图表
plt.show()
```
在这个例子中,我们首先使用scatter函数画出散点图,然后设置了图表标题和轴标签,并用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.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()
```
阅读全文