写一个基于pytorch的回归预测,特征和标签都存在data.csv中,显示损失变化
时间: 2023-02-08 20:06:49 浏览: 126
可以使用以下代码实现回归预测:
```
import torch
import torch.nn as nn
import pandas as pd
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv("data.csv")
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data.drop("label", axis=1), data["label"], test_size=0.2, random_state=42)
# 转换为PyTorch的Tensor
X_train = torch.from_numpy(X_train.values).float()
X_test = torch.from_numpy(X_test.values).float()
y_train = torch.from_numpy(y_train.values).float()
y_test = torch.from_numpy(y_test.values).float()
# 定义模型
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(X_train.shape[1], 1)
def forward(self, x):
return self.linear(x)
model = LinearRegression()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# 训练模型
loss_list = []
for epoch in range(1000):
optimizer.zero_grad()
outputs = model(X_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
loss_list.append(loss.item())
if epoch % 100 == 0:
print("Epoch: %d, Loss: %.4f" % (epoch, loss.item()))
# 显示损失变化
import matplotlib.pyplot as plt
plt.plot(loss_list)
plt.show()
```
该代码首先使用pandas读取了存在data.csv中的数据,并使用sklearn.model_selection中的train_test_split函数将数据划分为训练集和测试集。然后使用PyTorch中的Tensor将数据转换为PyTorch可识别的格式。
接下来定义了一个线性回归模型
阅读全文