手写
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
def distance(vex1,vex2):
return np.sqrt(np.sum(np.power(vex1-vex2,2)))
def kMeans_way(S,k,distMeas=distance):
m=np.shape(S)[0]
sampleTag = np.zeros(m)
n=np.shape(S)[1]
print (m,n)
clusterCenter = np.mat(np.zeros((k,n)))
for j in range(n):
minJ=min(S[:,j])
maxJ=max(S[:,j])
rangeJ=float(maxJ-minJ)
clusterCenter[:,j]=np.mat(minJ + rangeJ*np.random.rand(k,1))
#print (clusterCenter)
sampleTagChanged = True
SSE = 0.0
while sampleTagChanged:
sampleTagChanged = False
SSE = 0.0
for i in range(m):
minD = np.inf
minIndex = -1
for j in range(k):
d=distMeas(clusterCenter[j,:],S[i,:])
if d<minD:
minD=d
minIndex=j
if sampleTag[i]!=minIndex:
sampleTagChanged = True
sampleTag[i] = minIndex
SSE+=minD**2
print (SSE)
for i in range(k):
ClustI=S[np.nonzero(sampleTag[:]==i)[0]]
clusterCenter[i,:]= np.mean(ClustI,axis=0)
return clusterCenter,sampleTag,SSE
def draw_pic(samples,sampleTag,clusterCenter):
k=len(clusterCenter)
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
markers=['sg','py','ob','pr']
for i in range(k):
data_pos = samples[sampleTag== i]
plt.plot(data_pos[:,0].tolist(),data_pos[:,1].tolist(),markers[i])
plt.plot(clusterCenter[:,0].tolist(),clusterCenter[:,1].tolist(),"r*",markersize=20)
plt.title('鸢尾花')
plt.show()
def main():
k=3
print ("----------ing-------------")
iris_data = load_iris()
data= iris_data.data[:]
clusterCenter,sampleTag,SSE = kMeans_way(data,k)
if np.isnan(clusterCenter).any():
print ("Error!reson:质心重叠!")
return
print (type(sampleTag))
draw_pic(data,sampleTag,clusterCenter)
print ("----------end-------------")
main()
调用sklearn
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
def draw_pic(data,centers,result):
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
markers=['sg','py','ob','pk']
for i,d in enumerate(data):
plt.plot(d[0],d[1],markers[result[i]])
for i,center in enumerate(centers):
plt.plot(center[0],center[1],"r*",markersize=20)
plt.title('鸢尾花')
plt.show()
def main():
k=4
print ("----------ing-------------")
iris_data = load_iris()
data= iris_data.data[:]
model = KMeans(n_clusters=k)
model.fit(data)
clusterCenter = model.cluster_centers_
if np.isnan(clusterCenter).any():
print ("Error!reson:质心重叠!")
return
result = model.predict(data)
print("result:",result)
print("model_labels:",model.labels_)
draw_pic(data,clusterCenter,result)
print ("----------end-------------")
main()
思路,随机生成聚类中心。
然后,比较样本点到距离聚类中心的距离大小,距离哪个样本点近就属于哪个聚类。
随之,画出样本点及聚类中心。