K-means 使用SSE和轮廓系数

import pandas as pd 
import numpy as np
#创造数据
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

x,y=make_blobs(n_samples=500,n_features=2,centers=4,random_state=1)

fig,ax1=plt.subplots(1)
ax1.scatter(x[:,0],x[:,1],
            marker='o',
            s=8)
plt.show()

color=['red','pink','orange','gray']
fig,ax1=plt.subplots(1)
for i in range(4):
    ax1.scatter(x[y==i,0],x[y==i,1],
                marker='o',
                s=8,
                c=color[i])
plt.show()


#对数据进行了解

from sklearn.cluster import KMeans
#使用SSE进行模型评估,
import matplotlib.pyplot as plt
sse=[]
for i in range(1,10):
    cluster=KMeans(n_clusters=i,random_state=0).fit(x)
    inertia=cluster.inertia_
    sse.append(inertia)
plt.figure(figsize=(8,6))
plt.plot(range(1,10),sse,color='red',linewidth=2.0,linestyle='--',marker='o',label='sse')
plt.grid(True)
plt.show()


#使用轮廓系数sc
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.pyplot as plt
sc=[]
for i in range(2,10):#为什么要从2开始,1的话会出错
    cluster_=KMeans(n_clusters=i,random_state=0).fit(x)
    y_pre=cluster_.labels_
    sc_=silhouette_score(x,y_pre)
    sc.append(sc_)
plt.figure(figsize=(8,6))
plt.plot(range(1,10),sse,color='red',linewidth=2.0,linestyle='--',marker='o',label='sse')
plt.show()

 

你可能感兴趣的:(机器算法)