训练数据和测试数据的标签值怎么没有读取进去?
时间: 2024-04-08 19:30:58 浏览: 91
2.tensorflow数据读取、训练模型、测试模型代码
对不起,我忘记在代码中添加读取标签的部分。以下是后的代码,包读取训练数据和测试数据的标值:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
import matplotlib.pyplot as plt
# 定义CNN模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=1, padding=1)
self.relu = nn.ReLU()
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1)
self.fc = nn.Linear(32 * 45 * 235, 150 * 675)
def forward(self, x):
x = self.relu(self.conv1(x))
x = self.relu(self.conv2(x))
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
# 读取训练数据及标签值
train_data = pd.read_excel('data.xlsx', sheet_name='Sheet1', usecols=[0], nrows=700)
train_labels = pd.read_excel('data.xlsx', sheet_name='Sheet1', usecols=[1], nrows=700)
train_data = torch.tensor(train_data.values.reshape(-1, 1, 45, 235), dtype=torch.float32)
train_labels = torch.tensor(train_labels.values, dtype=torch.float32)
# 读取测试数据及标签值
test_data = pd.read_excel('data.xlsx', sheet_name='Sheet1', usecols=[0], skiprows=700)
test_labels = pd.read_excel('data.xlsx', sheet_name='Sheet1', usecols=[1], skiprows=700)
test_data = torch.tensor(test_data.values.reshape(-1, 1, 45, 235), dtype=torch.float32)
test_labels = torch.tensor(test_labels.values, dtype=torch.float32)
# 初始化模型、损失函数和优化器
model = CNN()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练模型
num_epochs = 10
train_losses = []
test_losses = []
for epoch in range(num_epochs):
model.train()
train_loss = 0.0
for i, data in enumerate(train_data):
optimizer.zero_grad()
outputs = model(data.unsqueeze(0))
loss = criterion(outputs, train_labels[i])
loss.backward()
optimizer.step()
train_loss += loss.item()
train_losses.append(train_loss / len(train_data))
model.eval()
test_loss = 0.0
with torch.no_grad():
for i, data in enumerate(test_data):
outputs = model(data.unsqueeze(0))
loss = criterion(outputs, test_labels[i])
test_loss += loss.item()
test_losses.append(test_loss / len(test_data))
# 绘制训练误差和测试误差的图表
plt.plot(range(1, num_epochs+1), train_losses, label='Train Loss')
plt.plot(range(1, num_epochs+1), test_losses, label='Test Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
```
再次对之前的遗漏表示抱歉。更新后的代码会读取训练数据和测试数据的标签值,并在训练过程中使用它们计算损失。希望这次能满足你的需求。
阅读全文