2016年9月11日日曜日

Pythonのデータ分析系パッケージ NumPyとSciPy

Pythonのデータ分析系パッケージ
多次元配列、線形代数の計算などを行うNumPyをAnacondaのIPythonで扱う。
AnacondaからIPythonを開くとこんな感じ

In [1]: import numpy (NumPyをインポート) In [2]: numpy.array([1,2,3]) (1×3のベクトルを作成) Out[2]: array([1, 2, 3]) In [3]: numpy.array([[1,3],[2,4]]) (2×2の行列を作成) Out[3]: array([[1, 3], [2, 4]]) In [4]: a=numpy.array([[1,3],[2,4]]) (aという2×2の行列を作成) In [5]: a[0][1] (aの0行1列の要素を抽出) Out[5]: 3

-------------------------------------------------
NumPyのstd()関数で標準偏差を求める。

In [6]: score=numpy.array([80,70,75,82,90])

In [7]: numpy.std(score)
Out[7]: 6.7409198185410872

-------------------------------------------------
NumPyのcorrcoef()関数で相関係数を求める。
In [8]: x=numpy.array([1,2,3,4,5])

In [9]: y=numpy.array([1,3,3,4,5])

In [10]: numpy.corrcoef(x,y)
Out[10]:
array([[ 1.        ,  0.95940322],
       [ 0.95940322,  1.        ]])



-------------------------------------------------
SciPyを使う。SciPyのeuclidean()関数を使ってユークリッド距離を求める。

In [11]: import scipy

In [12]: from scipy.spatial import distance

In [13]: x=[1,2,3]

In [14]: y=[1,2,4]

In [15]: distance.euclidean(x,y)
Out[15]: 1.0

-------------------------------------------------
SciPyで最近傍探索を行う。

In [16]: from scipy.spatial import KDTree

In [17]: x,y,z=(1,1,2),(5,3,7),(2,5,1)

In [18]: label=('x','y','z')

In [19]: tree=KDTree((x,y,z))

In [20]: tree.data
Out[20]:
array([[1, 1, 2],
       [5, 3, 7],
       [2, 5, 1]])

In [21]: new_data=(4,5,1)

In [22]: d,n=tree.query(new_data)

In [23]: print('分類結果は{0}です'.format(label[n]))
分類結果はzです

In [24]: print('距離は{0}です'.format(d))
距離は2.0です

0 件のコメント: