Packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cluster import KMeans
import sklearn.metrics as sm
%matplotlib inline
引入数据集
iris = datasets.load_iris()
Feature数据
iris.feature_names
实际的分类,用来计算accuracy
iris.target
iris.target_names
把数据转换成 dataframe
x = pd.DataFrame(iris.data)
x.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
y = pd.DataFrame(iris.target)
y.columns = ['Targets']
可视化看一下数据的分类是怎样的
plt.figure(figsize=(14,7))
colormap = np.array(['red', 'lime', 'black'])
plt.subplot(1, 2, 1)
plt.scatter(x.sepal_length, x.sepal_width, c=colormap[y.Targets], s=40)
plt.title('sepal')
plt.subplot(1, 2, 2)
plt.scatter(x.petal_length, x.petal_width, c=colormap[y.Targets], s=40)
plt.title('petal')
应用KMeans模型
model = KMeans(n_clusters=3)
model.fit(x)
看结果
model.labels_
可视化结果
左图是实际值,右图是模型输出 model.labels_ 标注的
plt.figure(figsize=(14, 7))
colormap = np.array(['red', 'lime', 'black'])
plt.subplot(1, 2, 1)
plt.scatter(x.petal_length, x.petal_width, c=colormap[y.Targets], s=40)
plt.title('Real Classification')
plt.subplot(1, 2, 2)
plt.scatter(x.petal_length, x.petal_width, c=colormap[model.labels_], s=40)
plt.title('K Mean Classification')
为了类别颜色一致,需要调换
[2, 0, 1]根据不同的运行而不同,根据自己情况,左右对比去调换
predY = np.choose(model.labels_, [2, 0, 1]).astype(np.int64)
现在再看对比图
plt.figure(figsize=(14, 7))
colormap = np.array(['red', 'lime', 'black'])
plt.subplot(1, 2, 1)
plt.scatter(x.petal_length, x.petal_width, c=colormap[y.Targets], s=40)
plt.title('Real Classification')
plt.subplot(1, 2, 2)
plt.scatter(x.petal_length, x.petal_width, c=colormap[predY], s=40)
plt.title('K Mean Classification')
计算accuracy
sm.accuracy_score(y, predY)
0.89
看一下 confusion 矩阵
sm.confusion_matrix(y, predY)
这个矩阵是可以看出来,某一个实际的类被分辨成其他类的个数。
以上就是一个很清爽的例子。
文/不会停的蜗牛(简书作者)
原文链接:http://www.jianshu.com/p/66e928c815f2
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原文链接:http://www.jianshu.com/p/66e928c815f2
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原创文章,作者:xsmile,如若转载,请注明出处:http://www.17bigdata.com/%e4%b8%80%e4%b8%aa%e7%ae%80%e5%8d%95%e7%9a%84-kmeans-python%e5%ae%9e%e4%be%8b/
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载