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

实现多通道二维卷积

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-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
团子请爱我一次_十月...:不是戈门,干哪来了,这就是java嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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