PyTorch-implementing one-dimensional convolution of tabular data (CNN1D)

Dataset: first look at the data of my own table type

Seeing that everyone asked for the code in private messages, there were too many to send, so I put the code on github:

github link: https://github.com/JiaBinBin233/CNN1D
My data set is a two-category data set, which is a 12-dimensional data (the first column is the label column, and the other 11 columns are attribute columns)
insert image description here

neural network architecture

#两层卷积层,后面接一个全连接层
class Learn(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.model1 = nn.Sequential(
        	#输入通道一定为1,输出通道为卷积核的个数,2为卷积核的大小(实际为一个[1,2]大小的卷积核)
            nn.Conv1d(1, 16, 2),  
            nn.Sigmoid(),
            nn.MaxPool1d(2),  # 输出大小:torch.Size([128, 16, 5])
            nn.Conv1d(16, 32, 2),
            nn.Sigmoid(),
            nn.MaxPool1d(4),  # 输出大小:torch.Size([128, 32, 1])
            nn.Flatten(),  # 输出大小:torch.Size([128, 32])
        )
        self.model2 = nn.Sequential(
            nn.Linear(in_features=32, out_features=2, bias=True),
            nn.Sigmoid(),
        )
    def forward(self, input):
        x = self.model1(input)
        x = self.model2(x)
        return x

I personally think that the format of the input data is a difficult point

First look at the unprocessed data

for data in train_loader:
    X_data, Y_data = data[0], data[1]
    print(X_data)
    print(X_data.shape)
The output is as follows

insert image description here
The original data is a data with 128 rows and 11 columns, each row of data represents a sample, a total of 128 samples (batch_size=128)

Process the data into a data form that can be input to the convolutional network

X_data = X_data.reshape(-1,1,11) # -1表示让系统自己计算有多少个样本,这个操作的目的就是把数据转换为3维的
print(X_data)
print(X_data.shape)
The output is as follows

insert image description here

run

output = Learn(X_data)
loss = loss_function(output, Y_data)
optim.zero_grad()
loss.backward()
optim.step()

principle

The process of one-dimensional convolution is that the convolution kernel performs horizontal convolution on each sample (the number of convolution kernels is the size of the output channel), and the number of convolutions for each sample is the number of convolution kernels. Each sample is convoluted. I took a picture of the specific convolution process on someone else's blog for everyone to understand.

insert image description here

This figure is the specific operation of the convolution kernel to convolve a sample.

Guess you like

Origin blog.csdn.net/qq_40529151/article/details/125709932