题解 | 实现多通道二维卷积
实现多通道二维卷积
https://www.nowcoder.com/practice/bded3fd04b234685b9a178d43ecec052
# 注意机考时class外内容已写好,不用考虑处理输入输出
# 题目表述中没有任何卷积公式相关描述,只有输入输出格式描述
# If you need to import additional packages or classes, please import here.
import numpy as np
class Solution:
def Conv2D(self, input_data: np.ndarray, weight: np.ndarray, bias: np.ndarray, stride: int, padding: int, dilation: int) -> np.ndarray:
c, h, w = input_data.shape
_, c_out, k_h, k_w = weight.shape
k_h_eff = dilation * (k_h - 1) + 1
k_w_eff = dilation * (k_w - 1) + 1
h_out = (h + 2 * padding - k_h_eff) // stride + 1
w_out = (w + 2 * padding - k_w_eff) // stride + 1
if padding > 0:
input_padded = np.pad(input_data, ((0, 0), (padding, padding), (padding, padding)), mode="constant")
else:
input_padded = input_data
output = np.zeros((c_out, h_out, w_out))
for c_o in range(c_out):
for h in range(h_out):
for w in range(w_out):
h_st_pos = h * stride
w_st_pos = w * stride
reg = input_padded[:, h_st_pos: h_st_pos + k_h_eff:dilation, w_st_pos:w_st_pos + k_w_eff:dilation]
output[c_o, h, w] = np.sum(reg * weight[:, c_o, :, :])
if bias is not None:
output[c_o] += bias[c_o]
return output
if __name__ == "__main__":
c, x, y = map(int, input().split())
input_data = np.array(list(map(np.float64, input().split()))).reshape(c, x, y)
in_ch, out_sh, k1, k2 = map(int, input().split())
weight = np.array(list(map(np.float64, input().split()))).reshape(out_sh, in_ch, k1, k2)
bias, stride, padding, dilation = map(int, input().split())
if bias > 0:
bias = np.array(list(map(np.float64, input().split())))
else:
bias = np.array([0 for i in range(out_sh)])
function = Solution()
output = function.Conv2D(input_data, weight, bias, stride, padding, dilation)
print(' '.join(f'{x:.4f}' for x in output.flatten().tolist()))


查看9道真题和解析