1import os
2import numpy as np
3import matplotlib.pyplot as plt
4from sklearn import datasets
5from sklearn import metrics
6from sklearn import cluster
7os.chdir(r'D:\projects\wordpress\ex49')
8os.getcwd()
9iris = datasets.load_iris()
10X, y = iris.data, iris.target
11np.random.seed(123)
12n_clusters = 3
13c = cluster.KMeans(n_clusters=n_clusters)
14c.fit(X)
15y_pred = c.predict(X)
16print(y_pred[::8])
17print(y[::8])
18idx_0, idx_1, idx_2 = (np.where(y_pred == n) for n in range(3))
19y_pred[idx_0], y_pred[idx_1], y_pred[idx_2] = 2, 0, 1
20print(y_pred[::8])
21print(metrics.confusion_matrix(y, y_pred))
22N = X.shape[1]
23fig, axes = plt.subplots(N, N, figsize=(12, 12), sharex=True, sharey=True)
24colors = ["coral", "blue", "green"]
25markers = ["^", "v", "o"]
26for 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 
36fig.tight_layout()
37plt.savefig("example49.png", dpi=100)
38plt.show()
39plt.close()

 

example49

 

Discover more from Tips and Hints for Aerospace Engineers

Subscribe now to keep reading and get access to the full archive.

Continue reading