赞
踩
Python 机器学习库 Scikit-learn 基础知识
Python最流行的 ML&DM 库,使用广泛;
广泛用于回归分析、分类、聚类等机器学习任务,本小节主要介绍分类基础用法;
最新版本 ——v0.21.3,2019 年 7 月,后续将持续更新。
如何使用 KMeans 函数以及变种的 MiniBatchKMeans 函数完成程序编写
首先应该引入 sklearn 库或者直接引入需要的函数,在合适的位置调用函数,以实现所需要的功能。引入语句如下:
from sklearn.cluster important KMeans
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-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")

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。