深度学习之一维卷积神经网实践(序列数据)

一维卷积默认的输入格式是:input = (batch_size,channel,vector_dim)
看下面一个简单的例子:

# max_sent_len=35, batch_size=50, embedding_size=300
conv1 = nn.Conv1d(in_channels=300, out_channels=100, kernel_size=3)#300个向量
input = torch.randn(50, 35, 300)#根据输入的要求,channel:300必须在axis=1上
# batch_size x max_sent_len x embedding_size -> batch_size x embedding_size x max_sent_len
input = input.permute(0, 2, 1)#转置得到(50,300,35)
print("input:", input.size())
output = conv1(input)
print("output:", output.size())#卷积滑动后的结果

pool1d = nn.MaxPool1d(kernel_size=2)#池化后的结果:50,100,16
pool1d_value = pool1d(output)
print("最大池化输出:", pool1d_value.size())
# 全连接
fc = nn.Linear(in_features=16*10, out_features=2)#全连接层输入是160神经元
fc_inp = pool1d_value.view(-1, 16*10)#应该对100x16维度变换,使之成为特征是160,得到500x160
print("全连接输入:", fc_inp.size())
fc_outp = fc(fc_inp)
print("全连接输出:", fc_outp.size())
# softmax
m = nn.Softmax()
out = m(fc_outp)
print("输出结果值:", out)

在这里插入图片描述
还有一个例子:

class ConvNet(torch.nn.Module):
	def __init__(self,output_dim):
		super(ConvNet,self).__init__()
		
		self.conv = torch.nn.Sequential()
		self.conv.add_module("conv_1",torch.nn.Conv1d(20,256,kernel_size=2))#
		self.conv.add_module("maxpool1",torch.nn.MaxPool1d(kernel_size=2))
		self.conv.add_module("relu_1",torch.nn.ReLU())
		self.conv.add_module("conv_2",torch.nn.Conv1d(256,512,kernel_size=2))
		self.conv.add_module("dropout",torch.nn.Dropout())
		self.conv.add_module("maxpool2",torch.nn.MaxPool1d(kernel_size=2))
		self.conv.add_module("relu_2",torch.nn.ReLU())
		
		self.fc = torch.nn.Sequential()
		self.fc.add_module("fc1",torch.nn.Linear(24*512,50))
		self.fc.add_module("relu_3",torch.nn.ReLU())
		self.fc.add_module("dropout_3",torch.nn.Dropout())
		self.fc.add_module("fc2",torch.nn.Linear(50,output_dim))
		
	def forward(self,x):
		x = self.conv.forward(x)
		x = x.view(-1,24*512)
		return self.fc.forward(x)

训练集的size是(856,20,101)
即856(batch_size)个矩阵,矩阵的行是20,列是101,这里原本的数据格式是(856,101,20)根据课题和一维卷积网的需要,我给后两个维度转置了一下。
所以input_channel是20,out_channel设置为256,
第一层卷积后的size是(256,101-2+1)
第一层池化后的输出是(256,100/2)
第二层卷积后的size是(512,50-2+1)
第二层池化后的size是(512,24)
对应的全连接层输入应该是(512 X 24)
后面就是普通的全连接层了
另外附上一维卷积网在序列数据上的应用的另一个例子:
在这里插入图片描述

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值