用F.conv1d实现np.convolve tensor类型的卷积操作

之所以有这个需求是要在神经网络中写滤波器

就有几点要注意,输入的tensor要符合F.conv1d的三维要求,要加正确的padding位数才是对准的,神经网络里面的卷积实际上是相关,所以滤波器参数要翻转一下

# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 11:12:40 2020
np.convlve和F.conv1d对比
@author: user
"""

import torch
import torch.nn.functional as F
import numpy as np

torch.set_default_tensor_type(torch.DoubleTensor)
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")

x=np.arange(7)
h_filter=np.array([-1,0,1,0,2])
y=np.convolve(x,h_filter,'same')   #y.shape 7+4-1
print(y.shape)
print(y)

x_tr=torch.from_numpy(x).unsqueeze(0).unsqueeze(0).to(device).double()
h_tr=h_filter[::-1].copy()
h_tr=torch.from_numpy(h_tr).unsqueeze(0).unsqueeze(0).to(device).double()
y_tr=F.conv1d(x_tr,h_tr,padding=int(h_filter.shape[0]/2))
print(y_tr.shape)
print(y_tr)

如果padding给h_filter.shape[0]-1的话,输出信号长度就等于信号长度+滤波器参数长度-1,而不是取信号长度

# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 11:12:40 2020
np.convlve和F.conv1d对比
@author: user
"""

import torch
import torch.nn.functional as F
import numpy as np

torch.set_default_tensor_type(torch.DoubleTensor)
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")

x=np.arange(7)
h_filter=np.array([-1,0,1,0,2])
y=np.convolve(x,h_filter)   #y.shape 7+4-1
print(y.shape)
print(y)

x_tr=torch.from_numpy(x).unsqueeze(0).unsqueeze(0).to(device).double()
h_tr=h_filter[::-1].copy()
h_tr=torch.from_numpy(h_tr).unsqueeze(0).unsqueeze(0).to(device).double()
y_tr=F.conv1d(x_tr,h_tr,padding=int(h_filter.shape[0]-1))
print(y_tr.shape)
print(y_tr)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值