Reputation: 224
I'm trying to convert a section of code from Python to Julia and I'm having a hard time understanding the output differences between the following convolutions:
Python:
conc = [10,100,1000,5,2000,200,20]
conc_filter = [1,2,3]
sp.ndimage.convolve1d(conc, conc_filter,axis=0,mode='constant')
Output:[ 120, 1230, 2305, 5010, 4215, 6420, 640]
Julia:
conc = [10,100,1000,5,2000,200,20]
conc_filter = [1,2,3]
conv(conc,conc_filter)
Output: [10, 120, 1230, 2305, 5010, 4215, 6420, 640, 60]
Can anyone explain why the output lengths are different? In an attempt to recreate the Python output, I've tried to come up with a logical formula that relates the input/filter sizes with the index range required to slice the conv output and obtain the same result. However, I haven't had much luck. Is there a Julia function that can produce the same output?
Upvotes: 1
Views: 786
Reputation: 224
For those interested, I worked out the padding scheme used in the 'constant' mode, passed as a parameter to the Python convolution function. The difficulty in finding a relationship between the input/output sizes was due to the way left and right padding is done for symmetric vs unsymmetric convolution filters.
The Julia code below seems to match the Python equivalent for all tested input/outputs.
conc = [10,100,1000,5,2000,200,20]
conc_filter = [1,2,3]
n=length(conc)
m=length(conc_filter)
padleft=ceil(Int32,m/2)-1
padright=floor(Int32,m/2)
conc =append!(zeros(padleft),conc)
conc = append!(conc,zeros(padright))
out = zeros(n)
for i in 1:n
for j in 1:m
out[i] += conc[i+j-1]*conc_filter[m-j+1]
end
end
out
Result: [ 120, 1230, 2305, 5010, 4215, 6420, 640]
Upvotes: 1
Reputation: 6086
What Python conv routine are you using? Here is Python's numpy convolve:
>>> conc = [10,100,1000,5,2000,200,20]
>>> conc_filter = [1,2,3]
>>> numpy.convolve(conc, conc_filter,axis=0,mode='constant')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: convolve() got an unexpected keyword argument 'axis'
>>> numpy.convolve(conc, conc_filter)
array([ 10, 120, 1230, 2305, 5010, 4215, 6420, 640, 60])
You might need to peek at the documentation to your Python package and see how to make fft() type routines do what you need.
Upvotes: 2
Reputation: 2902
Assuming I understand your question correctly:
According to this answer on stackexchange, the vector length of the Julia example is correct.
N + M - 1 gives an output vector length of 9, as shown by the Julia answer.
Are you sure the Python code and/or copied output is correct?
Upvotes: 0