初识sklearn,了解clustering

sklearn 是一个 Python 的 科学计算库,提供了数种聚类算法可供选择

numpy、scipy 是 Python 的科学运算库,matplotlib 是图形库,用于绘图

首先是安装环境

sudo pipinstallnumpy scipy sklearn matplotlib

# 安装完成后跑一下 scipy 的测试

importscipyscipy.test()

如果有报错的话就把 numpy 和 scipy 卸载了重新装一次

装 sklearn 后常常会有冲突,重装一下 numpy 和 scipy 就好了

sudo pipuninstallnumpy, scipy

sudo pipinstallnumpy, scipy

如果是 Mac 系统的话,建议把 /Library/Python/2.7/site-packages/ 里面的 numpy、scipy 等库都删了再安装,不然很容易因为版本不同而冲突

效果图

范例代码(等以后有空再来逐行解释)

 
  

#! /usr/bin/env python

# -*- coding: utf-8

from __future__ import unicode_literals

import datetime

from collections import Counter

import numpy as np

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

from sklearn import cluster

from sklearn import datasets

iris = datasets.load_iris()

# X_iris = iris.data[50: 100]

X_iris = iris.data

Y_iris = iris.target

geo = 231

# X_iris = np.delete(X_iris, 3, axis=1)

# X_iris /= 10.

def timeit(name=None):

"""

@decorate

"""

def wrapper2(func):

def wrapper1(*args, **kargs):

start = datetime.datetime.now()

r = func(*args, **kargs)

end = datetime.datetime.now()

print '---------------'

print 'project name: %s' % name

print 'start at: %s' % start

print 'end at:  %s' % end

print 'cost:    %s' % (end - start)

print 'res:      %s' % r

print 'err1:    %s' \

% (50 - Counter(r[: 50]).most_common()[0][1])

print 'err2:    %s' \

% (50 - Counter(r[50: 100]).most_common()[0][1])

print 'err3:    %s' \

% (50 - Counter(r[100: 150]).most_common()[0][1])

print '---------------'

return r

return wrapper1

return wrapper2

def randrange(n, vmin, vmax):

return (vmax - vmin) * np.random.rand(n) + vmin

@timeit('target')

def target(fig):

global X_iris, Y_iris, geo

ax = fig.add_subplot(geo + 0, projection='3d', title='target')

for n, i in enumerate(X_iris):

ax.scatter(*i[: 3], c=['r', 'y', 'g'][Y_iris[n]], marker='o')

ax.set_xlabel('X Label')

ax.set_ylabel('Y Label')

ax.set_zlabel('Z Label')

return Y_iris

# kmeans

@timeit('kmeans')

def kmeans(fig):

global X_iris, geo

ax = fig.add_subplot(geo + 1, projection='3d', title='k-means')

k_means = cluster.KMeans(init='random', n_clusters=3)

k_means.fit(X_iris)

res = k_means.labels_

for n, i in enumerate(X_iris):

ax.scatter(*i[: 3], c='bgrcmyk'[res[n] % 7], marker='o')

ax.set_xlabel('X Label')

ax.set_ylabel('Y Label')

ax.set_zlabel('Z Label')

return res

@timeit('mini_batch_kmeans')

def mini_batch(fig):

global X_iris, geo

ax = fig.add_subplot(geo + 2, projection='3d', title='mini-batch')

mini_batch = cluster.MiniBatchKMeans(init='random', n_clusters=3)

mini_batch.fit(X_iris)

res = mini_batch.labels_

for n, i in enumerate(X_iris):

ax.scatter(*i[: 3], c='bgrcmyk'[res[n] % 7], marker='o')

ax.set_xlabel('X Label')

ax.set_ylabel('Y Label')

ax.set_zlabel('Z Label')

return res

@timeit('affinity')

def affinity(fig):

global X_iris, geo

ax = fig.add_subplot(geo + 3, projection='3d', title='affinity')

affinity = cluster.AffinityPropagation(preference=-50)

affinity.fit(X_iris)

res = affinity.labels_

for n, i in enumerate(X_iris):

ax.scatter(*i[: 3], c='bgrcmyk'[res[n] % 7], marker='o')

ax.set_xlabel('X Label')

ax.set_ylabel('Y Label')

ax.set_zlabel('Z Label')

return res

@timeit('mean_shift')

def mean_shift(fig):

global X_iris, geo

ax = fig.add_subplot(geo + 4, projection='3d', title='mean_shift')

bandwidth = cluster.estimate_bandwidth(X_iris, quantile=0.2, n_samples=50)

mean_shift = cluster.MeanShift(bandwidth=bandwidth, bin_seeding=True)

mean_shift.fit(X_iris)

res = mean_shift.labels_

for n, i in enumerate(X_iris):

ax.scatter(*i[: 3], c='bgrcmyk'[res[n] % 7], marker='o')

ax.set_xlabel('X Label')

ax.set_ylabel('Y Label')

ax.set_zlabel('Z Label')

return res

@timeit('dbscan')

def dbscan(fig):

global X_iris, geo

ax = fig.add_subplot(geo + 5, projection='3d', title='dbscan')

dbscan = cluster.DBSCAN()

dbscan.fit(X_iris)

res = dbscan.labels_

core = dbscan.core_sample_indices_

print repr(core)

size = [5 if i not in core else 40 for i in range(len(X_iris))]

print repr(size)

for n, i in enumerate(X_iris):

ax.scatter(*i[: 3], s=size[n], c='bgrcmyk'[res[n] % 7],

alpha=0.8, marker='o')

ax.set_xlabel('X Label')

ax.set_ylabel('Y Label')

ax.set_zlabel('Z Label')

return res

def main():

fig = plt.figure()

target(fig)

kmeans(fig)

mini_batch(fig)

affinity(fig)

mean_shift(fig)

dbscan(fig)

plt.show()

if __name__ == '__main__':

main()



作者:hzyido
链接:http://www.jianshu.com/p/93c03a09d689
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本程序是在python中完成,基于sklearn.cluster中的k-means聚类包来实现数据的聚类,对于里面使用的数据格式如下:(注意更改程序中的相关参数) 138 0 124 1 127 2 129 3 119 4 127 5 124 6 120 7 123 8 147 9 188 10 212 11 229 12 240 13 240 14 241 15 240 16 242 17 174 18 130 19 132 20 119 21 48 22 37 23 49 0 42 1 34 2 26 3 20 4 21 5 23 6 13 7 19 8 18 9 36 10 25 11 20 12 19 13 19 14 5 15 29 16 22 17 13 18 46 19 15 20 8 21 33 22 41 23 69 0 56 1 49 2 40 3 52 4 62 5 54 6 32 7 38 8 44 9 55 10 70 11 74 12 105 13 107 14 56 15 55 16 65 17 100 18 195 19 136 20 87 21 64 22 77 23 61 0 53 1 47 2 33 3 34 4 28 5 41 6 40 7 38 8 33 9 26 10 31 11 31 12 13 13 17 14 17 15 25 16 17 17 17 18 14 19 16 20 17 21 29 22 44 23 37 0 32 1 34 2 26 3 23 4 25 5 25 6 27 7 30 8 25 9 17 10 12 11 12 12 12 13 7 14 6 15 6 16 12 17 12 18 39 19 34 20 32 21 34 22 35 23 33 0 57 1 81 2 77 3 68 4 61 5 60 6 56 7 67 8 102 9 89 10 62 11 57 12 57 13 64 14 62 15 69 16 81 17 77 18 64 19 62 20 79 21 75 22 57 23 73 0 88 1 75 2 70 3 77 4 73 5 72 6 76 7 76 8 74 9 98 10 90 11 90 12 85 13 79 14 79 15 88 16 88 17 81 18 84 19 89 20 79 21 68 22 55 23 63 0 62 1 58 2 58 3 56 4 60 5 56 6 56 7 58 8 56 9 65 10 61 11 60 12 60 13 61 14 65 15 55 16 56 17 61 18 64 19 69 20 83 21 87 22 84 23 41 0 35 1 38 2 45 3 44 4 49 5 55 6 47 7 47 8 29 9 14 10 12 11 4 12 10 13 9 14 7 15 7 16 11 17 12 18 14 19 22 20 29 21 23 22 33 23 34 0 38 1 38 2 37 3 37 4 34 5 24 6 47 7 70 8 41 9 6 10 23 11 4 12 15 13 3 14 28 15 17 16 31 17 39 18 42 19 54 20 47 21 68 22

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值