pytorch 实现卷积层

import torch
from torch import nn

def corr2d(X, K):
    h, w = K.shape
    Y = torch.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
    for i in range(Y.shape[0]):
        for j in range(Y.shape[1]):
            Y[i, j] = (X[i: i + h, j: j + w] * K).sum()
    return Y


class Conv2D(nn.Module):
    def __init__(self, kernel_size):
        super(Conv2D, self).__init__()
        self.weight = nn.Parameter(torch.randn(kernel_size))
        self.bias = nn.Parameter(torch.randn(1))

    def forward(self, x):
        return corr2d(x, self.weight) + self.bias

conv2d=Conv2D(kernel_size=(2,2))
print(conv2d.weight.data)
print(conv2d.bias.data)
x=torch.ones(6,6)
y=conv2d(x)
print(y.shape)

参考文献:

pytorch学习笔记(十九):二维卷积层_pytorch二维卷积kernal_size和_逐梦er的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/qq_40107571/article/details/131400049