import numpy as np
x = np.random.randint(1,60,[30,1])
y = np.zeros(20)
k = 3
#1選取資料空間中的K個對象作為初始中心,每個對象代表一個聚類中心;
def initcen(x,k):
return x[:k]
#2對于樣本中的資料對象,根據它們與這些聚類中心的歐氏距離,按距離最近的準則将它們分到距離它們最近的聚類中心(最相似)所對應的類;
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
#3更新聚類中心:将每個類别中所有對象所對應的均值作為該類别的聚類中心,計算目标函數的值;
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[j] != n:
l[j] = n
flag = True
print(l,flag)
return (np.array(l),flag)
#4判斷聚類中心和目标函數的值是否發生改變,若不變,則輸出結果,若改變,則傳回2)
kc = initcen(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)

# 用鸢尾花花瓣作分析
x = np.array(iris_length)
y = np.zeros(x.shape[0])
kc = initcen(x,3)
flag = True
while flag:
y = xclassify(x,y,kc)
kc,flag = kcmean(x,y,kc,3)
print(kc,flag)
# 分析鸢尾花花瓣長度的資料,并用散點圖表示出來
import matplotlib.pyplot as plt
plt.scatter(iris_length, iris_length, marker='p', c=y, alpha=0.5, linewidths=4, cmap='Paired')
plt.show()
#4鸢尾花完整資料做聚類并用散點圖顯示.
from sklearn.datasets import load_iris
iris=load_iris()
x=iris.data
from sklearn.cluster import KMeans
eat=KMeans(n_clusters=3)
eat.fit(x)
eat.cluster_centers_
y=eat.predict(x)
y
import matplotlib.pyplot as plt
plt.scatter(x[:,0],x[:,1])
plt.show()
轉載于:https://www.cnblogs.com/yuxiang1212/p/9922079.html