Python_sklearn机器学习库学习笔记(五)k-means(聚类)
# K的选择:肘部法则
如果问题中没有指定 的值,可以通过肘部法则这一技术来估计聚类数量。肘部法则会把不同 值的
成本函数值画出来。随着 值的增大,平均畸变程度会减小;每个类包含的样本数会减少,于是样本
离其重心会更近。但是,随着 值继续增大,平均畸变程度的改善效果会不断减低。 值增大过程
中,畸变程度的改善效果下降幅度最大的位置对应的 值就是肘部。
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#随机生成一个实数,范围在(0.5,1.5)之间
cluster1=np.random.uniform(0.5,1.5,(2,10))
cluster2=np.random.uniform(3.5,4.5,(2,10))
#hstack拼接操作
X=np.hstack((cluster1,cluster2)).T
plt.figure()
plt.axis([0,5,0,5])
plt.grid(True)
plt.plot(X[:,0],X[:,1],'k.')

%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\msyh.ttc", size=10)
#coding:utf-8
#我们计算K值从1到10对应的平均畸变程度:
from sklearn.cluster import KMeans
#用scipy求解距离
from scipy.spatial.distance import cdist
K=range(1,10)
meandistortions=[]
for k in K:
kmeans=KMeans(n_clusters=k)
kmeans.fit(X)
meandistortions.append(sum(np.min(
cdist(X,kmeans.cluster_centers_,
'euclidean'),axis=1))/X.shape[0])
plt.plot(K,meandistortions,'bx-')
plt.xlabel('k')
plt.ylabel(u'平均畸变程度',fontproperties=font)
plt.title(u'用肘部法则来确定最佳的K值',fontproperties=font)

import numpy as np
x1 = np.array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])
x2 = np.array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 1, 3])
X=np.array(list(zip(x1,x2))).reshape(len(x1),2)
plt.figure()
plt.axis([0,10,0,10])
plt.grid(True)
plt.plot(X[:,0],X[:,1],'k.')

from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
K=range(1,10)
meandistortions=[]
for k in K:
kmeans=KMeans(n_clusters=k)
kmeans.fit(X)
meandistortions.append(sum(np.min(cdist(
X,kmeans.cluster_centers_,"euclidean"),axis=1))/X.shape[0])
plt.plot(K,meandistortions,'bx-')
plt.xlabel('k')
plt.ylabel(u'平均畸变程度',fontproperties=font)
plt.title(u'用肘部法则来确定最佳的K值',fontproperties=font)

# 聚类效果的评价
#### 轮廓系数(Silhouette Coefficient):s =ba/max(a, b)
import numpy as np
from sklearn.cluster import KMeans
from sklearn import metrics plt.figure(figsize=(8,10))
plt.subplot(3,2,1)
x1 = np.array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])
x2 = np.array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 1, 3])
X = np.array(list(zip(x1, x2))).reshape(len(x1), 2)
plt.xlim([0,10])
plt.ylim([0,10])
plt.title(u'样本',fontproperties=font)
plt.scatter(x1, x2)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b']
markers = ['o', 's', 'D', 'v', '^', 'p', '*', '+']
tests=[2,3,4,5,8]
subplot_counter=1
for t in tests:
subplot_counter+=1
plt.subplot(3,2,subplot_counter)
kmeans_model=KMeans(n_clusters=t).fit(X)
# print kmeans_model.labels_:每个点对应的标签值
for i,l in enumerate(kmeans_model.labels_):
plt.plot(x1[i],x2[i],color=colors[l],
marker=markers[l],ls='None')
plt.xlim([0,10])
plt.ylim([0,10])
plt.title(u'K = %s, 轮廓系数 = %.03f' %
(t, metrics.silhouette_score
(X, kmeans_model.labels_,metric='euclidean'))
,fontproperties=font)

# 图像向量化
import numpy as np
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
import mahotas as mh original_img=np.array(mh.imread('tree.bmp'),dtype=np.float64)/255
original_dimensions=tuple(original_img.shape)
width,height,depth=tuple(original_img.shape)
image_flattend=np.reshape(original_img,(width*height,depth)) print image_flattend.shape
image_flattend
输出结果:
(102672L, 3L)
array([[ 0.55686275, 0.57647059, 0.61960784],
[ 0.68235294, 0.70196078, 0.74117647],
[ 0.72156863, 0.7372549 , 0.78039216],
...,
[ 0.75686275, 0.63529412, 0.46666667],
[ 0.74117647, 0.61568627, 0.44705882],
[ 0.70588235, 0.57647059, 0.40784314]])
然后我们用K-Means算法在随机选择1000个颜色样本中建立64个类。每个类都可能是压缩调色板中的一种颜色
image_array_sample=shuffle(image_flattend,random_state=0)[:1000]
image_array_sample.shape
estimator=KMeans(n_clusters=64,random_state=0)
estimator.fit(image_array_sample) #之后,我们为原始图片的每个像素进行类的分配
cluster_assignments=estimator.predict(image_flattend) print cluster_assignments.shape
cluster_assignments
输出结果:
(102672L,)
array([59, 39, 33, ..., 46, 8, 17])
#最后,我们建立通过压缩调色板和类分配结果创建压缩后的图片:
compressed_palette = estimator.cluster_centers_
compressed_img = np.zeros((width, height, compressed_palette.shape[1]))
label_idx = 0
for i in range(width):
for j in range(height):
compressed_img[i][j] = compressed_palette[cluster_assignments[label_idx]]
label_idx += 1
plt.subplot(122)
plt.title('Original Image')
plt.imshow(original_img)
plt.axis('off')
plt.subplot(121)
plt.title('Compressed Image')
plt.imshow(compressed_img)
plt.axis('off')
plt.show()

Python_sklearn机器学习库学习笔记(五)k-means(聚类)的更多相关文章
- Python_sklearn机器学习库学习笔记(一)_一元回归
一.引入相关库 %matplotlib inline import matplotlib.pyplot as plt from matplotlib.font_manager import FontP ...
- Python_sklearn机器学习库学习笔记(一)_Feature Extraction and Preprocessing(特征提取与预处理)
# Extracting features from categorical variables #Extracting features from categorical variables 独热编 ...
- Python_sklearn机器学习库学习笔记(七)the perceptron(感知器)
一.感知器 感知器是Frank Rosenblatt在1957年就职于Cornell航空实验室时发明的,其灵感来自于对人脑的仿真,大脑是处理信息的神经元(neurons)细胞和链接神经元细胞进行信息传 ...
- Python_sklearn机器学习库学习笔记(三)logistic regression(逻辑回归)
# 逻辑回归 ## 逻辑回归处理二元分类 %matplotlib inline import matplotlib.pyplot as plt #显示中文 from matplotlib.font_m ...
- Python_sklearn机器学习库学习笔记(六) dimensionality-reduction-with-pca
# 用PCA降维 #计算协方差矩阵 import numpy as np X=[[2,0,-1.4], [2.2,0.2,-1.5], [2.4,0.1,-1], [1.9,0,-1.2]] np.c ...
- Python_sklearn机器学习库学习笔记(四)decision_tree(决策树)
# 决策树 import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.cross_validat ...
- muduo网络库学习笔记(五) 链接器Connector与监听器Acceptor
目录 muduo网络库学习笔记(五) 链接器Connector与监听器Acceptor Connector 系统函数connect 处理非阻塞connect的步骤: Connetor时序图 Accep ...
- thon_sklearn机器学习库学习笔记(四)decision_tree(决策树)
# 决策树 import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.cross_validat ...
- 机器学习实战(Machine Learning in Action)学习笔记————06.k-均值聚类算法(kMeans)学习笔记
机器学习实战(Machine Learning in Action)学习笔记————06.k-均值聚类算法(kMeans)学习笔记 关键字:k-均值.kMeans.聚类.非监督学习作者:米仓山下时间: ...
随机推荐
- hive UDF函数
虽然Hive提供了很多函数,但是有些还是难以满足我们的需求.因此Hive提供了自定义函数开发 自定义函数包括三种UDF.UADF.UDTF UDF(User-Defined-Function) ...
- FIREDAC直连ORACLE数据库
UniDac对Oracle的Direct连接,不需要套Oracle客户端dll,deploy时真的时 方便又快捷.FireDac连接Oracle,在没有Oracle Client的情况下,是可以连接上 ...
- 斯特灵数 (Stirling数)
@维基百科 在组合数学,Stirling数可指两类数,都是由18世纪数学家James Stirling提出的. 第一类 s(4,2)=11 第一类Stirling数是有正负的,其绝对值是个元素的项目分 ...
- cookie.js 加载顺序问题
今天遇到一个问题,在使用cookie.js时,只有在jquery.js文件后加载整体才有效 有效加载顺序 <head> <script type="text/javascr ...
- TinyTask Portable(录制和回放电脑操作过程)
一直想找个软件,可以回放自己或他人编码的过程.我认为,只有亲眼看到别人是怎么做的,才能更好的了解他人的思路. 虽然找到http://thecodeplayer.com/这个,但它只能回放它上面的代码, ...
- mysql和oracle日期和字符相互转换
一.mysql日期和字符相互转换 1.1.日期——>字符 date_format(date,'%Y-%m-%d') oracle中的to_char(); 1.2.字符——> ...
- cocos2d-x CCListView
转自:http://blog.csdn.net/onerain88/article/details/7641126 cocos2d-x 2.0 版更新了,把opengl 1.1 替换为opengl 2 ...
- 用VS2010开发Android应用的配置方法
在开发你的第一个Android应用程序之前,你应该先检查一下是否安装了Android SDK,以及是否创建好了Android模拟器(AVD),如果有不清楚的地方,请先看百度这篇文章“Android是什 ...
- socket通信简单介绍
“一切皆Socket!” 话虽些许夸张,可是事实也是,如今的网络编程差点儿都是用的socket. ——有感于实际编程和开源项目研究. 我们深谙信息交流的价值,那网络中进程之间怎样通信,如我们每天打开浏 ...
- android151 笔记
13. 14 .什么是Service以及描述下它的生命周期.Service有哪些启动方法,有什么区别,怎样停用Service? 在Service的生命周期中,被回调的方法比Activity少一些,只有 ...