torch.nn.Conv1d详解

本文详细介绍了PyTorch中torch.nn.Conv1d模块,包括一维卷积的几个关键问题:卷积的维度、卷积核大小、out_channel的概念,以及实际代码示例。通过分析,展示了输入和输出通道数如何变化,并指出卷积操作是在最后一个维度上进行的。

torch.nn.Conv1d详解

1.几个问题:

  • 一维卷积的是在哪个维度进行?

  • 一维卷积核的大小?

  • out_channel是指什么?怎么变换的?

2.卷积定义

torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode=‘zeros’)

参数定义

  • in_channel:输入的通道数,信号一般为一维

  • out_channel:输出的通道数

  • kernel_size:卷积核的大小

  • stride:步长

  • padding:0填充

3.在哪个维度移动的

一维信号卷积
多通道一维信号卷积

定义输入的大小为(batch_size,channel,length)

可以肯定的是卷积核是在最后一个维度移动的,例如上图的一维信号是卷积核从左往右进行卷积的。

然而卷积核的大小为多少呢?右上下图可知,卷积核大小为(channel*kernel_size),一般一维信号的卷积核大小就为(1*kernel_size)

一维卷积不是指卷积核是一维的,而是在一个维度进行卷积。

4.out_channel

从输入到输出的过程中,通道数经常在发生改变,而out_channel是什么呢?

out_channel就是同时用多少个卷积核去卷同一个区域。

5.实例代码

import time

import torch
import torch.nn as nn

'''
Description: torch.nn.Conv1d
input:(batch_size,in_channel,length)
output:(batch_size,out_channel,length)
shape of kernel:(channel*kernel_size)
out_channel :the num of kernel--> how much kernel do you need?
'''
#(batch_size,in_channel,length)
input =torch.rand(5,1,10)
print(input.shape)
print(input)
model =nn.Conv1d(in_channels=1,
                 out_channels=3,
                 kernel_size=5,
                 padding=2)
# (batch_size,out_channel,length)
output =model(input)
print(output.shape)
print(output)

input的输出:
在这里插入图片描述

output的输出:

在这里插入图片描述

6.分析

  • 可以看到除了channel变化以外其他的并没有改变,因为根据length的变化公式,正好length不变。

  • 输入看起来直观上是5条1乘以10的一维信号,输出看起来就是5条3乘以10的3通道一维信号。

7来源

  • [torch.nn — PyTorch master documentation](https://pytorch.org/docs/1.2.0/nn.html?highlight=nn conv1d#torch.nn.Conv1d)
  • https://stackoverflow.com/questions/42883547/intuitive-understanding-of-1d-2d-and-3d-convolutions-in-convolutional-neural-n
  • https://www.quora.com/How-does-a-convolutional-layer-convert-a-64-channel-input-into-a-3-channel-or-one-channel
  • https://towardsdatascience.com/pytorch-basics-how-to-train-your-neural-net-intro-to-cnn-26a14c2ea29
  • (86条消息) torch.nn.Conv1d及一维卷积详解_西工大苗苗的博客-CSDN博客_pytorch一维卷积
  • 还有一些忘记了在哪233333333
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值