「大人の教養・知識・気付き」を伸ばすブログ

一流の大人(ビジネスマン、政治家、リーダー…)として知っておきたい、教養・社会動向を意外なところから取り上げ学ぶことで“気付く力”を伸ばすブログです。データ分析・語学に力点を置いています。 →現在、コンサルタントの雛になるべく、少しずつ勉強中です(※2024年1月21日改訂)。

MENU

Juliaを使ってみる(02/22):基礎数学を扱う

1. 乱数を生成し、統計量を計算してみる

# 統計学のパッケージを使う
using Statistics

# 一様乱数U(0,1)を50個生成する
X = rand(50)

# 一様乱数U(0,1)50個を2つ生成する
Y = rand(2, 50)

# Xの合計,平均を出力させる
println(sum(X))
println(mean(X))

# Yの平均を出力させる
println(mean(Y)) #1つ目は50個×2列=100個の平均
println(mean(Y, dims = 1))  #1列目の50個の平均
println(mean(Y, dims = 2))  #2列目の50個の平均

# 共分散を出力
cov(X) # Xの分散

cov(Y, dims = 1) # Yの共分散

2. 正規乱数を生成

# 確率分布のパッケージ
using Distributions

mu = 1.5      #平均
sigma = 2.0 #標準偏差

z = rand(Normal(mu,sigma), 10000)
println(z)

println(mean(z)) # 1.4723455054593544
println(std(z))     # 2.0095894295395405

3. 関数の数値微分

using PyPlot

# f(x)を2次関数として定義
f(x) = - (x + 1) * (x - 1)

# hを微小値として定義
h = 1.0e-10

# 導関数を簡単な数値微分で定義
f′(a) = (f(a + h) - f(a))/h

# 関数の可視化範囲
xs = range(-100,100,length = 10000)
fig, axes = subplots(2,1, figsize = (4,6))

# 関数のプロット
axes[1].plot(xs,f.(xs),"b")
axes[1].grid()
axes[1].set_xlabel("x"),axes[1].set_ylabel("y")
axes[1].set_title("function f(x)")

axes[2].plot(xs, f′.(xs),"r")
axes[2].grid()
axes[2].set_xlabel("x"),axes[2].set_ylabel("y")
axes[2].set_title("derivative f'(x)")

tight_layout()

4. 勾配ベクトルの図示

using PyPlot

# グラフを可視化する際の解像度
L = 10

# f2(x)を可視化する範囲
xs1 = range(-10, 10 , length = L)
xs2 = range(-10, 10 , length = L)

# 2値関数
f2(x) = -(x.+1)'*(x.-1)

# 勾配
gf2(x) = -2x

# グラフ
fig, axes = subplots(1,2,figsize = (8,4))

# 関数の等高線図の可視化
cs = axes[1].contour(xs1, xs2, [f2([x1,x2]) for x1 in xs1, x2 in xs2]')
axes[1].clabel(cs, inline=true)
axes[1].set_xlabel("x1"), axes[1].set_ylabel("x2")
axes[1].set_title("f2(x)")

# 勾配ベクトルの計算と可視化
vec1 = [gf2([x1,x2])[1] for x1 in xs1, x2 in xs2]
vec2 = [gf2([x1,x2])[2] for x1 in xs1, x2 in xs2]
axes[2].quiver(repeat(xs1,1,L), repeat(xs2',L,1), vec1, vec2)
axes[2].set_xlabel("x1"), axes[2].set_ylabel("x2")
axes[2].set_title("gf2(x)")

tight_layout()

5. 自動微分のパッケージForwardDiffを使ってみる

using ForwardDiff

# 2次関数を定義
f(x) = -(x + 1) * (x - 1)

# 自動微分によって導関数f'(x)を定義する
f′(x) = ForwardDiff.derivative(f,x)

xs = range(-10,10, length = 1000)

fig,axes = subplots(2, 1, figsize = (4, 6))

# 関数のプロット
axes[1].plot(xs, f.(xs), "b")
axes[1].grid()
axes[1].set_xlabel("x"), axes[1].set_ylabel("y") 
axes[1].set_title("function f(x)")

# 導関数のプロット
axes[2].plot(xs, f′.(xs), "r")
axes[2].grid()
axes[2].set_xlabel("x"), axes[2].set_ylabel("y")
axes[2].set_title("derivative f'(x)")

tight_layout()

6. 勾配法による最適化

# 勾配法による一変数関数の最適化
x_opt = 0.50
f(x) = -2(x-x_opt)^2 #最適化対象

# 図示
fig,ax = subplots()
xs = range(-3,3,length=1000)
ax.plot(xs,f.(xs), label = "function")
ax.plot(x_opt, f(x_opt), "rx", label = "optimal")
ax.set_xlabel("x"), ax.set_ylabel("y")
ax.grid()
ax.legend()
プライバシーポリシー お問い合わせ