基操(kmeans建模,拟合,质心,label,inertia)
数据格式(左下)和最终结果(右上)
模型准备和拟合
clf = KMeans(n_clusters=3)
clf.fit(data)
查看质心cluster_centers_
clf.cluster_centers_
查看每个点所属于的簇的标签labels_
clf.labels_
查看误差平方和 inertia_
clf.inertia_
绘制点图
点图plt.scatter(横坐标对应数据列,纵坐标对应数据列,颜色c=clf.labels_,标记marker=‘x’)
plt.scatter(data['每分钟助攻数'],data['每分钟得分数'],c=clf.labels_,marker='x')
标记质心 cluster_centers_ 结合刚才已经求得的质心坐标,第1列(索引0)为横坐标,第2列(索引1)为纵坐标,
eg:只要索引为0的第一列,表示为 [:,0],:表示行不要
plt.scatter(clf.cluster_centers_[:,0],clf.cluster_centers_[:,1],color='red')
最后加上横纵坐标,标题 xlabel,ylabel,title
横纵坐标为中文jupyter识别不了,改为英文解决
plt.scatter(data['每分钟助攻数'],data['每分钟得分数'],c=clf.labels_,marker='x')
plt.scatter(clf.cluster_centers_[:,0],clf.cluster_centers_[:,1],c='red')
plt.xlabel('assists per min')
plt.xlabel('points per min')
plt.title('KMeans Basketball data')
!!!注意,color用c肯定不会错,用color有时会报错
全文代码
import pandas as pd
from sklearn.cluster import KMeans
from matplotlib import pyplot as plt
1、准备数据集
data = pd.read_csv(r'basketball.csv')
data.head()
data.shape
2、Kmeans聚类
# 1.准备模型
km = KMeans(n_clusters=3)
# 2.训练模型
km.fit(data)
3、查看属性
# 1.质心
km.cluster_centers_
# 2.属于哪个簇
km.labels_
# 3.误差平方和
km.inertia_
4、最优模型
result = []
for n_clusters in range(2,10):
for max_iter in range(300,601,50):
for tol in range(2,10):
tol=tol*1e-5
km = KMeans(n_clusters=n_clusters, max_iter=max_iter, tol=tol)
km.fit(data)
d = {'n_clusters':n_clusters, 'max_iter':max_iter, 'tol':tol, 'inertia': km.inertia_}
result.append(d)
result
result_df = pd.DataFrame(result)
result_df
找到误差平方和最小,对应的模型参数
r = result_df.iloc[result_df['inertia'].argmin(), :]
type(r)
r
n_clusters = r['n_clusters']
n_clusters
max_iter = int(r['max_iter'])
max_iter
tol = r['tol']
tol
选择合适的K值
data.head()
data.shape
for n_clusters in range(2,20):
print(n_clusters)
x = []
y = []
for n_clusters in range(2,20):
print(n_clusters)
km = KMeans(n_clusters=n_clusters, max_iter=max_iter, tol=tol)
km.fit(data)
# 保存n_clusters、误差平方和
x.append(n_clusters)
y.append(km.inertia_)
x
y
用n_clusters(k)作为横坐标,误差平方和作为中坐标---折线图(最优k)
plt.figure(figsize=(20, 8), dpi=100)
plt.plot(x, y)
plt.xlabel('K')
plt.ylabel('inertia')
plt.title('k-inertia relation')
# 将数字标注到折线图中
for a, b in zip(x, y):
plt.text(a, b, round(b, 2), ha='center', va='bottom')
ppt-K-Means代码示例
法1
min_inertia = 10000000
k = 0
for i in range(5,30):
km = KMeans(n_clusters=i)
km.fit(data)
inertia = km.inertia_
if min_inertia > inertia:
min_inertia = inertia
k = i
min_inertia
k
法2
d = {}
for i in range(5,30):
km = KMeans(n_clusters=i).fit(data)
d[i] = km.inertia_
d
d_new = pd.Series(d)
d_new
d_new = pd.Series(d)
d_new.idxmin()
min(zip(d.values(), d.keys()))[1]
min(d.items(), key=lambda x: x[1])[0]
d_new
d_new.argmin()
d_new.argmin()
法3
e_min = 1000000
k = 0
for i in d:
# print(i)
if d[i] < e_min:
e_min = d[i]
k = i
e_min
k
### 聚类成3个簇
clf = KMeans(n_clusters=3)
clf.fit(data)
data.head()
clf.labels_
#y_pred=clf.predict(data)
#y_pred
plt.scatter(data['每分钟助攻数'],data['每分钟得分数'],c=clf.labels_,marker='x')
clf.cluster_centers_
plt.scatter(data['每分钟助攻数'],data['每分钟得分数'],c=clf.labels_,marker='x')
plt.scatter(clf.cluster_centers_[:,0],clf.cluster_centers_[:,1],c='red')
plt.xlabel('assists per min')
plt.xlabel('points per min')
plt.title('KMeans Basketball data')
本文含有隐藏内容,请 开通VIP 后查看