Created
September 10, 2024 03:43
-
-
Save TimSC/04326ddd7565d804b0b6cc661dc26436 to your computer and use it in GitHub Desktop.
This is an implemention of torch's conv2d using scipy correlate2d.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from scipy import signal | |
def conv2d_simplified(input, weight, bias=None, padding=0): | |
# This is an implemention of torch's conv2d using scipy correlate2d. Only | |
# limited options are supported for simplicity. | |
# Inspired by https://github.com/99991/NumPyConv2D/ | |
c_out, c_in_by_groups, kh, kw = weight.shape | |
if not isinstance(padding, int): | |
raise NotImplementedError() | |
if padding: | |
input = np.pad(input, ((0, 0), (0, 0), (padding, padding), (padding, padding)), "constant") | |
outArr = np.empty((input.shape[0], c_out, input.shape[2]+1-kh, input.shape[3]+1-kw)) | |
al = np.empty((outArr.shape[2], outArr.shape[3])) | |
for k in range(input.shape[0]): | |
for i in range(weight.shape[0]): | |
al[:, :] = 0.0 | |
for j in range(weight.shape[1]): | |
al += signal.correlate2d(input[k, j, :, :], weight[i, j, :, :], 'valid') | |
outArr[k, i, :, :] = al | |
if bias is not None: | |
outArr = outArr + bias.reshape(1, c_out, 1, 1) | |
return outArr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment