裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

Julia に翻訳--041 Excel にある二変量統計関数

2021年03月09日 | ブログラミング

#==========
Julia の修行をするときに,いろいろなプログラムを書き換えるのは有効な方法だ。
以下のプログラムを Julia に翻訳してみる。

Excel にある二変量統計関数
http://aoki2.si.gunma-u.ac.jp/R/bivariate.html

ファイル名: bivariate.jl  関数名: correl, covar, forcast, growth,
                                
intercept, logest, pearson,
                                 rsq, slope, steyx, trend

翻訳するときに書いたメモ

Excel に用意する関数は,あまり網羅的でもないんだなあ。

==========#

using Statistics

x = [3, 5, 4, 8, 2, 1];
y = [2, 4, 5, 7, 1, 6];

correl(x, y) = cor(x, y)

correl(x, y) # 0.492515750317586

covar(x, y) = cov(x, y, corrected=false)

covar(x, y) # 2.3611111111111107

forecast(data, y, x) = mean(y) .+ cov(x, y)/var(x) .* (data .- mean(x))

forecast(6, y, x) # 5.162162162162162
forecast(8, y, x) # 6.081081081081081
forecast([6, 8, 10], y, x)
# 3-element Array{Float64,1}:
#  5.162162162162162
#  6.081081081081081
#  7.0

function growth(y, x, data, one = false)
    all(y .> 0) || error("any y is less than or equal to zero.")
    y = log.(y)
    if one
        b = sum(x .* y) / sum(x .^ 2)
        constant = 0
    else
        b = cov(x, y) / var(x)
        constant = mean(y) - b * mean(x)
    end
    exp.(constant .+ b .* data)
end

growth(y, x, 6)       # 4.677106652484691
growth(y, x, [1, 2, 3])
# 3-element Array{Float64,1}:
#  2.3140857250280833
#  2.6637840201891647
#  3.0663277636912243

growth(y, x, 6, true) # 5.228738441530447
growth(y, x, [1, 2, 3], true)
# 3-element Array{Float64,1}:
#  1.3174459890112413
#  1.7356639339618076
#  2.2866434880694557

intercept(y, x) = mean(y) - cov(x, y) / var(x) * mean(x)

intercept(y, x) # 2.4054054054054057

function logest(y, x, one = false)
    all(y .> 0) || error("any y is less than or equal to zero.")
    y = log.(y)
    if one
        b = sum(x .* y) / sum(x .^ 2)
        constant = 0
    else
        b = cov(x, y) / var(x)
        constant = mean(y) - b * mean(x)
    end
    Dict(:model => "a*b^x", :a => exp(constant), :b => exp(b))
end

logest(y, x)
# Dict{Symbol,Any} with 3 entries:
#   :a     => 2.0103
#   :b     => 1.15112
#   :model => "a*b^x"

logest(y, x, true)
# Dict{Symbol,Any} with 3 entries:
#   :a     => 1.0
#   :b     => 1.31745
#   :model => "a*b^x"

pearson(x, y) = cor(x, y)

pearson(x, y) # 0.492515750317586

rsq(y, x) = cor(y, x)^2

rsq(y, x) # 0.2425717643108947

slope(y, x, zero = false) = zero ? sum(x .* y) / sum(x .^ 2) : cov(x, y) / var(x)

slope(y, x) # 0.45945945945945943
slope(y, x, true) # 0.9243697478991597

function steyx(y, x)
    n = length(x)
    sqrt((var(y) - cov(x, y) ^ 2 / var(x)) * (n - 1) / (n - 2))
end

steyx(y, x) # 2.254125347242491

trend(y, x, data, zero = false) = zero ? sum(x .* y) / sum(x .^ 2) .* data :
                         intercept(y, x) .+ (cov(x, y) / var(x)) .* data

trend(y, x, 6)       # 5.162162162162162
trend(y, x, [4, 5, 6])
# 3-element Array{Float64,1}:
#  4.243243243243244
#  4.7027027027027035
#  5.162162162162162

trend(y, x, 6, true) # 5.546218487394958
trend(y, x, [4, 5, 6], true)
# 3-element Array{Float64,1}:
#  3.697478991596639
#  4.621848739495799
#  5.546218487394958

 

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Julia に翻訳--040 自己相関係数

2021年03月09日 | ブログラミング

#==========
Julia の修行をするときに,いろいろなプログラムを書き換えるのは有効な方法だ。
以下のプログラムを Julia に翻訳してみる。

自己相関係数
http://aoki2.si.gunma-u.ac.jp/R/acf.html

ファイル名: acf.jl  関数名: acf

翻訳するときに書いたメモ

StatsBase には autocor がある。

==========#

using Statistics, Plots

function acf(x, k)
    n = length(x)
    (n >= 3 && n-k >= 2 && k >= 1) || error("invalid argument")
    mean2 = mean(x)
    num = sum((x[1:n-k] .- mean2) .* (x[k+1:n] .- mean2))
    den = var(x)*(n-1)
    num/den
end

x = [662, 944, 816, 946, 355, 448, 731, 420, 670, 867, 651, 307, 393, 812, 616, 721, 658, 653,
     347, 368, 687, 685, 710, 686, 770, 508, 458, 335, 735, 697];

acf(x, 1) # 0.1854958594271549
acf(x, 5) # -0.1833559602380119
y = [acf(x, i) for i = 1:length(x)-2]
pyplot()
plt = plot(y, seriestype=:sticks, color=:black, grid=false,
           tick_direction=:out, label="")
hline!([0], color=:black, label="")

using StatsBase
autocor(float.(x), [1, 2])
# 2-element Array{Float64,1}:
#   0.1854958594271549
#  -0.2241014077628256
y2 = autocor(float.(x), 1:length(x)-2)
plt2 = plot(y2, seriestype=:sticks, color=:black, grid=false,
           tick_direction=:out, label="")
hline!([0], color=:black, label="")

plot(plt, plt2)

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Julia に翻訳--039 ホッジス・レーマン推定量

2021年03月09日 | ブログラミング

#==========
Julia の修行をするときに,いろいろなプログラムを書き換えるのは有効な方法だ。
以下のプログラムを Julia に翻訳してみる。

ホッジス・レーマン推定量
http://aoki2.si.gunma-u.ac.jp/R/HLe.html

ファイル名: hle.jl  関数名: hle

翻訳するときに書いたメモ

素直に 2 重の for ループで書くと遅い。
内包表記を使う場合と,外積を計算する方法はほぼ同じ速度で,R の 3 倍ほど速い。

==========#

using Statistics

function hle(x)
    n = length(x)
    temp = []
    for j in 1:n
        for i in j:n
            append!(temp, (x[i] + x[j]) / 2)
        end
    end
    median(temp)
end

x = [2.3, 3.5, 6.7, 8.2];
hle(x) # 5.175

using Random
Random.seed!(123);
x = randn(10000);
using RCall
R"""
HLe = function(x) {
 temp <- outer(x, x, "+")/2
 return(median(temp[upper.tri(temp, diag=TRUE)]))
}
system.time(print(HLe($x)))
"""
# [1] 0.01280589
# RObject{RealSxp}
#    user  system elapsed 
#   5.425   1.318   6.758 

@time hle(x)
# 9.871744 seconds (50.01 M allocations: 1.529 GiB, 9.67% gc time)
# 0.012805892306661737

using LinearAlgebra
function hle2(x)
    temp = [(x1 + x2) * 0.5 for x1 in x, x2 in x]
    median(temp[tril(trues(size(temp)))])
end

@time hle2(x)
# 1.810776 seconds (13 allocations: 1.513 GiB, 6.54% gc time)
# 0.012805892306661737

function hle3(x)
    temp = (x .+ x') .* 0.5
    median(temp[tril(trues(size(temp)))])
end

@time hle3(x)
# 1.801151 seconds (237.61 k allocations: 1.524 GiB, 6.21% gc time)
# 0.012805892306661737

 

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Julia に翻訳--038 同値のある場合の中央値

2021年03月09日 | ブログラミング

#==========
Julia の修行をするときに,いろいろなプログラムを書き換えるのは有効な方法だ。
以下のプログラムを Julia に翻訳してみる。

同値のある場合の中央値
http://aoki2.si.gunma-u.ac.jp/R/median.html

ファイル名: mymedian.jl  関数名: mymedian

翻訳するときに書いたメモ

return 文の中の accu は accuracy

==========#

using Statistics

mymedian = function (x; y=[], accuracy=0)
    if length(y) == 0
        med = median(x)
        ntie = sum(x .== med)
        if ntie != 1 && accuracy > 0
            x = vcat(x[x .!= med], (med-(ntie+1)*accuracy/2/ntie) .+ (1:ntie)/ntie)
            med = median(x)
        end
        return med
    else
        k = length(y)
        length(x)-1 == k || error("length(x) - 1 ≠ length(y)")
        csum = cumsum(y)
        n = csum[k]
        for i in 1:k
            if csum[i] >= n/2
                return x[i]-accuracy/2+(n/2-csum[i-1])/y[i]*(x[i+1]-x[i])
            end
        end    
    end
end

x = [1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5]
mymedian(x, accuracy=1) # 3.125

x = 1:6
f = [2, 4, 8, 6, 2]
mymedian(x, y=f, accuracy=1) # 3.125

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

PVアクセスランキング にほんブログ村

PVアクセスランキング にほんブログ村