pytorch自定义高斯卷积核进行卷积

pytorch支持自定义卷积核进行卷积操作,使用

torch.nn.functional.conv2d

下面是我用到的自定义高斯卷积核的代码:



class SA_net(nn.Module):
    def __init__(self):
        super(SA_net, self).__init__()
        kernel =get_kernel(kernlen=5,nsig=3) #获得高斯卷积核
        kernel = torch.FloatTensor(kernel).unsqueeze(0).unsqueeze(0)   #扩展两个维度
        self.weight = nn.Parameter(data=kernel, requires_grad=False)
        self.BN=nn.BatchNorm2d(num_features=1)
 
    def forward(self, x1,x2):   #x1是用来计算attention的,x2是用来计算的Cs
        x1_attention = F.conv2d(x1, self.weight, padding=2)    #bs,i_c,H1,W1---->bs,1,H1,W1
        x1_attention=self.BN(x1_attention)   #bs,1,H1,W1
        x_max=torch.max(x1_attention,x1)     #bs,1,H1,W1
        x_out=x_max*x2    #bs,1,H,W *bs,i_c,H1,W1 =bs,i_c,H_max,W_max (H1和H2取较大的那个)

        return x_out


def get_kernel(kernlen=16, nsig=3):     # nsig 标准差 ,kernlen=16核尺寸      
    interval = (2*nsig+1.)/kernlen      #计算间隔 
    x = np.linspace(-nsig-interval/2., nsig+interval/2., kernlen+1)   #在前两者之间均匀产生数据

                                          #高斯函数其实就是正态分布的密度函数
    kern1d = np.diff(st.norm.cdf(x))      #先积分在求导是为啥?得到一个维度上的高斯函数值
    '''st.norm.cdf(x):计算正态分布累计分布函数指定点的函数值
        累计分布函数:概率分布函数的积分'''
    kernel_raw = np.sqrt(np.outer(kern1d, kern1d))   #np.outer计算外积,再开平方,从1维高斯参数到2维高斯参数
    kernel = kernel_raw/kernel_raw.sum()             #确保均值为1
    return kernel
自定义卷积核并执行卷积操作,需要按照以下步骤进行: 1. 导入必要的库,包括PyTorch库和numpy库。 ```python import torch import numpy as np ``` 2. 定义卷积核的权重矩阵,可以手动创建或使用随机数生成器。然后将权重矩阵转换为PyTorch张量,以便在下一步中使用。 ```python kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]).astype(np.float32) weights = torch.from_numpy(kernel).unsqueeze(0).unsqueeze(0) ``` 3. 创建输入张量,将其转换为PyTorch张量,并使用unsqueeze函数将其扩展为4D张量。 ```python input_tensor = np.random.rand(1, 1, 5, 5).astype(np.float32) input = torch.from_numpy(input_tensor).unsqueeze(0) ``` 4. 使用PyTorch中的conv2d函数进行卷积操作。将输入张量和权重矩阵传递给该函数,并指定所需的卷积参数(如步长、边界填充和输出通道数)。 ```python output = torch.nn.functional.conv2d(input, weights, stride=1, padding=0) ``` 5. 输出结果。可以使用PyTorch张量的numpy函数将张量转换为同类型的numpy数组,并使用它来输出卷积操作的结果。 ```python result = output.numpy() print(result) ``` 完整的示例代码如下所示: ```python import torch import numpy as np # 定义卷积核 kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]).astype(np.float32) # 将卷积核转换为PyTorch张量 weights = torch.from_numpy(kernel).unsqueeze(0).unsqueeze(0) # 创建输入张量 input_tensor = np.random.rand(1, 1, 5, 5).astype(np.float32) # 将输入张量转换为PyTorch张量并扩展为4D张量 input = torch.from_numpy(input_tensor).unsqueeze(0) # 执行卷积运算 output = torch.nn.functional.conv2d(input, weights, stride=1, padding=0) # 输出结果 result = output.numpy() print(result) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值