基于pytorch写一个多对多预测代码,数据集名称为data.csv,前四列为特征,其余列为标签,前800行为训练集其余为测试集,将其中一组预测值与真实值输出到excel工作表中
时间: 2023-02-16 19:03:37 浏览: 109
下面是一个基于 PyTorch 的多对多预测代码示例:
```python
import torch
import pandas as pd
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
# 读取数据
data = pd.read_csv('data.csv')
# 划分训练集和测试集
train_data = data.iloc[:800, :-5]
train_label = data.iloc[:800, 4:]
test_data = data.iloc[800:, :-5]
test_label = data.iloc[800:, 4:]
# 将训练数据转换为 Tensor
train_dataset = TensorDataset(torch.tensor(train_data.values, dtype=torch.float32), torch.tensor(train_label.values, dtype=torch.float32))
test_dataset = TensorDataset(torch.tensor(test_data.values, dtype=torch.float32), torch.tensor(test_label.values, dtype=torch.float32))
# 设置 DataLoader
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# 定义网络模型
class Multi2Multi(nn.Module):
def __init__(self):
super(Multi2Multi, self).__init__()
self.fc = nn.Linear(4, 5)
def forward(self, x):
x = self.fc(x)
return x
# 初始化模型
model = Multi2Multi()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# 训练模型
for epoch in range(100):
for i, (data, label) in enumerate(train_loader):
output = model(data)
loss = criterion(output, label)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f'epoch {epoch+1}, loss: {loss.item()}')
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for data, label in test_loader:
outputs = model(data)
_, predicted = torch.max(outputs.data, 1)
total += label.size(0)
correct += (predicted == label).sum().item()
阅读全文