找不到我的代码出了什么问题?(带numpy的二维矩阵卷积)

2024-10-06 10:21:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚从Andrew Ng的deeplearning.ai coursera课程中学习了矩阵卷积,我想尝试使用numpy制作自己的2D矩阵卷积,但我一直得到以下错误。(代码底部)

我不明白我做错了什么,因为第一次迭代的f=100和w=0,所以我不明白为什么aSlice = dataColor[vertStart:vertEnd, vertStart:vertEnd]是一个100乘99的矩阵。我试着对“horiEnd”做+1,但它变为100乘101。我也试过assert(dataColor.shape == (1200,1200)),但这似乎也不是问题所在。我认为问题是在for循环之后开始的。任何帮助都将不胜感激

def convSingleStep(aSlice, F = np.full((100,100), 0.000001)):
    #F = f*f filter
    s = aSlice*F
    Z = np.sum(s)
    
    return Z



def convForward(dataColor, F = np.full((100,100), 0.000001)):
    nH, nW = dataColor.shape         #1200 x 1200
    f, f = F.shape                   #100 x 100
    theNewSlice = np.zeros((nH, nW)) #1200 x 1200
    
    for h in range(nH): #nH = 1200
        vertStart = h
        vertEnd = h + f
        
        for w in range(nW): #nW = 1200
            horiStart = w
            horiEnd = w + f
            aSlice = dataColor[vertStart:vertEnd, horiStart:horiEnd]
            theNewSlice[h, w] = convSingleStep(aSlice, F = np.full((100,100), 0.000001))
            
    return theNewSlice
```----> 3     s = aSlice*F
ValueError: operands could not be broadcast together with shapes (100,99) (100,100)```

Tags: fordefnp矩阵卷积fullshapenw
1条回答
网友
1楼 · 发布于 2024-10-06 10:21:19

在循环的第一步中

h = 0, , vertEnd = 100
w = 0, , horiEnd = 100
aSlice.shape = (100,100)

这一切都很好,并按预期行事。
但是到达第1100步(11101)

h = 1100, , vertEnd = 1200 # Note the index is 1200, which requires length of 1201
w = 0, , horiEnd = 100

现在,您正在使用vertEnd = 1200设置数据范围之外的形状:

aSlice = dataColor[vertStart:vertEnd, horiStart:horiEnd]

aSlice.shape # 99, 100

这里,

aSlice[0] = dataColor[1101:1200] = dataColor[1101:] = dataColor[1101:1200]

相关问题 更多 >