本文介绍了scipy convolve2d 输出错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我用来检查 convolve2d 正确性的代码
Here is my code which I used for checking the correctness of 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]
在我的电脑上,结果如下:
On my computer this results in the following:
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 函数.
Background story: I've been debugging a convnet library, and somehow the gradients were always wrong. After a few weeks I concluded that everything should be working fine, so I checked the convolve2d function by bare hand.
推荐答案
表达式 (X[:3,:3]*K).sum()
不正确.对于卷积,您必须反转内核,例如(X[:3,:3]*K[::-1,::-1]).sum()
The expression (X[:3,:3]*K).sum()
is not correct. For convolution, you have to reverse the kernel, e.g. (X[:3,:3]*K[::-1,::-1]).sum()
这篇关于scipy convolve2d 输出错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!