在之前谈到的保序回归加速话题中,我们聊起如何利用Cython改进回归算法的性能表现。我觉得将Python优化代码的性能表现与原生Julia方案加以比对能够进一步明确大家对于速度提升的直观感受。
今天的文章将承接上一篇,因此大家在进行阅读前,不妨先对前文进行一番回顾、旨在掌握相关背景信息。
我们将借用前文中提到的两种算法,并在这里就性能表现在Julia与Python之间展开一番比拼。
线性PAVA
相关Cython代码可以通过Github上的scikit-learn进行下载,而Julia代码则来自GitHub上的Isotonic.jl。
Julia代码采用的是最为简单的PAVA表达,不掺杂任何花哨的内容与修饰;@inbounds宏的作用是客观比较Cython的执行效果并关闭bound check。function isotonic_regression(y::Vector{Float64}, weights::Vector{Float64})
@inbounds begin
n = size(y, 1)
if n <= 1
return y
end
n -= 1
while true
i = 1
pooled = 0
while i <= n
k = i
while k <= n && y[k] >= y[k+1]
k += 1
end
# Find a decreasing subsequence, and update
# all points in the sequence to the weighted average.
if y[i] != y[k]
numerator = 0.0
denominator = 0.0
for j in i : k
numerator += y[j] * weights[j]
denominator += weights[j]
end
for j in i : k
y[j] = numerator / denominator
end
pooled = 1
end
i = k + 1
end
if pooled == 0
break
end
end
end
return y
end
isoto