srand(1234);
x = [] # 何でも入るリスト
0-element Array{Any,1}
x = Int[] # Int型のみのリスト
0-element Array{Int64,1}
x = Vector{Int}() # Int[]と同じ
0-element Array{Int64,1}
x = [1,2,3] # 3要素からなるリスト
3-element Array{Int64,1}: 1 2 3
fill(42, 10)
10-element Array{Int64,1}: 42 42 42 42 42 42 42 42 42 42
fill("foo", 4)
4-element Array{String,1}: "foo" "foo" "foo" "foo"
x = [1,2,3]
3-element Array{Int64,1}: 1 2 3
push!(x, 4) # 右に追加
4-element Array{Int64,1}: 1 2 3 4
unshift!(x, 0) # 左に追加
5-element Array{Int64,1}: 0 1 2 3 4
append!(x, [5,6,7]) # 別のベクトルを追加
8-element Array{Int64,1}: 0 1 2 3 4 5 6 7
x = [1,2,3,4,5]
5-element Array{Int64,1}: 1 2 3 4 5
pop!(x) # 右端を削除
5
x
4-element Array{Int64,1}: 1 2 3 4
shift!(x) # 左端を削除
1
x
3-element Array{Int64,1}: 2 3 4
deleteat!(x, 2) # 特定の場所の要素を削除
2-element Array{Int64,1}: 2 4
issorted([1,2,3,4])
true
issorted([1,3,2,4])
false
x = [1,5,4,3,7,6,2]
7-element Array{Int64,1}: 1 5 4 3 7 6 2
sort(x) # ベクトルを新しく作る
7-element Array{Int64,1}: 1 2 3 4 5 6 7
sort(x, rev=true) # 逆順でソート
7-element Array{Int64,1}: 7 6 5 4 3 2 1
sort!(x) # ベクトルを上書きする
7-element Array{Int64,1}: 1 2 3 4 5 6 7
x = [1,2,3,4]
4-element Array{Int64,1}: 1 2 3 4
reverse(x) # ベクトルを新しく作る
4-element Array{Int64,1}: 4 3 2 1
x == [1,2,3,4]
true
reverse!(x) # ベクトルを上書きする
4-element Array{Int64,1}: 4 3 2 1
x == [1,2,3,4]
false
x = [1,2,3,4,5,6]
6-element Array{Int64,1}: 1 2 3 4 5 6
shuffle(x) # ベクトルを新しく作る
6-element Array{Int64,1}: 2 1 3 6 4 5
x == [1,2,3,4,5,6]
true
shuffle!(x) # ベクトルを上書きする
6-element Array{Int64,1}: 6 1 5 2 3 4
x == [1,2,3,4,5,6]
false
vcat([1,2,3], [4,5,6]) # 縦方向 => ベクトル
6-element Array{Int64,1}: 1 2 3 4 5 6
hcat([1,2,3], [4,5,6]) # 横方向 => 行列
3×2 Array{Int64,2}: 1 4 2 5 3 6
Dict() # 何でも入る空の辞書
Dict{Any,Any} with 0 entries
Dict{String,Int}() # Stringがキー、Intが値の空の辞書
Dict{String,Int64} with 0 entries
Dict("one" => 1, "two" => 2) # 初期値のある辞書
Dict{String,Int64} with 2 entries: "two" => 2 "one" => 1
haskey(Dict("one" => 1, "two" => 2), "two")
true
haskey(Dict("one" => 1), "two")
false
d = Dict("one" => 1, "two" => 2)
Dict{String,Int64} with 2 entries: "two" => 2 "one" => 1
d["one"]
1
d["three"] # キーがなければエラー
KeyError: key "three" not found Stacktrace: [1] getindex(::Dict{String,Int64}, ::String) at ./dict.jl:474
d = Dict("one" => 1, "two" => 2)
Dict{String,Int64} with 2 entries: "two" => 2 "one" => 1
get(d, "one", 0) # 第三引数がデフォルト値
1
get(d, "three", 0)
0
d = Dict("one" => 1, "two" => 2)
Dict{String,Int64} with 2 entries: "two" => 2 "one" => 1
d["three"] = 3
3
d
Dict{String,Int64} with 3 entries: "two" => 2 "one" => 1 "three" => 3
d = Dict("one" => 1, "two" => 2)
Dict{String,Int64} with 2 entries: "two" => 2 "one" => 1
keys(d) # イテレータとして取り出す
Base.KeyIterator for a Dict{String,Int64} with 2 entries. Keys: "two" "one"
collect(keys(d)) # ベクトルとして取り出す
2-element Array{String,1}: "two" "one"
values(d)
Base.ValueIterator for a Dict{String,Int64} with 2 entries. Values: 2 1
collect(values(d))
2-element Array{Int64,1}: 2 1
Set{Int}() # 空の集合
Set{Int64}()
Set([1,2,3]) # ベクトルから
Set([2, 3, 1])
Set(["foo", "bar", "baz"])
Set(String["bar", "baz", "foo"])
2 in Set([1,2,3])
true
4 in Set([1,2,3])
false
2 ∈ Set([1,2,3]) # ∈ は in の別名
true
s = Set([1,2,3])
push!(s, 4)
Set([4, 2, 3, 1])
union!(s, [5, 6])
Set([4, 2, 3, 5, 6, 1])
s1 = Set([1,2,3])
s2 = Set([2,3,4,5])
Set([4, 2, 3, 5])
union(s1, s2) # 和集合
Set([4, 2, 3, 5, 1])
s1 ∪ s2 # \cupは和集合
Set([4, 2, 3, 5, 1])
intersect(s1, s2) # 積集合
Set([2, 3])
s1 ∩ s2 # \capは積集合
Set([2, 3])
setdiff(s1, s2) # 差集合
Set([1])
s = Set([1,2,3])
collect(s) # 順番は順不同
3-element Array{Int64,1}: 2 3 1
length("foo")
3
length("αβγ")
3
sizeof("foo")
3
sizeof("αβγ")
6
convert(Vector{UInt8}, "foo")
3-element Array{UInt8,1}: 0x66 0x6f 0x6f
convert(Vector{UInt8}, "αβγ")
6-element Array{UInt8,1}: 0xce 0xb1 0xce 0xb2 0xce 0xb3
Vector{UInt8}("foo") # これもOK
3-element Array{UInt8,1}: 0x66 0x6f 0x6f
convert(String, [0x66, 0x6f, 0x6f])
"foo"
convert(String, [0xce, 0xb1, 0xce, 0xb2, 0xce, 0xb3])
"αβγ"
String([0x66, 0x6f, 0x6f]) # これもOK
"foo"
replace("hello, world", "world", "there")
"hello, there"
replace("a5b4ra221ca1d856ab86r7a7", r"\d+", "")
"abracadabra"
collect("foo")
3-element Array{Char,1}: 'f' 'o' 'o'
collect("αβγ")
3-element Array{Char,1}: 'α' 'β' 'γ'
"foo" * "bar"
"foobar"
string("foo", 123)
"foo123"
join(["foo", "bar", "baz"], ",")
"foo,bar,baz"
split("foo,bar,baz", ",")
3-element Array{SubString{String},1}: "foo" "bar" "baz"
split("123 45 567", r"\s+")
3-element Array{SubString{String},1}: "123" "45" "567"
rpad(123, 5)
"123 "
lpad(123, 5)
" 123"
println(" left aligned: ", rpad(123, 5))
println("right aligned: ", lpad(123, 5))
left aligned: 123 right aligned: 123
@sprintf("%5d", 123)
" 123"
chomp("foo bar\n")
"foo bar"
chomp("foo bar\r\n")
"foo bar"
strip(" foo bar ") # 両側
"foo bar"
lstrip(" foo bar ") # 左のみ
"foo bar "
rstrip(" foo bar ") # 右のみ
" foo bar"
uppercase("foo")
"FOO"
lowercase("FOO")
"foo"
readstring("data/julia.md")
"Juliaは技術計算のための動的言語で、以下の様な機能を備えています。\n\n- 多重ディスパッチ\n- JITコンパイル\n- マクロなどのメタプログラミング\n"
readlines("data/julia.md") # 改行で分割
5-element Array{String,1}: "Juliaは技術計算のための動的言語で、以下の様な機能を備えています。" "" "- 多重ディスパッチ" "- JITコンパイル" "- マクロなどのメタプログラミング"
i = 1
for line in eachline("data/julia.md")
println(i, ": ", line)
i += 1
end
1: Juliaは技術計算のための動的言語で、以下の様な機能を備えています。 2: 3: - 多重ディスパッチ 4: - JITコンパイル 5: - マクロなどのメタプログラミング
read("data/julia.md")
193-element Array{UInt8,1}: 0x4a 0x75 0x6c 0x69 0x61 0xe3 0x81 0xaf 0xe6 0x8a 0x80 0xe8 0xa1 ⋮ 0x83 0xa9 0xe3 0x83 0x9f 0xe3 0x83 0xb3 0xe3 0x82 0xb0 0x0a
isfile("data/julia.md")
true
isfile("data/python.md")
false
filesize("data/julia.md") # 単位はバイト
193
file = open("data/julia.md")
IOStream(<file data/julia.md>)
isopen(file) # ファイルが開いているか判定する
true
readline(file) # 1行読み込む
"Juliaは技術計算のための動的言語で、以下の様な機能を備えています。"
close(file)
isopen(file)
false
file = open("data/julia.md")
IOStream(<file data/julia.md>)
position(file) # 最初の位置は0
0
sizeof(readline(file)) # 1行(改行含む)を読む
95
position(file) # 1行分読み込み位置が進む
96
eof(file) # 読み込み位置は末尾か判定
false
sizeof(read(file)) # 残りすべてを読み込む
97
eof(file)
true
# open ... do ... endはdoの中でエラーが起きても必ずファイルを閉じる
open("data/julia.md") do file
println(readline(file))
div(1, 0) # エラー!
end
Juliaは技術計算のための動的言語で、以下の様な機能を備えています。
DivideError: integer division error Stacktrace: [1] open(::##1#2, ::String) at ./iostream.jl:152
using CodecZlib # https://github.com/bicycle1885/CodecZlib.jl
file = GzipDecompressionStream(open("data/julia.md.gz"))
TranscodingStreams.TranscodingStream{CodecZlib.GzipDecompression,IOStream}(<state=idle>)
readlines(file)
5-element Array{String,1}: "Juliaは技術計算のための動的言語で、以下の様な機能を備えています。" "" "- 多重ディスパッチ" "- JITコンパイル" "- マクロなどのメタプログラミング"
close(file)
write("data/output.txt", "アブラカダブラ\n")
22
readstring("data/output.txt")
"アブラカダブラ\n"
file = open("data/output.txt", "w")
println(file, "寿限無寿限無")
close(file)
readstring("data/output.txt")
"寿限無寿限無\n"
file = open("data/object.dat", "w")
serialize(file, "テキスト")
serialize(file, 3.14)
serialize(file, [10, 20, 30])
serialize(file, Dict("愛里寿" => "センチュリオン", "ミカ" => "BT-42"))
close(file)
file = open("data/object.dat")
while !eof(file)
@show deserialize(file)
end
close(file)
deserialize(file) = "テキスト" deserialize(file) = 3.14 deserialize(file) = [10, 20, 30] deserialize(file) = Dict("ミカ"=>"BT-42","愛里寿"=>"センチュリオン")
run(`echo "hello"`)
hello
readstring(`ls data`)
"julia.md\njulia.md.gz\nobject.dat\noutput.txt\n"
read(`ls data`)
43-element Array{UInt8,1}: 0x6a 0x75 0x6c 0x69 0x61 0x2e 0x6d 0x64 0x0a 0x6a 0x75 0x6c 0x69 ⋮ 0x0a 0x6f 0x75 0x74 0x70 0x75 0x74 0x2e 0x74 0x78 0x74 0x0a
pipe, proc = open(`ls data`) # パイプとプロセス
(Pipe(RawFD(-1) closed => RawFD(51) open, 0 bytes waiting), Process(`ls data`, ProcessExited(0)))
while !eof(pipe)
println(readline(pipe))
end
julia.md julia.md.gz object.dat output.txt
proc
Process(`ls data`, ProcessExited(0))
filter(isodd, [1,2,3,4,5])
3-element Array{Int64,1}: 1 3 5
filter(x->x>2, [1,2,3,4,5])
3-element Array{Int64,1}: 3 4 5
any(isodd, [1,2,3,4])
true
any(isodd, [2,4,6,8])
false
all(isodd, [1,2,3,4])
false
all(isodd, [1,3,5,7])
true
map(sin, [0.0, 1.0, 2.0, 3.0])
4-element Array{Float64,1}: 0.0 0.841471 0.909297 0.14112
sin.([0.0, 1.0, 2.0, 3.0])
4-element Array{Float64,1}: 0.0 0.841471 0.909297 0.14112
foldl(+, 0, [1,2,3]) # 総和の計算
6
foldl(+, [1,2,3]) # 第二引数は省略可
6
# 分岐する式の作成
foldr((x, r)->:(if x == $(x); print($(x)); else; $(r); end), :(nothing), [1,2,3])
:(if x == 1 # In[146], line 2: print(1) else # In[146], line 2: if x == 2 # In[146], line 2: print(2) else # In[146], line 2: if x == 3 # In[146], line 2: print(3) else # In[146], line 2: nothing end end end)
sort(randn(100000)) # コンパイルのため測定前に一度実行する
@elapsed sort(randn(100000)) # 単位は秒
0.008851748
[@elapsed sort(randn(100000)) for _ in 1:10]
10-element Array{Float64,1}: 0.00876565 0.0156572 0.00870781 0.00845791 0.00924334 0.0104665 0.00999714 0.0109102 0.0105973 0.00948196
sort(randn(100000)) # コンパイルのため測定前に一度実行する
@allocated sort(randn(100000)) # 単位はバイト
1600240
[@allocated sort(randn(100000)) for _ in 1:10]
10-element Array{Int64,1}: 1600240 1600240 1600240 1600240 1600240 1600240 1600240 1600240 1600240 1600240
sort(randn(100000)) # コンパイルのため測定前に一度実行する
@time sort(randn(100000));
0.008674 seconds (9 allocations: 1.526 MiB)
for _ in 1:10
@time sort(randn(100000))
end
0.011001 seconds (5 allocations: 1.526 MiB) 0.010731 seconds (5 allocations: 1.526 MiB) 0.010590 seconds (5 allocations: 1.526 MiB) 0.008951 seconds (5 allocations: 1.526 MiB) 0.009545 seconds (5 allocations: 1.526 MiB) 0.008640 seconds (5 allocations: 1.526 MiB) 0.008199 seconds (5 allocations: 1.526 MiB) 0.008194 seconds (5 allocations: 1.526 MiB) 0.009020 seconds (5 allocations: 1.526 MiB) 0.008863 seconds (5 allocations: 1.526 MiB)
100000 * sizeof(Float64) * 2 / 1024^2 # 100000要素の倍精度浮動小数点数のメモリ割り当て量 (MiB)
1.52587890625
using BenchmarkTools # https://github.com/JuliaCI/BenchmarkTools.jl
@benchmark sort(randn(100000))
BenchmarkTools.Trial: memory estimate: 1.53 MiB allocs estimate: 5 -------------- minimum time: 7.214 ms (0.00% GC) median time: 8.233 ms (0.00% GC) mean time: 8.661 ms (1.33% GC) maximum time: 25.404 ms (0.00% GC) -------------- samples: 577 evals/sample: 1
@benchmark sort(randn(10))
BenchmarkTools.Trial: memory estimate: 400 bytes allocs estimate: 3 -------------- minimum time: 421.925 ns (0.00% GC) median time: 452.987 ns (0.00% GC) mean time: 554.083 ns (3.35% GC) maximum time: 19.120 μs (0.00% GC) -------------- samples: 10000 evals/sample: 199
function bubblesort(x)
x = copy(x)
swapped = true
while swapped
swapped = false
for i in 1:endof(x)-1
if x[i+1] < x[i]
x[i+1], x[i] = x[i], x[i+1]
swapped = true
end
end
end
return x
end
bubblesort (generic function with 1 method)
bubblesort(randn(10))
10-element Array{Float64,1}: -1.79628 -1.73885 -0.460956 -0.450571 -0.151273 0.342973 0.474332 0.617031 0.710638 0.768515
x = randn(10000)
Profile.clear()
@profile bubblesort(x);
Profile.print()
196 ./task.jl:335; (::IJulia.##11#14)() 1 ...Julia/src/eventloop.jl:5; eventloop(::ZMQ.Socket) 1 ...v0.6/IJulia/src/msg.jl:87; recv_ipython(::ZMQ.Socket) 1 ....6/JSON/src/Parser.jl:375; #parse#1(::Type{Dict{String,Any}}... 1 ....6/JSON/src/Parser.jl:158; parse_value(::JSON.Parser.Memory... 1 ....6/JSON/src/Parser.jl:201; parse_object(::JSON.Parser.Memor... 195 ...Julia/src/eventloop.jl:8; eventloop(::ZMQ.Socket) 195 ...rc/execute_request.jl:160; execute_request(::ZMQ.Socket, ::... 195 ./loading.jl:515; include_string(::String, ::String) 195 ./<missing>:?; anonymous 195 ./profile.jl:23; macro expansion 53 ./In[157]:6; bubblesort(::Array{Float64,1}) 109 ./In[157]:7; bubblesort(::Array{Float64,1}) 31 ./In[157]:8; bubblesort(::Array{Float64,1}) 2 ./In[157]:9; bubblesort(::Array{Float64,1})
isodd(41) # 奇数
true
iseven(42) # 偶数
true
using Primes # https://github.com/JuliaMath/Primes.jl
isprime(42)
false
isprime(43)
true
using Primes # https://github.com/JuliaMath/Primes.jl
primes(50)
15-element Array{Int64,1}: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
div(42, 5)
8
42 / 5 # 整数 / 整数 = 浮動小数点数 になるので注意
8.4
42 % 5
2
rem(42, 5) # 上と同じ
2
abs(-42)
42
abs(42)
42
xor(42, 35)
9
42 ⊻ 35 # 上と同じ(\xor)
9
x = [1.0, 2.0, 3.0]
y = [-1.0, 3.0, 0.0]
3-element Array{Float64,1}: -1.0 3.0 0.0
x + y
3-element Array{Float64,1}: 0.0 5.0 3.0
x - y
3-element Array{Float64,1}: 2.0 -1.0 3.0
3.2x
3-element Array{Float64,1}: 3.2 6.4 9.6
x'
1×3 RowVector{Float64,Array{Float64,1}}: 1.0 2.0 3.0
x'' # 2回でもとに戻る
3-element Array{Float64,1}: 1.0 2.0 3.0
dot(x, x)
14.0
x ⋅ x # 上と同じ (\cdot)
14.0
x'x
14.0
x * x'
3×3 Array{Float64,2}: 1.0 2.0 3.0 2.0 4.0 6.0 3.0 6.0 9.0
diagm([1.0, 2.0, 3.0]) # 通常の行列の型
3×3 Array{Float64,2}: 1.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 3.0
Diagonal([1.0, 2.0, 3.0]) # 対角行列の型
3×3 Diagonal{Float64}: 1.0 ⋅ ⋅ ⋅ 2.0 ⋅ ⋅ ⋅ 3.0
A = randn(3, 3)
B = randn(3, 3)
3×3 Array{Float64,2}: 0.726385 1.6588 1.13122 1.01566 1.77963 0.710212 -0.0650975 -1.22412 1.03047
A * B # 通常の行列積
3×3 Array{Float64,2}: -1.28874 -3.78644 -1.10194 -1.70857 -4.33366 -0.816591 1.54023 2.93319 1.31487
At_mul_B(A, B) # Aを転置して掛ける
3×3 Array{Float64,2}: -2.19284 -5.01086 -2.08284 -1.06601 -3.18224 0.516614 1.47724 2.94792 1.4728
A'B # 上と同じ
3×3 Array{Float64,2}: -2.19284 -5.01086 -2.08284 -1.06601 -3.18224 0.516614 1.47724 2.94792 1.4728
A_mul_Bt(A, B) # Bを転置して掛ける
3×3 Array{Float64,2}: -0.35104 -1.17308 0.938959 -1.26934 -2.02604 2.15484 2.2404 2.53849 -1.5252
A * B' # 上と同じ
3×3 Array{Float64,2}: -0.35104 -1.17308 0.938959 -1.26934 -2.02604 2.15484 2.2404 2.53849 -1.5252
At_mul_Bt(A, B) # AもBも転置して掛ける
3×3 Array{Float64,2}: -2.22868 -3.02436 1.7201 -0.275315 -0.892186 2.39829 1.98846 2.34479 -1.18667
A'B' # 上と同じ
3×3 Array{Float64,2}: -2.22868 -3.02436 1.7201 -0.275315 -0.892186 2.39829 1.98846 2.34479 -1.18667
X = [5.0 2.0; -2.0 3.0]
2×2 Array{Float64,2}: 5.0 2.0 -2.0 3.0
eigvals(X)
2-element Array{Complex{Float64},1}: 4.0+1.73205im 4.0-1.73205im
eigvecs(X) # 複素数の固有ベクトル
2×2 Array{Complex{Float64},2}: 0.707107+0.0im 0.707107-0.0im -0.353553+0.612372im -0.353553-0.612372im
eigvals(X'X) # 固有値はすべて正なので正定値行列
2-element Array{Float64,1}: 12.0557 29.9443
eigvecs(X'X) # 正定値行列に対しては実数の固有ベクトル
2×2 Array{Float64,2}: 0.229753 -0.973249 -0.973249 -0.229753
A = [3.0 2.0 -1.0
2.0 -2.0 4.0
-1.0 0.5 -1.0]
b = [1.0, -2.0, 0.0]
3-element Array{Float64,1}: 1.0 -2.0 0.0
x = A \ b # A x = b の解
3-element Array{Float64,1}: 1.0 -2.0 -2.0
A * x ≈ b # 解の確認
true
rand()
0.3867181118018075
rand(30)
30-element Array{Float64,1}: 0.0233823 0.584213 0.996262 0.0486294 0.823912 0.00980484 0.506794 0.922409 0.846705 0.685258 0.0148934 0.101358 0.578418 ⋮ 0.672831 0.167329 0.826931 0.181764 0.401678 0.1965 0.202258 0.0961149 0.245319 0.919989 0.549066 0.184145
randn()
0.04586384215519224
randn(30)
30-element Array{Float64,1}: -0.437116 0.385278 -0.473007 -0.371043 -0.0256377 1.2682 0.552556 -0.0252973 -1.13349 2.46311 -0.902314 1.19349 0.271862 ⋮ -1.3191 0.194445 2.25805 1.87969 -0.176167 -0.0395945 1.24096 -1.03593 -0.259864 1.2209 2.11896 -0.695827
import Distributions ## https://github.com/JuliaStats/Distributions.jl
g = Distributions.Gamma(1.0, 2.0) # ガンマ分布
rand(g, 10)
10-element Array{Float64,1}: 0.851551 1.8048 0.0905379 0.0643867 0.464794 0.792174 2.73824 0.332647 0.565023 1.14877
p = Distributions.Poisson(10) # ポアソン分布
rand(p, 10)
10-element Array{Int64,1}: 10 12 13 8 12 7 7 12 4 11
rand(1:20) # 1-20の値から1個サンプリング
8
rand(1:20, 10) # 1~20の値から10個サンプリング
10-element Array{Int64,1}: 10 8 17 7 17 3 10 18 7 10
using StatsBase # https://github.com/JuliaStats/StatsBase.jl
sample(1:20, 10, replace=false) # 非復元抽出
10-element Array{Int64,1}: 7 18 17 8 20 12 14 5 4 19
mean(randn(100))
0.008539475320023372
var(randn(100))
0.865934027580458
median(exp.(randn(100)))
1.0103736890230341
x = exp.(randn(100));
quantile(x, 0.1)
0.39879867876339664
quantile(x, 0.25)
0.6779346947809612
for q in linspace(0, 1, 11)
println(q, ": ", quantile(x, q))
end
0.0: 0.10576604052523694 0.1: 0.39879867876339664 0.2: 0.5585514635406499 0.3: 0.7252001881297099 0.4: 0.9280416777324269 0.5: 1.1110217625293453 0.6: 1.4068712917385797 0.7: 1.7752452712496667 0.8: 2.9288228171021804 0.9: 4.571210350690497 1.0: 15.1433030232737
A = randn(5, 3)
5×3 Array{Float64,2}: -0.80238 0.644167 -0.0853525 0.823909 -0.350321 -0.969769 0.463137 2.23558 -0.64375 1.85394 0.886008 1.16761 -0.821372 0.468997 -1.69867
maximum(A) # 全要素の最大値 (最小値はminimum)
2.235578644026364
maximum(A, 2) # 行最大
5×1 Array{Float64,2}: 0.644167 0.823909 2.23558 1.85394 0.468997
maximum(A, 1) # 列最大
1×3 Array{Float64,2}: 1.85394 2.23558 1.16761
A = randn(5, 3) + 10
5×3 Array{Float64,2}: 10.9184 10.6914 8.21326 10.2181 10.8977 11.8139 9.11668 9.83351 10.3405 11.5015 8.74474 9.91524 11.31 10.1985 8.82895
A .- mean(A, 2) # 行平均を引く
5×3 Array{Float64,2}: 0.977356 0.75038 -1.72774 -0.758501 -0.0788276 0.837329 -0.646876 0.0699516 0.576924 1.44766 -1.30908 -0.138582 1.19753 0.0860069 -1.28354
A .- mean(A, 1) # 列平均を引く
5×3 Array{Float64,2}: 0.305433 0.618205 -1.6091 -0.394858 0.824564 1.99153 -1.49624 -0.23966 0.51812 0.888563 -1.32843 0.092875 0.697097 0.125321 -0.993418
X = [3.0 5.8 1.1; 1.0 4.2 0.1]
2×3 Array{Float64,2}: 3.0 5.8 1.1 1.0 4.2 0.1
cov(X, 1) # 各行がサンプル
3×3 Array{Float64,2}: 2.0 1.6 1.0 1.6 1.28 0.8 1.0 0.8 0.5
cov(X, 2) # 各列がサンプル
2×2 Array{Float64,2}: 5.59 4.99 4.99 4.64333
cor(X, 2) # ピアソンの相関係数の行列
2×2 Array{Float64,2}: 1.0 0.979444 0.979444 1.0
X = randn(20, 4)
b = [-1.0, 1.0, 2.0, 3.0]
4-element Array{Float64,1}: -1.0 1.0 2.0 3.0
y = X * b + randn(20) * 0.1
20-element Array{Float64,1}: 1.8996 6.01268 1.41041 -0.542336 -2.5572 -0.450025 3.60568 -3.86358 -0.819904 1.11038 -6.1131 1.69123 -2.1921 5.05921 -1.56521 2.39779 3.91339 0.451056 -1.10424 4.80995
正規方程式 $(X'X)\beta = X'y$ の解
(X'X)\X'*y
4-element Array{Float64,1}: -1.02689 0.976217 2.01937 2.98385
また、$X=QR$と分解すると、$X$が最大列階数のとき正規方程式は
\begin{align} (X'X)\beta &= X'y \\ (QR)'(QR)\beta &= (QR)'y \\ R'(Q'Q)R\beta &= R'Q'y \\ R\beta &= Q'y \end{align}なので次のようにも計算できる
Q, R = qr(X)
R\(Q'y)
4-element Array{Float64,1}: -1.02689 0.976217 2.01937 2.98385
using Roots # https://github.com/JuliaMath/Roots.jl
fzero(log, 0, 10)
1.0
fzero(x -> sin(x - 3), 2, 4)
3.0
using Interpolations
f(x) = sin(x) * exp(-x)
f (generic function with 1 method)
xs = linspace(-3, 3, 8)
itp = interpolate([f(x) for x in xs], BSpline(Cubic(Line())), OnCell())
scl = scale(itp, xs)
g = x->scl[x]
(::#17) (generic function with 1 method)
f(1)
0.3095598756531122
g(1)
0.31573248343343835
using Gadfly
plot(layer([f, g], -3, 3), layer(x=xs, y=f.(xs), Geom.point))
import ForwardDiff # https://github.com/JuliaDiff/ForwardDiff.jl
f(x) = sin(x) * exp(-x)
f′(x) = ForwardDiff.derivative(f, x)
f′ (generic function with 1 method)
f(1.0)
0.3095598756531122
f′(1.0)
-0.11079376530669924
using Gadfly
plot([f, f′], -3, 3)
import ReverseDiff # https://github.com/JuliaDiff/ReverseDiff.jl
f(x) = 2dot(x, x) + sum(x)
f′(x) = ReverseDiff.gradient(f, x)
f′ (generic function with 1 method)
f′(zeros(3))
3-element Array{Float64,1}: 1.0 1.0 1.0
f′(ones(3))
3-element Array{Float64,1}: 5.0 5.0 5.0
using Optim # https://github.com/JuliaNLSolvers/Optim.jl
# 2変数のRosenbrock関数 https://en.wikipedia.org/wiki/Rosenbrock_function
f(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
f (generic function with 1 method)
optimize(f, zeros(2))
Results of Optimization Algorithm * Algorithm: Nelder-Mead * Starting Point: [0.0,0.0] * Minimizer: [0.9999710322210338,0.9999438685860869] * Minimum: 1.164323e-09 * Iterations: 74 * Convergence: true * √(Σ(yᵢ-ȳ)²)/n < 1.0e-08: true * Reached Maximum Number of Iterations: false * Objective Function Calls: 108
optimize(f, zeros(2), BFGS())
Results of Optimization Algorithm * Algorithm: BFGS * Starting Point: [0.0,0.0] * Minimizer: [0.9999999926033423,0.9999999852005353] * Minimum: 5.471433e-17 * Iterations: 16 * Convergence: true * |x - x'| < 1.0e-32: false * |f(x) - f(x')| / |f(x)| < 1.0e-32: false * |g(x)| < 1.0e-08: true * f(x) > f(x'): false * Reached Maximum Number of Iterations: false * Objective Function Calls: 69 * Gradient Calls: 69