1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
from sklearn.datasets import load_iris import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans x = np.random.randint(1,50,[20,1])
y = np.zeros(20) k = 3
def initcenter(x,k): return x[:k]
def nearest(kc,i): d = abs(kc -i) w = np.where(d == np.min(d)) return w[0][0]
def xclassify(x, y, kc): for i in range(x.shape[0]): y[i] = nearest(kc, x[i]) return y kc = initcenter(x,k) y = xclassify(x,y,kc) print(kc,y)
def kcmean(x,y,kc,k): l = list(kc) flag = False for c in range(k): m = np.where(y ==0) n = np.mean(x[m]) if l[c] != n: l[c] = n flag = True print(l,flag) return (np.array(l),flag)
kc = initcenter(x,k) flag = True print(x,y,kc,flag) while flag: y = xclassify(x,y,kc) kc,flag = kcmean(x,y,kc,k) print(y,kc)
|