fork download
  1. # your code goes here
  2. import numpy as np
  3. from sklearn.datasets import load_iris
  4.  
  5. # iris.csv の代わりに scikit-learn のデータを使う
  6. iris = load_iris()
  7. X = iris.data[:100, :2] # 先頭100件、1〜2列目(がく片の長さ・幅)
  8.  
  9. # 初期のクラスタ平均
  10. P = [[4, 1], [6, 5]]
  11.  
  12. def assign(X, P):
  13. """各データを最も近いクラスタ平均に割り当てる"""
  14. d1 = (X[:, 0] - P[0][0])**2 + (X[:, 1] - P[0][1])**2
  15. d2 = (X[:, 0] - P[1][0])**2 + (X[:, 1] - P[1][1])**2
  16. return np.where(d1 < d2, 0, 1)
  17.  
  18. # 初期割り当て
  19. c = assign(X, P)
  20.  
  21. # 収束するまで反復
  22. t = 0
  23. while True:
  24. P_old = [list(P[0]), list(P[1])]
  25. P[0] = [np.average(X[c == 0, 0]), np.average(X[c == 0, 1])]
  26. P[1] = [np.average(X[c == 1, 0]), np.average(X[c == 1, 1])]
  27. t += 1
  28.  
  29. # クラスタ平均が変わらなければ収束
  30. if np.allclose(P_old, P):
  31. break
  32.  
  33. c = assign(X, P)
  34.  
  35. print("クラスタ平均が変化した回数:", t - 1)
  36. print("収束を確認した反復回数:", t)
  37. print("最終クラスタ平均:", P)
Success #stdin #stdout 2.87s 88208KB
stdin
Standard input is empty
stdout
クラスタ平均が変化した回数: 8
収束を確認した反復回数: 9
最終クラスタ平均: [[5.016363636363637, 3.350909090909091], [6.026666666666666, 2.791111111111111]]