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()

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值