之所以有这个需求是要在神经网络中写滤波器
就有几点要注意,输入的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)