裏 RjpWiki

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

みんな大好き,Julia の速度自慢

2021年01月25日 | ブログラミング

つい一月半位前に

みんな大好き,R と Python の速度比較

というのを書いた。そのときには,Julia なんて眼中になかったのだ。

そこで,Julia で同じことをやるとどんだけ〜〜速いかやってみた。

 

結論

Julia 速い。ただし,初回は若干時間が掛かる。

Python は ピアソンの積率相関係数行列,分散・共分散行列,重回帰分析で健闘している。

 

using CSV, DataFrames

test.csv は 100000行, 1500列のデータ

データ読み込み

@time df = CSV.read("test.csv", DataFrame)
#  23.113033 seconds (24.45 M allocations: 2.275 GiB, 3.44% gc time)
# R では,変数型を指定して 33.607, Pythonでは 28.793 だったので,かなり速いといえよう
# 以下では 単位は秒

単変量分析

@time a = mapcols(sum, df)  # 0.0777, R: 0.739, Pyhton: 5.416
using Statistics
@time a = mapcols(mean, df) # 0.0760, R: 0.662, Python:  5.352
@time a = mapcols(var, df)  # 0.123,  R: 0.552, Python:  8.466
@time a = mapcols(std, df)  # 0.125,  R: 0.561, Python: 11.574

2変量分析

ピアソンの積率相関係数
@time a = cor(df[:, 1], df[:, 2]) # 0.00106, R: 0.011, Python: 0.004

多変量回帰

ピアソンの積率相関係数行列
@time a = cor(Array{Float64,2}(df)) # 4.331, R: 100.509, Python: 360.236

スピアマンの順位相関係数行列
using StatsBase
function spearmancor(x::Array{Float64,2})
    rank = similar(x, Float64)
    for i = 1:size(x, 2)
        rank[:, i] = tiedrank(x[:, i])
    end
    return cor(rank)
end
@time a = spearmancor(Array{Float64,2}(df)) # 23.354, R: 140.892, Python 4238.496

分散・共分散行列
@time a = cov(Array{Float64,2}(df));  # 4.469, R: 106.829, Python: 4.987

重回帰分析
using GLM
@time a = lm(@formula(X1 ~ X2+X3+X4+X5+X6+X7+X8+X9+X10), df) # 0.0255, R: 0.163, Python 0.031

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

簡単なプログラミング問題を Julia で解く

2021年01月25日 | ブログラミング

以下では Python の解答例が示されているので,Julia でやったらどうなるか書いてみた。

10 Algorithms To Solve Before your Python Coding Interview

関数として定義したが,一般的に Python よりは短く簡潔に書ける。

1. Reverse Integer

Given an integer, return the integer with reversed digits. 
Note: The integer could be either positive or negative.

func1(x) = (x < 0 ? "-" : "") * reverse(string(abs(x)))

println(func1(-123))
println(func1(123))

-321
321

2. Average Words Length

For a given sentence, return the average word length. Note: Remember to
remove punctuation first.

たかが mean() を使うだけで using Statistics するのは,大げさだなあ。

using Statistics
func2(sentence) = mean(length.(split(replace(sentence, r"[!?':,,.]" => ""))))

sentence1 = "Hi all, my name is Tom... I am originally from Australia."
sentence2 = "I need to work very hard to learn more about algorithms in Python!"
println(func2(sentence1))
println(func2(sentence2))

3.8181818181818183
4.076923076923077

3. Add Strings

Given two non-negative integers num1 and num2 represented as string,
return the sum of num1 and num2. You must not use any built-in
BigInteger library or convert the inputs to integer directly. Notes:
Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not
contain any leading zero

func3(a, b) = parse(Int, a) + parse(Int, b)

num1 = "364"
num2 = "1836"
println(func3(num1, num2))

2200

4. First Unique Character

Given a string, find the first non-repeating character in it and return
its index. If it doesn’t exist, return -1. Note: all the input strings
are already lowercase.

function func4(s)
    t = split(s, "")
    for i in 1:length(t)
        if count(t .t[i]) 1
            return i
        end
    end
    return -1
end

println(func4("alphabet")) # Julia では,文字位置は1から数える
println(func4("barbados"))
println(func4("ppaap"))

2
3
-1

5. Valid Palindrome

Given a non-empty string s, you may delete at most one character. Judge
whether you can make it a palindrome. The string will only contain
lowercase characters a-z.

function func5(s)
    len = length(s)
    for i = 1:len
        t = s[1:i-1] * s[i+1:len]
        if t reverse(t)
            return true
        end
    end
    return false
end

s = "radkar"
println(func5(s))
println(func5("abcde"))

true
false

6. Monotonic Array

Given an array of integers, determine whether the array is monotonic or
not.

func6(x) = x sort(x) || x sort(x, rev=true)

println(func6([6, 5, 4, 4]))
println(func6([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]))
println(func6([1, 1, 2, 3, 7]))

true
false
true

7. Move Zeroes

Given an array nums, write a function to move all zeroes to the end of
it while maintaining the relative order of the non-zero elements.

発想の転換をすれば,解は簡単に求まる。

function func7(x)
    a = [i for i in x if i != 0]
    append!(a, repeat([0], count(x .0)))
    return a
end

array1 = [0,1,0,3,12]
println(func7(array1))
array2 = [1,7,0,0,8,0,10,12,0,4]
println(func7(array2))

[1, 3, 12, 0, 0]
[1, 7, 8, 10, 12, 4, 0, 0, 0, 0]

8. Fill The Blanks

Given an array containing None values fill in the None values with most
recent non None value in the array.

Julia に None はないので,NaN に置き換えて考える。

function func8(x)
    for i in 2:length(x)
        if isnan(x[i])
            x[i] = x[i-1]
        end
    end
    x
end

array1 = [1,NaN,2,3,NaN,NaN,5,NaN];
println(func8(array1))

[1.0, 1.0, 2.0, 3.0, 3.0, 3.0, 5.0, 5.0]

9. Matched & Mismatched Words

Given two sentences, return an array that has the words that appear in
one sentence and not the other and an array with the words in common.

function func9(a, b)
    a = Set(split(a, " "))
    b = Set(split(b, " "))
    sort([i for i in union(a, b)]), sort([i for i in intersect(a, b)])
end

sentence1 = "We are really pleased to meet you in our city"
sentence2 = "The city was hit by a really heavy storm"
u, i = func9(sentence1, sentence2)
println(u)
println(i)

SubString{String}["The", "We", "a", "are", "by", "city", "heavy", "hit", "in", "meet", "our", "pleased", "really", "storm", "to", "was", "you"]
SubString{String}["city", "really"]

10. Prime Numbers Array

Given k numbers which are less than n, return the set of prime number
among them Note: The task is to write a program to print all Prime
numbers in an Interval. Definition: A prime number is a natural number
greater than 1 that has no positive divisors other than 1 and itself.

参照先の解答例は n 以下の素数リストを求めるだけのものだけど,ちょっと違うんじゃないか?

function func10(k)
    n = maximum(k)
    primes = [2]
    for i = 3:2:n
        isprime = true
        for j = 2:floor(Int, sqrt(i))
            if mod(i, j) 0
                isprime = false
                break
            end
        end
        if isprime
            append!(primes, i)
        end
    end
    sort([s for s in intersect(Set(k), Set(primes))])
end

n 以下の値の k 個の数のリストから,素数のみから成るリストを求めよ

k = [2, 1, 3, 4, 3, 7, 13, 18, 27, 35]
func10(k)

  2
  3
  7
 13

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

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

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