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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
| import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris import numpy as np
plt.rcParams['font.sans-serif']=['SimHei'] iris = load_iris() X = iris.data lable = iris.target
arr = np.array(X) hua_e = arr[:,0]*arr[:,1] hua_ban = arr[:,2]*arr[:,3]
def shuju(k): b =set() while(len(b)<k): b.add(np.random.randint(0,150)) return(b)
def getDistance(point_x,point_y,cent_x,cent_y,k): x = point_x y = point_y x0 = cent_x y0 = cent_y i = 0 j = 0 ds = [[]for i in range(len(x))]
while i < len(x): while j < k: M = np.sqrt((x[i]-x0[j]) * (x[i]-x0[j]) + (y[i]-y0[j]) * (y[i]-y0[j])) M = round(M,1) j = j + 1 ds[i].append(M) j = 0 i = i + 1 return(ds)
def EDistance(point_x,point_y,cent_x,cent_y,k): x = point_x y = point_y x0 = cent_x y0 = cent_y i = 0 j = 0 sum = 0 while i < k: while j < len(x): M = (x[j]-x0[i]) * (x[j]-x0[i]) + (y[j]-y0[i]) * (y[j]-y0[i]) M = round(M,1) sum += M j = j + 1 j = 0 i = i + 1 return(sum)
def cent(lable): temp = lable mean_x = [] mean_y = [] i = 0 j = 0 while i < 3: cent_x = 0 cent_y = 0 count = 0 while j < len(x): if i == temp[j]: count = count + 1 cent_x = cent_x + x[j] cent_y = cent_y + y[j] j = j + 1 cent_x = cent_x / count cent_y = cent_y / count mean_x.append(cent_x) mean_y.append(cent_y) j = 0 i = i + 1 return[mean_x,mean_y]
def julei(ds,x): x = x x = len(x) i = 0 temp = [] while i < x: temp.append(ds[i].index(min(ds[i]))) i = i + 1 return(temp)
k = 3
b = shuju(k) ceshi_hua_e = [hua_e[i] for i in range(len(hua_e)) if (i in b)] ceshi_hua_ban = [hua_ban[i] for i in range(len(hua_ban)) if (i in b)] ceshi_lable = [lable[i] for i in range(len(lable)) if (i in b)] x = hua_e y = hua_ban x0 = ceshi_hua_e y0 = ceshi_hua_ban
n = 0 ds = getDistance(x,y,x0,y0,k) temp = julei(ds,x) temp1 = EDistance(x,y,x0,y0,k) n = n + 1 center = cent(temp) x0 = center[0] y0 = center[1] ds = getDistance(x,y,x0,y0,k) temp = julei(ds,x) temp2 = EDistance(x,y,x0,y0,k) n = n + 1
while np.abs(temp2 - temp1) != 0: temp1 = temp2 center = cent(temp) x0 = center[0] y0 = center[1] ds = getDistance(x,y,x0,y0,k) temp = julei(ds,x) temp2 = EDistance(x,y,x0,y0,k) n = n + 1 print(n,temp2)
print("迭代次数: ", n) print('质心位置:',x0,y0)
plt.scatter(x0,y0,color='r',s=50,marker='s') plt.scatter(x,y,c=temp,s=25,marker='o') plt.xlabel('花萼面积') plt.ylabel('花瓣面积') plt.title("聚3类") plt.show()
|