Cucco’s Compute Hack

コンピュータ関係の記事を書いていきます。

sklearnでクラスタリング(その3)

学習済みのクラスタ識別機は、pickleで保存する模様。

プログラム
import numpy as np
from sklearn.cluster import KMeans

import pickle
import os

X = np.array([[0, 0],[0, 1],[1, 0],[1, 1], [0, 10], [0, 9], [0, 8], [10, 10], [10, 9],[9,10]])
Y = np.array([[0, 0], [0, 1], [1, 0], [1, 1], [0, 10], [0, 9], [0, 8], [10, 10], [10, 9], [9, 10]])

# クラスタ識別機の学習
kmeans = KMeans(n_clusters=3, random_state=0).fit(X)

# 学習結果を表示
print("オリジナルのクラスタ識別機を利用した結果")
print(kmeans.labels_)
print(kmeans.cluster_centers_)
print(kmeans.predict(Y))
print(kmeans.transform(Y))

# 学習済みクラスタ識別機を保存
traind_kmeans_file = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'traind_kmeans_model.pickle'
with open(traind_kmeans_file, mode='wb') as fp:
    pickle.dump(kmeans, fp)

# 学習済みクラスタ識別機をファイルから呼び出し
with open(traind_kmeans_file , mode='rb') as fp:
    kmeans_new = pickle.load(fp)

# 学習結果を表示
print("読み出したクラスタ識別機を利用した結果")
print(kmeans_new.labels_)
print(kmeans_new.cluster_centers_)
print(kmeans_new.predict(Y))
print(kmeans_new.transform(Y))
結果
オリジナルのクラスタ識別機を利用した結果
[0 0 0 0 2 2 2 1 1 1]
[[0.5        0.5       ]
 [9.66666667 9.66666667]
 [0.         9.        ]]
[0 0 0 0 2 2 2 1 1 1]
[[ 0.70710678 13.6707311   9.        ]
 [ 0.70710678 12.98289473  8.        ]
 [ 0.70710678 12.98289473  9.05538514]
 [ 0.70710678 12.25651754  8.06225775]
 [ 9.5131488   9.67241209  1.        ]
 [ 8.51469318  9.6896279   0.        ]
 [ 7.51664819  9.80929265  1.        ]
 [13.43502884  0.47140452 10.04987562]
 [12.74754878  0.74535599 10.        ]
 [12.74754878  0.74535599  9.05538514]]
読み出したクラスタ識別機を利用した結果
[0 0 0 0 2 2 2 1 1 1]
[[0.5        0.5       ]
 [9.66666667 9.66666667]
 [0.         9.        ]]
[0 0 0 0 2 2 2 1 1 1]
[[ 0.70710678 13.6707311   9.        ]
 [ 0.70710678 12.98289473  8.        ]
 [ 0.70710678 12.98289473  9.05538514]
 [ 0.70710678 12.25651754  8.06225775]
 [ 9.5131488   9.67241209  1.        ]
 [ 8.51469318  9.6896279   0.        ]
 [ 7.51664819  9.80929265  1.        ]
 [13.43502884  0.47140452 10.04987562]
 [12.74754878  0.74535599 10.        ]
 [12.74754878  0.74535599  9.05538514]]
set_params()は学習結果は含んでいない

get_params()の結果をset_params(**get_params()の結果)でセットしただけでは、以下といわれる。

sklearn.exceptions.NotFittedError: This KMeans instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.