scipy convolve2d输出错误的值

时间:2016-10-25 19:04:17

标签: python debugging numpy scipy convolution

这是我用来检查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函数。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

我认为问题在于你没有做SciPy实施的工作。我不会详细介绍细节或基础,但只为您提供解决方案:

反转内核。

CCCryptorStatus CCCryptorGCM(
                 CCOperation     op, // kCCEncrypt, kCCDecrypt
                 CCAlgorithm     kCCAlgorithmAES,
                 const void      *key,    size_t  keyLength,
                 const void      *iv,     size_t  ivLen,
                 const void      *aData,  size_t  aDataLen, // does not work
                 const void      *dataIn, size_t  dataInLength,
                 void            *dataOut,
                 const void      *tag,    size_t *tagLength);