我想在Julia中优化以下代码,它以高度矢量化的形式编写,而MATLAB等语言则表现出色。 MATLAB中完全相同的代码花费Elapsed time is 0.277608 seconds.
,速度提高了2.8倍,所以我认为可以在Julia中完成一些工作。公平地说,我注意到MATLAB默认使用多线程,因此,如果在Julia中也启用了多线程也没问题。谢谢您的帮助。
function fit_xlin(x, y, w)
n = length(x)
regularization = 1.0e-5
xx_0_0 = fill(sum(w.*1) , n)
xx_1_0 = fill(sum(w.*x) , n)
xx_0_1 = fill(sum(w.*x) , n)
xx_1_1 = fill(sum(w.*x.*x), n)
xy_0 = fill(sum(w.*y) , n)
xy_1 = fill(sum(w.*x.*y), n)
xx_1_0 .+= regularization
xx_0_1 .+= regularization
xxk_0_0 = xx_0_0 .- w.*1
xxk_1_0 = xx_1_0 .- w.*x
xxk_0_1 = xx_0_1 .- w.*x
xxk_1_1 = xx_1_1 .- w.*x.*x
xyk_0 = xy_0 .- w.*y
xyk_1 = xy_1 .- w.*x.*y
det = xxk_0_0.*xxk_1_1 .- xxk_0_1.*xxk_1_0
c0 = (xxk_1_1.*xyk_0 .- xxk_0_1.*xyk_1)./det
c1 = (-xxk_1_0.*xyk_0 .+ xxk_0_0.*xyk_1)./det
y_est = c0 .+ c1.*x
end
using BenchmarkTools
function test_xlin()
x = rand( 0.0:4.0, 5000_000)
y = rand( 0.0:4.0, 5000_000)
w = rand( 0.0:4.0, 5000_000)
@btime fit_xlin($x, $y, $w)
end
这次是:
julia> test_xlin();
775.292 ms (46 allocations: 877.38 MiB)
答案 0 :(得分:3)
这是仍在向量化的代码,它不使用多线程。在我的计算机上,它的速度是原始计算机的两倍多,但是仍然可以在此处完成操作。
顺便说一句,我严重怀疑Matlab代码是否经过特别优化,因为正在进行一些非常浪费的操作-不必要的分配,不必要的操作(sum(w.*1)
确实很糟糕,将数组乘以1并分配一个此过程中多余的数组非常浪费:)此外,您也不需要在Matlab中分配任何矢量xx_0_0
,xx_1_0
,您可以像在Julia中那样使用广播。
无论如何,这是我的第一次尝试:
function fit_xlin2(x, y, w)
regularization = 1.0e-5
sumwx = (w' * x) + regularization
sumwy = (w' * y)
sumwxx = sum(a[1]*a[2]^2 for a in zip(w, x))
sumwxy = sum(prod, zip(w, x, y))
wx = w .* x
xxk_0_0 = sum(w) .- w
xxk_1_0 = sumwx .- wx
xxk_1_1 = sumwxx .- wx .* x
xyk_0 = sumwy .- w .* y
xyk_1 = sumwxy .- wx .* y
det = xxk_0_0 .* xxk_1_1 .- xxk_1_0 .* xxk_1_0
c0 = (xxk_1_1 .* xyk_0 .- xxk_1_0 .* xyk_1)./det
c1 = (-xxk_1_0 .* xyk_0 .+ xxk_0_0 .* xyk_1)./det
return c0 .+ c1 .* x
end
编辑:您可以通过对主循环进行矢量化处理来获得一定程度的加速。该代码比原始的Julia代码快17倍,仍然是单线程的,并且可读性强:
function fit_xlin_loop(x, y, w)
if !(size(x) == size(y) == size(w))
error("Input vectors must have the same size.")
end
regularization = 1.0e-5
sumw = sum(w)
sumwx = (w' * x) + regularization
sumwy = (w' * y)
sumwxx = sum(a[1]*a[2]^2 for a in zip(w, x))
sumwxy = sum(prod, zip(w, x, y))
y_est = similar(x)
@inbounds for i in eachindex(y_est)
wx = w[i] * x[i]
xxk_0_0 = sumw - w[i]
xxk_1_0 = sumwx - wx
xxk_1_1 = sumwxx - wx * x[i]
xyk_0 = sumwy - w[i] * y[i]
xyk_1 = sumwxy - wx * y[i]
det = xxk_0_0 * xxk_1_1 - xxk_1_0 * xxk_1_0
c0 = (xxk_1_1 * xyk_0 - xxk_1_0 * xyk_1) / det
c1 = (-xxk_1_0 * xyk_0 + xxk_0_0 * xyk_1) / det
y_est[i] = c0 + c1 * x[i]
end
return y_est
end