【问题标题】:scipy convolve2d outputs wrong valuesscipy convolve2d 输出错误的值
【发布时间】:2017-03-07 23:06:24
【问题描述】:

这是我用来检查 convolve2d 正确性的代码

import numpy as np
from scipy.signal import convolve2d

X = np.random.randint(5, size=(10,10))
K = np.random.randint(5, size=(3,3))
print "Input's top-left corner:"
print X[:3,:3]
print 'Kernel:'
print K

print 'Hardcording the calculation of a valid convolution (top-left)'
print (X[:3,:3]*K)
print 'Sums to'
print (X[:3,:3]*K).sum()
print 'However the top-left value of the convolve2d result'
Y = convolve2d(X, K, 'valid')
print Y[0,0]

在我的电脑上,结果如下:

Input's top-left (3x3) corner:
[[0 0 0]
 [1 1 2]
 [1 3 0]]
Kernel:
[[4 1 1]
 [0 3 3]
 [2 1 2]]
Hardcording the calculation of a valid convolution (top-left)
[[0 0 0]
 [0 3 6]
 [2 3 0]]
Sums to
14
However the top-left value of the convolve2d result
10

背景故事:我一直在调试一个 convnet 库,不知怎么的,渐变总是错误的。几周后,我得出结论认为一切正常,因此我徒手检查了 convolve2d 函数。

【问题讨论】:

    标签: python debugging numpy scipy convolution


    【解决方案1】:

    我认为问题在于您没有执行 SciPy 实现的操作。我不会详述细节或基础,只为您提供解决方案:

    反转内核。

    >>> import numpy as np
    
    >>> arr = np.array([[0, 0, 0],
                        [1, 1, 2],
                        [1, 3, 0]])
    
    >>> kernel = np.array([[4, 1, 1],
                           [0, 3, 3],
                           [2, 1, 2]])
    
    >>> from scipy.signal import convolve2d
    
    >>> convolve2d(arr, kernel[::-1, ::-1])
    array([[ 0,  0,  0,  0,  0],
           [ 2,  3,  7,  4,  4],
           [ 5, 13, 14, 12,  0],
           [ 4, 14, 16,  6,  8],
           [ 1,  4,  7, 12,  0]])
    
    >>> convolve2d(arr, kernel[::-1, ::-1], 'valid')
    array([[14]])
    

    【讨论】:

    • 感谢您的回复,文档对我来说并不简单
    • @botcs 是的,我知道。我总是使用astropy.convolution.convolve,因为它以您(和我)想的方式实现它 - 无需反转内核。
    【解决方案2】:

    表达式(X[:3,:3]*K).sum() 不正确。对于卷积,您必须反转内核,例如(X[:3,:3]*K[::-1,::-1]).sum()

    【讨论】:

    • 谢谢,我知道根据定义我们必须反转内核,我很久以前完全忘记了它
    猜你喜欢
    • 2015-09-17
    • 1970-01-01
    • 2016-08-13
    • 2013-12-03
    • 2022-09-29
    • 2016-08-14
    • 2013-03-04
    • 2016-03-03
    • 2023-04-02
    相关资源
    最近更新 更多