LoginSignup
5
6

More than 5 years have passed since last update.

PyCallを使ってscikit-learnコードを動かしてみた。

Last updated at Posted at 2018-03-24

追記

この記事よりもPyCall.jlでPyTorch使ってDeep Learningするのほうが内容が豊富です。
追記終わり。


JuliaからPythonを呼ぶにはPyCallを使えばいいらしいので、Scikit-learnのサンプルコードを試しに移植してみました。いくつか修正は必要ですが、ほとんどそのまま動く印象です。

ここでは、移植に際して必要な変更点を最初に列挙します。そのあとにコード全文を載せました。

オリジナルのサンプルコードはアヤメデータの可視化です。

モジュール呼び出しの変更(Python -> Julia)

1. matplotlib(Python)はPyPlot(Julia)から呼び出す.

変更前(Python)

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

変更後(Julia)

using PyPlot

注)plt.は必要なくなります。

2. Pythonモジュールの読み込みにPyCallを使う

変更前(Python)

from sklearn import datasets
from sklearn.decomposition import PCA

変更後(Julia)

using PyCall
@pyimport sklearn.datasets as datasets
@pyimport sklearn.decomposition as decomposition

その他の変更箇所

Python -> Julia

  • インデックス
    • Python:0-base
    • Julia:1-base
  • 最初の2つの要素のスライス
    • Python:array[:2] <= 右端を含まない
    • Julia:array[1:2]<= 右端を含む

NumPy -> Julia

  • ndarrayはJulia nativeのArrayに変換される。
  • 1次元配列からの最大値の取得
    • Python:array.max()
    • Julia:maximum(array)

PyCall

  • @pyimportでインポート出来るのはモジュールのみ
    • Pythonのクラス、関数、変数の直接の読み込みは出来ない
    • from xxx import yyyの構文は使えない(たぶん)
  • Pythonオブジェクトoのメソッド/アトリビュートへのアクセスにはJuliaのsymbolを使う。
    • Python : o.attribute
    • Julia : o[:attribute]

コード全文

# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause

using PyCall
using PyPlot
@pyimport sklearn.datasets as datasets
@pyimport sklearn.decomposition as decomposition

# import some data to play with
iris = datasets.load_iris()
X = iris["data"][:, 1:2]  # we only take the first two features.
y = iris["target"]

x_min, x_max = minimum(X[:, 1]) - .5, maximum(X[:, 1]) + .5
y_min, y_max = minimum(X[:, 2]) - .5, maximum(X[:, 2]) + .5

figure(2, figsize=(8, 6))
clf()

# Plot the training points
scatter(X[:, 1], X[:, 2], c=y, cmap=PyPlot.cm[:Set1],
            edgecolor="k")
xlabel("Sepal length")
ylabel("Sepal width")

xlim(x_min, x_max)
ylim(y_min, y_max)
xticks(())
yticks(())

# To getter a better understanding of interaction of the dimensions
# plot the first three PCA dimensions
fig = figure(1, figsize=(8, 6))
ax = Axes3D(fig, elev=-150, azim=110)
X_reduced = decomposition.PCA(n_components=3)[:fit_transform](iris["data"])
ax[:scatter](X_reduced[:, 1], X_reduced[:, 2], X_reduced[:, 3], c=y,
           cmap=PyPlot.cm[:Set1], edgecolor="k", s=40)

ax[:set_title]("First three PCA directions")
ax[:set_xlabel]("1st eigenvector")
ax[:w_xaxis][:set_ticklabels]([])

ax[:set_ylabel]("2nd eigenvector")
ax[:w_yaxis][:set_ticklabels]([])
ax[:set_zlabel]("3rd eigenvector")
ax[:w_zaxis][:set_ticklabels]([])

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6