题解 | 实现多通道二维卷积

实现多通道二维卷积

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()))

全部评论

相关推荐

头像 会员标识
09-10 17:21
牛客_运营/测试
求求给个offer我...:笑死了,笑完过了几分钟感觉挺可悲的
点赞 评论 收藏
分享
darius_:我试了简历上有微服务和没微服务主动要简历的外包的比例都不一样,微服务稍微看看还是要写上去,人人都写你不写会被pass
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务