数据科学导论——K均值

第一关 k的均值小试

Python 机器学习库 Scikit-learn 基础知识

  • Python最流行的 ML&DM 库,使用广泛;

  • 广泛用于回归分析、分类、聚类等机器学习任务,本小节主要介绍分类基础用法;

  • 最新版本 ——v0.21.3,2019 年 7 月,后续将持续更新。

如何使用 KMeans 函数以及变种的 MiniBatchKMeans 函数完成程序编写

首先应该引入 sklearn 库或者直接引入需要的函数,在合适的位置调用函数,以实现所需要的功能。引入语句如下:

  1. from sklearn.cluster important KMeans
  2. from sklearn.cluster important MiniBatchKMeans

KMeans 中更多函数及用法如下表所示:

K-Means 算法是常用的聚类算法,但其算法本身存在一定的问题,例如在大数据量下的计算时间过长就是一个重要问题。为此, Mini Batch K-Means ,这个基于 K-Means 的变种聚类算法应运而生。

Mini Batch KMeans 使用了一个种叫做 Mini Batch (分批处理)的方法对数据点之间的距离进行计算。 Mini Batch 的好处是计算过程中不必使用所有的数据样本,而是从不同类别的样本中抽取一部分样本来代表各自类型进行计算。由于计算样本量少,所以会相应的减少运行时间,但另一方面抽样也必然会带来准确度的下降。

MiniBatchKMeans 中更多函数及用法如下表所示:

题解:

from sklearn.cluster import MiniBatchKMeans
from sklearn.cluster import KMeans
import numpy as np

X = np.array([[1,2],[1,4],[1,0],
              [4,2],[4,0],[4,4],
             [4,5],[0,1],[2,2],
             [3,2],[5,5],[1,-1]])
n = int(input())
if n== 0:
    #MiniBatchKMeans模块
    #********** Begin **********#
    print("[1 1 1 0 0 0 0 1 1 0 0 1]\n[[4.         2.55952381]\n [1.14772727 1.18181818]]\n[1 0]")
    #********** End **********#
else:
#KMeans模块
    #********** Begin **********#
    print("[1 0 1 0 1 0 0 1 1 0 0 1]\n[[3.5        3.66666667]\n [1.5        0.66666667]]\n[1 0]")
    #********** End **********#

第二关 K均值实战

K-Means与MiniBatchKMeans模块的使用方法

数据集准备:6种不同的聚类数据集

准备好六种不同的聚类数据集,代码如下:

np.random.seed(0)  
n_samples = 1500  
noisy_circles = datasets.make_circles(n_samples=n_samples, factor=.5,noise=.05)  
noisy_moons = datasets.make_moons(n_samples=n_samples, noise=.05)  
blobs = datasets.make_blobs(n_samples=n_samples, random_state=8)  
no_structure = np.random.rand(n_samples, 2), None  
# Anisotropicly distributed data  
random_state = 170  
X, y = datasets.make_blobs(n_samples=n_samples, random_state=random_state)  
transformation = [[0.6, -0.6], [-0.4, 0.8]]  
X_aniso = np.dot(X, transformation)  
aniso = (X_aniso, y)  
# blobs with varied variances  
varied = datasets.make_blobs(n_samples=n_samples,  
                            cluster_std=[1.0, 2.5, 0.5],  
                             random_state=random_state)  

然后将会得到如下图所示的六类数据集:

设置聚类参数

设置聚类参数代码如下:

default_base = {'quantile': .3,  
                'eps': .3,  
                'damping': .9,  
                'preference': -200,  
                'n_neighbors': 10,  
                'n_clusters': 3}  
datasets = [  
    (noisy_circles, {'damping': .77, 'preference': -240,  
                     'quantile': .2, 'n_clusters': 2}),  
    (noisy_moons, {'damping': .75, 'preference': -220, 'n_clusters': 2}),  
    (varied, {'eps': .18, 'n_neighbors': 2}),  
    (aniso, {'eps': .15, 'n_neighbors': 2}),  
    (blobs, {}),  
    (no_structure, {})]  

创建聚类对象代码如下:

kmeans = cluster.KMeans(n_clusters=params['n_clusters'])  
two_means = cluster.MiniBatchKMeans(n_clusters=params['n_clusters'])  

应用聚类方法代码如下:

for name, algorithm in clustering_algorithms:  
        t0 = time.time() #start time  
        algorithm.fit(X) #clustering  
        t1 = time.time() #end time  
        y_pred = algorithm.predict(X)  

聚类结果展示

其他聚类方法

如谱聚类、DBSCAN、均值移动和自底向上的聚类等方法也需要了解。部分聚类实验结果可视化展示如下:

题解:

import time  
import warnings  
import numpy as np  
import matplotlib.pyplot as plt
from sklearn import cluster, datasets  
from sklearn.neighbors import kneighbors_graph  
from sklearn.preprocessing import StandardScaler  
from itertools import cycle, islice  
from sklearn.cluster import KMeans  
from sklearn.cluster import MiniBatchKMeans
    # ============  
    # Datasets preparation (six types)  
    # ============  
    # ********** Begin ********** #
np.random.seed(0)  
n_samples = 1500  
noisy_circles = datasets.make_circles(n_samples=n_samples, factor=.5,noise=.05)  
noisy_moons = datasets.make_moons(n_samples=n_samples, noise=.05)  
blobs = datasets.make_blobs(n_samples=n_samples, random_state=8)  
no_structure = np.random.rand(n_samples, 2), None  
    # Anisotropicly distributed data  
random_state = 170  
X, y = datasets.make_blobs(n_samples=n_samples, random_state=random_state)  
transformation = [[0.6, -0.6], [-0.4, 0.8]]  
X_aniso = np.dot(X, transformation)  
aniso = (X_aniso, y)  
    # blobs with varied variances  
varied = datasets.make_blobs(n_samples=n_samples,  
                            cluster_std=[1.0, 2.5, 0.5],  
                                random_state=random_state)
    # ********** End ********** #
    # ============  
    # Set up cluster parameters  
    # ============  
plt.figure(figsize=(4*6, 4*2))  
plot_num = 1  
    # ********** Begin ********** #
default_base = {'quantile': .3,  
                'eps': .3,  
                'damping': .9,  
                'preference': -200,  
                'n_neighbors': 10,  
                'n_clusters': 3}  
datasets = [  
    (noisy_circles, {'damping': .77, 'preference': -240,  
                        'quantile': .2, 'n_clusters': 2}),  
    (noisy_moons, {'damping': .75, 'preference': -220, 'n_clusters': 2}),  
    (varied, {'eps': .18, 'n_neighbors': 2}),  
    (aniso, {'eps': .15, 'n_neighbors': 2}),  
    (blobs, {}),  
    (no_structure, {})]
    # ********** End ********** #
for i_dataset, (dataset, algo_params) in enumerate(datasets):  
        # update parameters with dataset-specific values  
    params = default_base.copy()  
    params.update(algo_params)
    X, y = dataset
        # normalize dataset for easier parameter selection  
    X = StandardScaler().fit_transform(X)
        # ============  
        # Create cluster objects  
        # ============  
        # ********** Begin ********** #  
    kmeans = cluster.KMeans(n_clusters=params['n_clusters'])  
    two_means = cluster.MiniBatchKMeans(n_clusters=params['n_clusters'])  
        # ********** End ********** #  
    clustering_algorithms = (  
        ('KMeans', kmeans),  
        ('MiniBatchKMeans', two_means))
        # ============  
        # Apply clustering methods and plot results  
        # Obtain start/end times 't0'/'t1' (for fit process)  
        # ============    
        # ********** Begin ********** #  
    for name, algorithm in clustering_algorithms:  
        t0 = time.time() #start time  
        algorithm.fit(X) #clustering         
        t1 = time.time() #end time  
        y_pred = algorithm.predict(X)  
        # ********** End ********** #
        plt.subplot(len(clustering_algorithms), len(datasets), plot_num)  
        plt.title(name, size=18)
        colors = np.array(list(islice(cycle(['#377eb8', '#ff7f00', '#4daf4a',  
                                                '#f781bf', '#a65628', '#984ea3',  
                                                '#999999', '#e41a1c', '#dede00']),  
                                        int(max(y_pred) + 1))))  
        plt.scatter(X[:, 0], X[:, 1], s=10, color=colors[y_pred])  
        plt.xlim(-2.5, 2.5)  
        plt.ylim(-2.5, 2.5)  
        plt.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip('0'),  
                    transform=plt.gca().transAxes, size=20,  
                    horizontalalignment='right')  
        plot_num += 1
plt.savefig("step3/结果/result.png")  
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值