使用cnn在pytorch中进行二元分类模型

binary classifying model in pytorch using cnn

我建立了一个关于钓鱼网站的分类模型。

1.首先,关于我的数据

num_dataset: i have about 16000 dataset

num_feature: my dataset has 12 characterisitics.

label: if it's a phishing site, i set it's label -1. else 1

batch_size: set batch_size 128, for cnn model

kernel_size: 3

2。我试试

from torch.utils.data import DataLoader, TensorDataset

train_dataset = TensorDataset(x_train, y_train)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)

#-------------------------------------------------------#
class CNN(nn.Module):
  def __init__(self, kernel_size):
    super().__init__()  
    self.layer1 = nn.Sequential(
        nn.Conv1d(12, 32, 3,
                  stride=1, padding=1)
...

  def forward(self, x):
    out = self.layer1(x)
...
#-------------------------------------------------------#
model = CNN()

for epoch in range(epochs):
  avg_cost = 0

  for x_train, y_train in train_loader:

    Hypothesis = model(x_train)

x_train.shape

torch.Size([16072, 12])

y_train.shape

torch.Size([16072, 1])

3。错误

Hypothesis = model(x_train)

RuntimeError:3 维权重 [32、12、3] 的预期 3 维输入,但得到的是大小 [128、12] 的二维输入

4.最后

我认为这是因为我对 conv1d 和 conv2d 感到困惑,但我无法弄清楚...

请问这个问题的原因

您正在使用 nn.Conv1d,它应该接收形状为 (batch_size, n_channels, sequence_length) 的 3 维输入。这就是说你的输入有 n_channels=12(因为你已经用 12 个输入通道初始化了 1d conv)和一个 sequence_length=1。为了满足要求,您需要在输入中添加一个额外的维度。将 x_train.unsqueeze(-1) 之类的内容传递到您的网络应该有效。

参见以下示例:

>>> x = torch.rand(100, 12, 1)
>>> L = nn.Conv1d(12, 32, 3, stride=1, padding=1)
>>> L(x).shape
torch.Size([100, 32, 1])