pytorch做一维数据的分类任务

刚刚接触深度学习,希望同学们能指点一下
做一个一维数据的分类模型,一共有9类,一类样本有1024个样本,一个样本有1024个数据。(样本在csv中是一行一个)
下面是模型代码

import torch
import numpy as np
import pandas as pd
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torch.utils.data import Dataset
from torch.utils.data import DataLoader


class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv1d(
                in_channels=1,
                out_channels=16,
                kernel_size=5,
                stride=1,
                padding=2
            ),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=1)
        )
        self.conv2 = nn.Sequential(
            nn.Conv1d(
                in_channels=16,
                out_channels=64,
                kernel_size=5,
                stride=1,
                padding=2
            ),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=1)
        )
        self.out = nn.Linear(128, 9)

    def forward(self, x):
        # x = torch.Tensor(x).view(-1, 1, 1024)
        # x = torch.unsqueeze(x, dim=0)
        print(x.shape)
        x = self.conv1(x),
        x = self.conv2(x),
        output = self.out(x)
        return output


# 转tensor
# transform = transforms.Compose([
#     transforms.ToTensor(),
#     transforms.Normalize((0.1307,), (0.3081,))
# ])


# 数据导入


class MyDataset:
    def __init__(self, filepath):
        xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32)
        self.len = xy.shape[0]
        self.x_data = torch.from_numpy(xy[:, :-1])
        self.y_data = torch.from_numpy(xy[:, [-1]])
        print('--------数据已载入--------')

    def __getitem__(self, index):
        return self.x_data[index], self.y_data[index]

    def __len__(self):
        return self.len


file = 'F:/PyCharm 项目/dataset/多分类/多分类—CNN .csv'

mydataset = MyDataset(file)

train_loader = DataLoader(dataset=mydataset,
                          batch_size=16,
                          shuffle=True)

#  实例化模型
model = CNN()
#  损失函数:交叉熵
criterion = nn.CrossEntropyLoss()
#  带动量的随机梯度下降
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
#  储存损失
loss_list = []

for epoch in range(5):
    for batch, (X, y) in enumerate(train_loader):
        # 正向传播
        y_pred = model(X)
        # 计算损失
        loss = criterion(y_pred, y)
        # 梯度归零
        optimizer.zero_grad()
        # 反向传播
        loss.backward()
        # 更新参数
        optimizer.step()
        # 每100次查看损失
        if batch % 100 == 0:
            loss_list.append(loss.data.item())
            print('loss-------------:', loss.data.item())

# 显示损失下降的图像
plt.plot(np.linspace(0, 1000, len(loss_list)), loss_list)
plt.show()

# 检验测试集的正确率
rets = []
total = 0
correct = 0

# 不需要计算梯度
with torch.no_grad():
    for data in test_loader:
        X, y = data
        y_pred = model(X)
        # 返回值有两个,第一个是最大的值,第二个是最大值的索引
        _, predicted = torch.max(y_pred.data, dim=1)

        total += y.size(0)
        correct += (predicted == y).sum().item()

print('Accuracy on test set: %.2f %% ' % (100.0 * (correct / total)))



运行之后出这个bug


```python
"F:\PyCharm 2020.1\Anadonda 3\python.exe" "F:/PyCharm 项目/练习/1D-CNN/CNN.py"
--------数据已载入--------
torch.Size([16, 1024])
Traceback (most recent call last):
  File "F:/PyCharm 项目/练习/1D-CNN/CNN.py", line 93, in <module>
    y_pred = model(X)
  File "F:\PyCharm 2020.1\Anadonda 3\lib\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)
  File "F:/PyCharm 项目/练习/1D-CNN/CNN.py", line 42, in forward
    x = self.conv1(x),
  File "F:\PyCharm 2020.1\Anadonda 3\lib\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)
  File "F:\PyCharm 2020.1\Anadonda 3\lib\site-packages\torch\nn\modules\container.py", line 141, in forward
    input = module(input)
  File "F:\PyCharm 2020.1\Anadonda 3\lib\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)
  File "F:\PyCharm 2020.1\Anadonda 3\lib\site-packages\torch\nn\modules\conv.py", line 302, in forward
    return self._conv_forward(input, self.weight, self.bias)
  File "F:\PyCharm 2020.1\Anadonda 3\lib\site-packages\torch\nn\modules\conv.py", line 298, in _conv_forward
    return F.conv1d(input, weight, bias, self.stride,
RuntimeError: Given groups=1, weight of size [16, 1, 5], expected input[1, 16, 1024] to have 1 channels, but got 16 channels instead

```

RuntimeError: Given groups=1, weight of size [16, 1, 5], expected input[1, 16, 1024] to have 1 channels, but got 16 channels instead

数据集的维度不匹配

你的标签不对,要用独热码编辑