数据是由excel表读取的,不是随机生成的,修改一下以上代码
时间: 2024-04-07 14:33:39 浏览: 61
读取excel表数据代码!
如果你的数据是由Excel表格读取而来,你可以使用`pandas`库来读取Excel数据,并将其转换为PyTorch张量。以下是修改后的代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.transforms import ToTensor
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import matplotlib.pyplot as plt
# 自定义数据集类
class CustomDataset(Dataset):
def __init__(self, data, labels):
self.data = data
self.labels = labels
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx], self.labels[idx]
# 自定义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.conv3 = nn.Conv2d(32, 1, kernel_size=3, stride=1, padding=1)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.relu(x)
x = self.conv3(x)
return x
# 从Excel表格读取数据
train_df = pd.read_excel('train_data.xlsx')
train_data = torch.tensor(train_df.values).float().unsqueeze(1) # 添加通道维度
train_labels_df = pd.read_excel('train_labels.xlsx')
train_labels = torch.tensor(train_labels_df.values).float().unsqueeze(1) # 添加通道维度
train_dataset = CustomDataset(train_data, train_labels)
train_dataloader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_df = pd.read_excel('test_data.xlsx')
test_data = torch.tensor(test_df.values).float().unsqueeze(1) # 添加通道维度
test_labels_df = pd.read_excel('test_labels.xlsx')
test_labels = torch.tensor(test_labels_df.values).float().unsqueeze(1) # 添加通道维度
test_dataset = CustomDataset(test_data, test_labels)
test_dataloader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# 模型训练
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = CNN().to(device)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
train_loss_history = []
test_loss_history = []
for epoch in range(10):
train_loss = 0.0
model.train()
for inputs, labels in train_dataloader:
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
train_loss /= len(train_dataloader)
train_loss_history.append(train_loss)
test_loss = 0.0
model.eval()
with torch.no_grad():
for inputs, labels in test_dataloader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
test_loss += loss.item()
test_loss /= len(test_dataloader)
test_loss_history.append(test_loss)
print(f"Epoch {epoch+1}: Train Loss: {train_loss:.4f}, Test Loss: {test_loss:.4f}")
# 绘制误差图像
plt.plot(train_loss_history, label='Train Loss')
plt.plot(test_loss_history, label='Test Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
```
在这个修改后的代码中,我们使用了`pandas`库来从Excel表格中读取训练和测试数据。你需要将`'train_data.xlsx'`、`'train_labels.xlsx'`、`'test_data.xlsx'`和`'test_labels.xlsx'`替换为你实际的Excel文件名。数据读取后,我们将其转换为PyTorch张量,并将其添加了一个通道维度(unsqueeze(1))。然后,我们使用自定义的数据集类`CustomDataset`和数据加载器`DataLoader`来加载数据。
希望这次的修改对你有帮助!如果还有其他问题,请随时提问。
阅读全文