1 | import os |
2 | import numpy as np |
3 | import matplotlib.pyplot as plt |
4 | from sklearn import datasets |
5 | from sklearn import metrics |
6 | from sklearn import cluster |
7 | os.chdir(r 'D:\projects\wordpress\ex49' ) |
8 | os.getcwd() |
9 | iris = datasets.load_iris() |
10 | X, y = iris.data, iris.target |
11 | np.random.seed( 123 ) |
12 | n_clusters = 3 |
13 | c = cluster.KMeans(n_clusters = n_clusters) |
14 | c.fit(X) |
15 | y_pred = c.predict(X) |
16 | print (y_pred[:: 8 ]) |
17 | print (y[:: 8 ]) |
18 | idx_0, idx_1, idx_2 = (np.where(y_pred = = n) for n in range ( 3 )) |
19 | y_pred[idx_0], y_pred[idx_1], y_pred[idx_2] = 2 , 0 , 1 |
20 | print (y_pred[:: 8 ]) |
21 | print (metrics.confusion_matrix(y, y_pred)) |
22 | N = X.shape[ 1 ] |
23 | fig, axes = plt.subplots(N, N, figsize = ( 12 , 12 ), sharex = True , sharey = True ) |
24 | colors = [ "coral" , "blue" , "green" ] |
25 | markers = [ "^" , "v" , "o" ] |
26 | for m in range (N): |
27 | for n in range (N): |
28 | for p in range (n_clusters): |
29 | mask = y_pred = = p |
30 | axes[m, n].scatter(X[:, m][mask], X[:, n][mask], |
31 | marker = markers[p], s = 30 , |
32 | color = colors[p], alpha = 0.25 ) |
33 |
34 | [crayon - 67f18d234b79c204146585 / ] |
35 |
36 | fig.tight_layout() |
37 | plt.savefig( "example49.png" , dpi = 100 ) |
38 | plt.show() |
39 | plt.close() |
Recent Comments