Scikit Learn 简明教程

Scikit Learn - Quick Guide

Scikit Learn - Introduction

在本章中,我们将了解什么是 Scikit-Learn 或 Sklearn、Scikit-Learn 的起源以及其他一些相关主题,例如负责 Scikit-Learn 开发和维护的社区和贡献者、它的前提条件、安装和它的特性。

What is Scikit-Learn (Sklearn)

Scikit-learn (Sklearn) 是 Python 中最有用且健壮的机器学习库。它通过 Python 中的一致界面提供一系列高效的工具,用于机器学习和统计建模,包括分类、回归、聚类和降维。此库在很大程度上是用 Python 编写的,它基于 NumPy, SciPyMatplotlib 构建。

Origin of Scikit-Learn

它最初称为 scikits.learn ,最初由 David Cournapeau 在 2007 年作为谷歌代码夏季项目开发。后来,在 2010 年,来自 FIRCA(法国计算机科学与自动化研究院)的 Fabian Pedregosa、Gael Varoquaux、Alexandre Gramfort 和 Vincent Michel 将该项目带到了另一个层次,并于 2010 年 2 月 1 日发布了第一个公开版本 (v0.1 beta)。

让我们看看它的版本历史 −

  1. May 2019: scikit-learn 0.21.0

  2. March 2019: scikit-learn 0.20.3

  3. December 2018: scikit-learn 0.20.2

  4. November 2018: scikit-learn 0.20.1

  5. September 2018: scikit-learn 0.20.0

  6. July 2018: scikit-learn 0.19.2

  7. July 2017: scikit-learn 0.19.0

  8. September 2016. scikit-learn 0.18.0

  9. November 2015. scikit-learn 0.17.0

  10. March 2015. scikit-learn 0.16.0

  11. July 2014. scikit-learn 0.15.0

  12. August 2013. scikit-learn 0.14

Community & contributors

Scikit-learn 是一项社区工作,任何人都可以为它做出贡献。此项目托管在 https://github.com/scikit-learn/scikit-learn. 上,当前有以下人员是 Sklearn 开发和维护的核心贡献者 −

  1. Joris Van den Bossche(数据科学家)

  2. Thomas J Fan(软件开发人员)

  3. Alexandre Gramfort(机器学习研究员)

  4. Olivier Grisel(机器学习专家)

  5. Nicolas Hug(助理研究科学家)

  6. Andreas Mueller(机器学习科学家)

  7. Hanmin Qin (Software Engineer)

  8. Adrin Jalali(开源开发人员)

  9. Nelle Varoquaux(数据科学研究员)

  10. Roman Yurchak (Data Scientist)

各种机构都在使用 Sklearn,例如 Booking.com、JP Morgan、Evernote、Inria、AWeber、Spotify 以及更多其他机构。

Prerequisites

在我们开始使用 scikit-learn 的最新版本之前,我们需要满足以下要求:

  1. Python (>=3.5)

  2. NumPy (>= 1.11.0)

  3. Scipy (>= 0.17.0)li

  4. Joblib (>= 0.11)

  5. 需要使用 Matplotlib(>= 1.5.1)来获取 Sklearn 的绘图能力。

  6. 需要使用 Pandas(>= 0.18.0)来获取一些使用数据结构和分析的 scikit-learn 示例。

Installation

如果您已安装 NumPy 和 Scipy,以下是安装 scikit-learn 的两种最简单的方法:

Using pip

可以使用以下命令通过 pip 安装 scikit-learn:

pip install -U scikit-learn

Using conda

可以使用以下命令通过 conda 安装 scikit-learn:

conda install scikit-learn

另一方面,如果尚未在您的 Python 工作站安装 NumPy 和 Scipy,则可以使用 pipconda 来安装它们。

使用 scikit-learn 的另一种选择是使用 Python 发行版,例如 CanopyAnaconda ,因为它们都随附最新版本的 scikit-learn。

Features

Scikit-learn 库专注于对数据进行建模,而不是专注于加载、处理和汇总数据。Sklearn 提供的一些最流行的模型组如下:

Supervised Learning algorithms - scikit-learn 包含几乎所有的流行监督学习算法,例如线性回归、支持向量机 (SVM)、决策树等。

Unsupervised Learning algorithms - 另一方面,它还包含从聚类、因子分析、PCA(主成分分析)到无监督神经网络的所有流行无监督学习算法。

Clustering - 此模型用于对未标记的数据进行分组。

Cross Validation − 用于检查监督模型在未见过数据上的准确性。

Dimensionality Reduction − 用于减少数据中的属性数量,此数量可进一步用于汇总、可视化和功能选择。

Ensemble methods − 如名称所示,用于组合多个监督模型的预测。

Feature extraction − 用于从数据中提取功能,以便定义图像和文本数据中的属性。

Feature selection − 用于识别创建监督模型的有用属性。

Open Source − 它是开源库,也可以在 BSD 许可证下进行商业使用。

Scikit Learn - Modelling Process

本章介绍 Sklearn 中涉及的建模流程。让我们详细了解一下并从加载数据集开始。

Dataset Loading

一个数据集合称为数据集。它具有以下两个组成部分:

Features - 数据变量称为其特征。它们也称为预测变量、输入或属性。

  1. Feature matrix - 如果有多个特征,则称为特征集合。

  2. Feature Names - 它是所有特征名称的列表。

Response - 它是输出变量,基本上取决于特征变量。它们也称为目标、标签或输出。

  1. Response Vector - 用它来表示响应列。通常,我们只有一个响应列。

  2. Target Names - 它表示响应向量可能取的值。

Scikit-learn 有几个示例数据集,如 irisdigits 用于分类, Boston house prices 用于回归。

Example

以下是一个加载 iris 数据集的示例:

from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names
target_names = iris.target_names
print("Feature names:", feature_names)
print("Target names:", target_names)
print("\nFirst 10 rows of X:\n", X[:10])

Output

Feature names: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
Target names: ['setosa' 'versicolor' 'virginica']
First 10 rows of X:
[
   [5.1 3.5 1.4 0.2]
   [4.9 3. 1.4 0.2]
   [4.7 3.2 1.3 0.2]
   [4.6 3.1 1.5 0.2]
   [5. 3.6 1.4 0.2]
   [5.4 3.9 1.7 0.4]
   [4.6 3.4 1.4 0.3]
   [5. 3.4 1.5 0.2]
   [4.4 2.9 1.4 0.2]
   [4.9 3.1 1.5 0.1]
]

Splitting the dataset

要检查我们模型的准确性,我们可以将数据集分成两部分- a training seta testing set 。使用训练集训练模型,使用测试集测试模型。然后,我们可以评估我们的模型表现如何。

Example

以下示例将以 70:30 的比例分割数据,即 70% 的数据将用作训练数据,30% 将用作测试数据。正如上面的示例中,数据集是 iris 数据集。

from sklearn.datasets import load_iris
iris = load_iris()

X = iris.data
y = iris.target

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
   X, y, test_size = 0.3, random_state = 1
)

print(X_train.shape)
print(X_test.shape)

print(y_train.shape)
print(y_test.shape)

Output

(105, 4)
(45, 4)
(105,)
(45,)

如上例所示,它使用 scikit-learn 的 train_test_split() 函数来分割数据集。该函数具有以下参数:

  1. X, y - 在这里, Xfeature matrix ,y 是 response vector ,需要分割。

  2. test_size - 它表示测试数据与给定总数据的比率。正如在上面的示例中,我们在 X 的 150 行中设置 test_data = 0.3 。它会产生 150*0.3 = 45 行的测试数据。

  3. random_size - 用它来确保分割始终相同。这在需要可重复结果的情况下很有用。

Train the Model

接下来,我们可以使用我们的数据集来训练一些预测模型。正如所讨论的,scikit-learn 具有各种 Machine Learning (ML) algorithms ,它们具有用于拟合、预测准确率、召回率等的统一接口。

Example

在下面的示例中,我们将使用 KNN(K 最近邻)分类器。不要深入了解 KNN 算法的详细信息,因为会有单独的一章介绍它。此示例仅用于让您理解实现部分。

from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
   X, y, test_size = 0.4, random_state=1
)
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
classifier_knn = KNeighborsClassifier(n_neighbors = 3)
classifier_knn.fit(X_train, y_train)
y_pred = classifier_knn.predict(X_test)
# Finding accuracy by comparing actual response values(y_test)with predicted response value(y_pred)
print("Accuracy:", metrics.accuracy_score(y_test, y_pred))
# Providing sample data and the model will make prediction out of that data

sample = [[5, 5, 3, 2], [2, 4, 3, 5]]
preds = classifier_knn.predict(sample)
pred_species = [iris.target_names[p] for p in preds] print("Predictions:", pred_species)

Output

Accuracy: 0.9833333333333333
Predictions: ['versicolor', 'virginica']

Model Persistence

一旦你训练了模型,那么最好让该模型持久化以便于将来使用,这样我们就无需一遍遍地重新训练它。这可以通过 joblib 包的 dumpload 特性来完成。

考虑下面的示例,其中我们将保存上述训练的模型(classifier_knn)以备将来使用:

from sklearn.externals import joblib
joblib.dump(classifier_knn, 'iris_classifier_knn.joblib')

上述代码会将模型保存到名为 iris_classifier_knn.joblib 的文件中。现在,可以使用以下代码从文件中重新加载该对象:

joblib.load('iris_classifier_knn.joblib')

Preprocessing the Data

由于我们正在处理大量数据,并且该数据处于原始形式,因此在将该数据输入机器学习算法之前,我们需要将其转换为有意义的数据。这个过程称为数据预处理。Scikit-learn 为此目的有一个名为 preprocessing 的包。 preprocessing 包具有以下技术:

Binarisation

当我们需要将数值转换为布尔值时,使用此预处理技术。

Example

import numpy as np
from sklearn import preprocessing
Input_data = np.array(
   [2.1, -1.9, 5.5],
   [-1.5, 2.4, 3.5],
   [0.5, -7.9, 5.6],
   [5.9, 2.3, -5.8]]
)
data_binarized = preprocessing.Binarizer(threshold=0.5).transform(input_data)
print("\nBinarized data:\n", data_binarized)

在上述示例中,我们使用了 threshold value = 0.5 这就是为什么所有高于 0.5 的值都将转换为 1,所有低于 0.5 的值都将转换为 0。

Output

Binarized data:
[
   [ 1. 0. 1.]
   [ 0. 1. 1.]
   [ 0. 0. 1.]
   [ 1. 1. 0.]
]

Mean Removal

此技术用于从特征向量中消除平均值,以便每个特征都以零为中心。

Example

import numpy as np
from sklearn import preprocessing
Input_data = np.array(
   [2.1, -1.9, 5.5],
   [-1.5, 2.4, 3.5],
   [0.5, -7.9, 5.6],
   [5.9, 2.3, -5.8]]
)

#displaying the mean and the standard deviation of the input data
print("Mean =", input_data.mean(axis=0))
print("Stddeviation = ", input_data.std(axis=0))
#Removing the mean and the standard deviation of the input data

data_scaled = preprocessing.scale(input_data)
print("Mean_removed =", data_scaled.mean(axis=0))
print("Stddeviation_removed =", data_scaled.std(axis=0))

Output

Mean = [ 1.75 -1.275 2.2 ]
Stddeviation = [ 2.71431391 4.20022321 4.69414529]
Mean_removed = [ 1.11022302e-16 0.00000000e+00 0.00000000e+00]
Stddeviation_removed = [ 1. 1. 1.]

Scaling

我们使用此预处理技术来缩放特征向量。特征向量的缩放很重要,因为特征不应人为地过大或过小。

Example

import numpy as np
from sklearn import preprocessing
Input_data = np.array(
   [
      [2.1, -1.9, 5.5],
      [-1.5, 2.4, 3.5],
      [0.5, -7.9, 5.6],
      [5.9, 2.3, -5.8]
   ]
)
data_scaler_minmax = preprocessing.MinMaxScaler(feature_range=(0,1))
data_scaled_minmax = data_scaler_minmax.fit_transform(input_data)
print ("\nMin max scaled data:\n", data_scaled_minmax)

Output

Min max scaled data:
[
   [ 0.48648649 0.58252427 0.99122807]
   [ 0. 1. 0.81578947]
   [ 0.27027027 0. 1. ]
   [ 1. 0.99029126 0. ]
]

Normalisation

我们使用此预处理技术来修改特征向量。需要对特征向量进行归一化,以便可以按照常见比例测量特征向量。有两种归一化类型,如下所示:

L1 Normalisation

它也称为最小绝对偏差。它以一种方式修改值,使得每个行中的绝对值的总和始终保持到 1。以下示例显示了在输入数据上实现 L1 归一化的过程。

Example

import numpy as np
from sklearn import preprocessing
Input_data = np.array(
   [
      [2.1, -1.9, 5.5],
      [-1.5, 2.4, 3.5],
      [0.5, -7.9, 5.6],
      [5.9, 2.3, -5.8]
   ]
)
data_normalized_l1 = preprocessing.normalize(input_data, norm='l1')
print("\nL1 normalized data:\n", data_normalized_l1)

Output

L1 normalized data:
[
   [ 0.22105263 -0.2 0.57894737]
   [-0.2027027 0.32432432 0.47297297]
   [ 0.03571429 -0.56428571 0.4 ]
   [ 0.42142857 0.16428571 -0.41428571]
]

L2 Normalisation

也称为最小二乘。它以一种方式修改值,使得每个行中的平方和始终保持到 1。以下示例显示了在输入数据上实现 L2 归一化的过程。

Example

import numpy as np
from sklearn import preprocessing
Input_data = np.array(
   [
      [2.1, -1.9, 5.5],
      [-1.5, 2.4, 3.5],
      [0.5, -7.9, 5.6],
      [5.9, 2.3, -5.8]
   ]
)
data_normalized_l2 = preprocessing.normalize(input_data, norm='l2')
print("\nL1 normalized data:\n", data_normalized_l2)

Output

L2 normalized data:
[
   [ 0.33946114 -0.30713151 0.88906489]
   [-0.33325106 0.53320169 0.7775858 ]
   [ 0.05156558 -0.81473612 0.57753446]
   [ 0.68706914 0.26784051 -0.6754239 ]
]

Scikit Learn - Data Representation

众所周知,机器学习即将从数据创建模型。为了这个目的,计算机必须首先理解数据。接下来,我们将讨论各种方法,以便计算机可以理解如何表示数据。

Data as table

在 Scikit-learn 中表示数据的最佳方式是表格形式。表格表示一个 2-D 数据网格,其中行表示数据集的各个元素,而列表示与这些各个元素相关的数量。

Example

使用下面给出的示例,我们可以借助 python seaborn 库以 Pandas DataFrame 的形式下载 iris dataset

import seaborn as sns
iris = sns.load_dataset('iris')
iris.head()

Output

sepal_length sepal_width petal_length petal_width  species
0        5.1      3.5         1.4             0.2   setosa
1        4.9      3.0         1.4             0.2   setosa
2        4.7      3.2         1.3             0.2   setosa
3        4.6      3.1         1.5             0.2   setosa
4        5.0      3.6         1.4             0.2   setosa

从上面的输出中,我们可以看出数据中的每一行都代表一朵观察到的花,而行数代表数据集中花的总数。通常,我们将矩阵的行称为样本。

另一方面,数据中的每一列表示描述每个样本的定量信息。通常,我们将矩阵的列称为特征。

Data as Feature Matrix

特征矩阵可以定义为可以将信息视为二维矩阵的表格布局。它存储在名为 ` X ` 的变量中,并且假定为具有形状 [n_samples, n_features] 的二维矩阵。通常,它包含在 NumPy 数组或 Pandas DataFrame 中。正如前面所说的,样本始终表示由数据集描述的各个对象,而特征表示以定量方式描述每个样本的不同观察结果。

Data as Target array

除了特征矩阵(用 X 表示)之外,我们还有目标数组。它也称为标签。它用 y 表示。标签或目标数组通常是一维的,长度为 n_samples。它通常包含在 NumPy ` array ` 或 Pandas ` Series ` 中。目标数组可以同时具有值,连续数值和离散值。

How target array differs from feature columns?

我们可以通过一点来区分两者,即目标数组通常是我们希望从数据中预测的数量,即在统计学中它是因变量。

Example

在下面的示例中,从鸢尾数据集我们根据其他测量结果预测花卉的物种。在这种情况下,Species 列将被视为特征。

import seaborn as sns
iris = sns.load_dataset('iris')
%matplotlib inline
import seaborn as sns; sns.set()
sns.pairplot(iris, hue='species', height=3);

Output

target array
X_iris = iris.drop('species', axis=1)
X_iris.shape
y_iris = iris['species']
y_iris.shape

Output

(150,4)
(150,)

Scikit Learn - Estimator API

在本章中,我们将学习 Estimator API (应用程序编程接口)。让我们从了解什么是估计器 API 开始。

What is Estimator API

它是 Scikit-learn 实现的主要 API 之一。它为广泛的机器学习应用程序提供了一致的接口,因此 Scikit-Learn 中的所有机器学习算法都是通过估计器 API 实现的。从数据学习的对象(拟合数据)是一个估计器。它可用于任何算法,例如分类、回归、聚类,甚至可用于从原始数据中提取有用特征的转换器。

为了拟合数据,所有估计器对象都会公开一个接收显示为以下形式的数据集的 fit 方法 −

estimator.fit(data)

接下来,估计器所有参数均可在通过相应属性实例化后设置,如下所示。

estimator = Estimator (param1=1, param2=2)
estimator.param1

上面的输出将是 1。

一旦数据被拟合使用估算器,则从手头数据中估算参数。现在,所有估算的参数将作为估算器对象以一个下划线结尾的属性,如下所示 −

estimator.estimated_param_

Use of Estimator API

估算器的主要用途如下 −

Estimation and decoding of a model

估算器对象用于模型的估算和解码。此外,该模型被估算为以下内容的确定性函数 −

  1. 对象构建中提供的参数。

  2. 如果估算器的 random_state 参数设为无,则为全局随机状态 (numpy.random)。

  3. 传递到 fit, fit_transform, or fit_predict 最近一次调用的任何数据。

  4. partial_fit 一系列调用中传递的任何数据。

Mapping non-rectangular data representation into rectangular data

它将非矩形数据表示映射到矩形数据中。简单来说,它接受输入,其中每个样本并不表示为固定长度的类似数组的对象,并将每个样本的特征生成为类似数组的对象。

Distinction between core and outlying samples

它使用以下方法构建核心和离群样本之间的区别 −

  1. fit

  2. fit_predict if transductive

  3. predict if inductive

Guiding Principles

在设计 Scikit-Learn API 时,遵循以下指导原则 −

Consistency

此原则指出,所有对象应共享从一系列方法中提取的通用接口。文档应保持一致。

Limited object hierarchy

此指导原则指出 −

  1. 算法应由 Python 类表示

  2. 数据集应表示为标准格式,如 NumPy 数组、Pandas 数据框、SciPy 稀疏矩阵。

  3. 参数名称应使用标准 Python 字符串。

Composition

我们知道,ML 算法可表示为多项基本算法的序列。Scikit-learn 在需要时利用这些基本算法。

Sensible defaults

根据此原则,Scikit-learn 库在 ML 模型需要用户指定的参数时,定义适当的默认值。

Inspection

根据此指导原则,暴露每个指定的参数值为公共属性。

Steps in using Estimator API

下列是使用 Scikit-Learn 估计器 API 的步骤 −

Step 1: Choose a class of model

在第一步中,我们需要选择模型类。可以通过从 Scikit-learn 导入适当的估计器类来完成。

Step 2: Choose model hyperparameters

在这一步中,我们需要选择类模型超参数。可以通过用所需值初始化类来完成。

Step 3: Arranging the data

接下来,我们需要将数据整理到特征矩阵 (X) 和目标向量 (y) 中。

Step 4: Model Fitting

现在,我们需要将模型拟合到你的数据。可以通过调用模型实例的 fit() 方法来完成。

Step 5: Applying the model

拟合模型后,我们可以将它应用到新数据。对于监督学习,使用 predict() 方法来预测未知数据的标签。而对于无监督学习,使用 predict()transform() 来推断数据的属性。

Supervised Learning Example

这里,作为此过程的一个示例,我们取将线拟合到 (x,y) 数据(即 simple linear regression )的常见案例。

首先,我们需要加载数据集,我们正在使用鸢尾花数据集 −

Example

import seaborn as sns
iris = sns.load_dataset('iris')
X_iris = iris.drop('species', axis = 1)
X_iris.shape

Output

(150, 4)

Example

y_iris = iris['species']
y_iris.shape

Output

(150,)

Example

现在,对于此回归示例,我们准备使用以下示例数据 −

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.RandomState(35)
x = 10*rng.rand(40)
y = 2*x-1+rng.randn(40)
plt.scatter(x,y);

Output

supervised

因此,我们拥有上述数据来进行线性回归示例。

现在,我们可以使用此数据来应用上述步骤。

Choose a class of model

这里,我们计算一个简单的线性回归模型,需要导入线性回归类,如下所示 −

from sklearn.linear_model import LinearRegression

Choose model hyperparameters

一旦我们选择了模型类,我们就需要做出一些重要的选择,这些选择通常表示为超参数或模型拟合到数据之前必须设置的参数。这里,对于线性回归的此示例,我们希望使用 fit_intercept 超参数来拟合截距,如下所示 −

Example

model = LinearRegression(fit_intercept = True)
model

Output

LinearRegression(copy_X = True, fit_intercept = True, n_jobs = None, normalize = False)

Arranging the data

现在,正如我们所知,我们的目标变量 y 处于正确形式,即长度为 n_samples 的 1-D 数组。但是,我们需要重新整形特征矩阵 X 以使其成为大小为 [n_samples, n_features] 的矩阵。可按如下方式进行 −

Example

X = x[:, np.newaxis]
X.shape

Output

(40, 1)

Model fitting

一旦我们整理好数据,就可以拟合模型,即可以将我们的模型应用于数据。这可以通过 fit() 方法来完成,如下所示 −

Example

model.fit(X, y)

Output

LinearRegression(copy_X = True, fit_intercept = True, n_jobs = None,normalize = False)

在 Scikit-learn 中, fit() 进程有一些尾随的下划线。

对于此示例,下方的参数显示了数据的简单线性拟合的斜率 −

Example

model.coef_

Output

array([1.99839352])

下方的参数表示数据的简单线性拟合的截距 −

Example

model.intercept_

Output

-0.9895459457775022

Applying the model to new data

在训练模型后,我们可以将它应用到新数据。正如监督机器学习的主要任务是基于不属于训练集部分的新数据来评估模型。可按如下方式使用 predict() 方法来完成 −

Example

xfit = np.linspace(-1, 11)
Xfit = xfit[:, np.newaxis]
yfit = model.predict(Xfit)
plt.scatter(x, y)
plt.plot(xfit, yfit);

Output

model new data

Complete working/executable example

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

iris = sns.load_dataset('iris')
X_iris = iris.drop('species', axis = 1)
X_iris.shape
y_iris = iris['species']
y_iris.shape

rng = np.random.RandomState(35)
x = 10*rng.rand(40)
y = 2*x-1+rng.randn(40)
plt.scatter(x,y);
from sklearn.linear_model import LinearRegression
model = LinearRegression(fit_intercept=True)
model
X = x[:, np.newaxis]
X.shape

model.fit(X, y)
model.coef_
model.intercept_

xfit = np.linspace(-1, 11)
Xfit = xfit[:, np.newaxis]
yfit = model.predict(Xfit)
plt.scatter(x, y)
plt.plot(xfit, yfit);

Unsupervised Learning Example

在此,作为一个处理流程示例,我们取一个典型案例来降低 Iris 数据集的维度,以便更方便地对它进行可视化。对于本示例,我们将使用主成分分析 (PCA),一种快速线性降维技术。

像上面给出的示例一样,我们可以加载和绘制 iris 数据集中的随机数据。然后,我们可以按照以下步骤执行操作:

Choose a class of model

from sklearn.decomposition import PCA

Choose model hyperparameters

Example

model = PCA(n_components=2)
model

Output

PCA(copy = True, iterated_power = 'auto', n_components = 2, random_state = None,
   svd_solver = 'auto', tol = 0.0, whiten = False)

Model fitting

Example

model.fit(X_iris)

Output

PCA(copy = True, iterated_power = 'auto', n_components = 2, random_state = None,
   svd_solver = 'auto', tol = 0.0, whiten = False)

Transform the data to two-dimensional

Example

X_2D = model.transform(X_iris)

现在,我们可以按如下方式绘制结果:

Output

iris['PCA1'] = X_2D[:, 0]
iris['PCA2'] = X_2D[:, 1]
sns.lmplot("PCA1", "PCA2", hue = 'species', data = iris, fit_reg = False);

Output

two dimensional

Complete working/executable example

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

iris = sns.load_dataset('iris')
X_iris = iris.drop('species', axis = 1)
X_iris.shape
y_iris = iris['species']
y_iris.shape
rng = np.random.RandomState(35)
x = 10*rng.rand(40)
y = 2*x-1+rng.randn(40)
plt.scatter(x,y);
from sklearn.decomposition import PCA

model = PCA(n_components=2)
model
model.fit(X_iris)
X_2D = model.transform(X_iris)
iris['PCA1'] = X_2D[:, 0]
iris['PCA2'] = X_2D[:, 1]
sns.lmplot("PCA1", "PCA2", hue='species', data=iris, fit_reg=False);

Scikit Learn - Conventions

Scikit-learn 的对象共享一个统一的基本 API,它包含以下三个互补的接口 −

  1. Estimator interface − 它用于构建和拟合模型。

  2. Predictor interface − 它用于进行预测。

  3. Transformer interface − 它用于转换数据。

这些 API 采用简单的约定,并且设计选择旨在避免框架代码泛滥。

Purpose of Conventions

这些约定的目的是确保 API 坚持以下广泛原则 −

Consistency − 所有对象(无论是基础对象还是复合对象)都必须共享一致的接口,该接口由一组有限的方法组成。

Inspection − 由学习算法确定的构造函数参数和参数值应存储并公开为公有属性。

Non-proliferation of classes − 数据集应表示为 NumPy 数组或 Scipy 稀疏矩阵,而超参数名称和值应表示为标准 Python 字符串,以避免框架代码的扩散。

Composition − 无论算法是否可表示为序列或数据变换组合,或者自然地视为参数化为其他算法的元算法,都应由现有构建模块实现并组合。

Sensible defaults − 在 scikit-learn 中,每当操作需要用户定义的参数时,都会定义一个适当的默认值。此默认值应使操作以合理的方式执行,例如,为手头任务提供基线解决方案。

Various Conventions

以下是 Sklearn 中可用的约定 −

Type casting

它指出输入应转换为 float64 。在以下示例中, sklearn.random_projection 模块用于减少数据的维数,将进行解释 −

Example

import numpy as np
from sklearn import random_projection
rannge = np.random.RandomState(0)
X = range.rand(10,2000)
X = np.array(X, dtype = 'float32')
X.dtype
Transformer_data = random_projection.GaussianRandomProjection()
X_new = transformer.fit_transform(X)
X_new.dtype

Output

dtype('float32')
dtype('float64')

在上面的示例中,我们可以看到 X 是 float32 ,由 float64 转换为 fit_transform(X)

Refitting & Updating Parameters

可以通过 set_params() 方法在构造估计器后更新并重新拟合估计器的超参数。让我们看以下示例来理解它 −

Example

import numpy as np
from sklearn.datasets import load_iris
from sklearn.svm import SVC
X, y = load_iris(return_X_y = True)
clf = SVC()
clf.set_params(kernel = 'linear').fit(X, y)
clf.predict(X[:5])

Output

array([0, 0, 0, 0, 0])

一旦构造了估计器,上面的代码将通过 SVC.set_params() 将默认内核 rbf 更改为线性。

现在,以下代码将内核改回 rbf,重新拟合估计器并进行第二次预测。

Example

clf.set_params(kernel = 'rbf', gamma = 'scale').fit(X, y)
clf.predict(X[:5])

Output

array([0, 0, 0, 0, 0])

Complete code

以下是完整的可执行程序 −

import numpy as np
from sklearn.datasets import load_iris
from sklearn.svm import SVC
X, y = load_iris(return_X_y = True)
clf = SVC()
clf.set_params(kernel = 'linear').fit(X, y)
clf.predict(X[:5])
clf.set_params(kernel = 'rbf', gamma = 'scale').fit(X, y)
clf.predict(X[:5])

Multiclass & Multilabel fitting

对于多类拟合,学习和预测任务都取决于拟合目标数据的格式。使用的模块是 sklearn.multiclass 。检查以下示例,其中多类分类器拟合在 1d 数组上。

Example

from sklearn.svm import SVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import LabelBinarizer
X = [[1, 2], [3, 4], [4, 5], [5, 2], [1, 1]]
y = [0, 0, 1, 1, 2]
classif = OneVsRestClassifier(estimator = SVC(gamma = 'scale',random_state = 0))
classif.fit(X, y).predict(X)

Output

array([0, 0, 1, 1, 2])

在上面的示例中,分类器拟合在一维的多类标签数组上,因此 predict() 方法提供了相应的多类预测。但是,另一方面,还可以像下面这样拟合在二进制标签指示符的二维数组上 −

Example

from sklearn.svm import SVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import LabelBinarizer
X = [[1, 2], [3, 4], [4, 5], [5, 2], [1, 1]]
y = LabelBinarizer().fit_transform(y)
classif.fit(X, y).predict(X)

Output

array(
   [
      [0, 0, 0],
      [0, 0, 0],
      [0, 1, 0],
      [0, 1, 0],
      [0, 0, 0]
   ]
)

同样,在多标签拟合的情况下,可以像下面这样为一个实例分配多个标签 −

Example

from sklearn.preprocessing import MultiLabelBinarizer
y = [[0, 1], [0, 2], [1, 3], [0, 2, 3], [2, 4]]
y = MultiLabelBinarizer().fit_transform(y)
classif.fit(X, y).predict(X)

Output

array(
   [
      [1, 0, 1, 0, 0],
      [1, 0, 1, 0, 0],
      [1, 0, 1, 1, 0],
      [1, 0, 1, 1, 0],
      [1, 0, 1, 0, 0]
   ]
)

在上面的示例中, sklearn.MultiLabelBinarizer 用于将多标签的二维数组二值化以进行拟合。这就是 predict() 函数输出一个 2d 数组作为每个实例的多个标签的原因。

Scikit Learn - Linear Modeling

本章将助你了解 Scikit-Learn 中的线性建模。让我们从了解 Sklearn 中的线性回归开始。

以下表格列出了 Scikit-Learn 提供的各种线性模型 −

Sr.No

Model & Description

1

Linear Regression 这是研究因变量 (Y) 与给定的一组自变量 (X) 之间关系的最佳统计模型之一。

2

Logistic Regression 逻辑回归,尽管其名称如此,但它是一种分类算法而不是回归算法。基于给定的一组自变量,它用于估算离散值 (0 或 1,是/否,真/假)。

3

Ridge Regression 岭回归或 Tikhonov 正则化是一种执行 L2 正则化的正则化技术。它通过添加与系数的幅值平方的罚金 (收缩量) 等效的惩罚来修改损失函数。

4

Bayesian Ridge Regression 贝叶斯回归允许通过使用概率分布器而非点估计值来构建线性回归,以一种自然机制来从不足够的数据或分布不良的数据中存活。

5

LASSO LASSO 是一种执行 L1 正则化的正则化技术。它通过添加与系数绝对值的和等效的罚金 (收缩量) 来修改损失函数。

6

Multi-task LASSO 它允许联合拟合多重回归问题,强迫所选特征对于所有回归问题来说是相同的,即所谓的任务。Sklearn 提供了一个名为 MultiTaskLasso 的线性模型,使用混合 L1、L2 范数进行正则化训练,该模型联合估算多个回归问题的稀疏系数。

7

Elastic-Net Elastic-Net 是一种正则化回归方法,它线性组合 Lasso 和 Ridge 回归方法的两个惩罚,即,L1 和 L2。当存在多个相关特征时,此方法很有用。

8

Multi-task Elastic-Net 此 Elastic-Net 模型能够联合拟合多个回归问题,强制为所有回归问题(也称为任务)选择相同的特征。

Scikit Learn - Extended Linear Modeling

本章重点介绍了 Sklearn 中的多项式特征和管道工具。

Introduction to Polynomial Features

针对数据非线性函数训练的线性模型,通常保持线性方法的快速性能。它还允许它们拟合更广泛的数据范围。这就是机器学习中使用针对非线性函数训练的这种线性模型的原因。

一个这样的示例是简单的线性回归可以通过从系数构造多项式特征来扩展。

在数学上,假设我们有标准线性回归模型,那么对于 2-D 数据而言,它会如下所示:

现在,我们可以将特征组合成二次多项式,我们的模型将如下所示:

以上仍然是线性模型。在这里,我们看到生成的多项式回归属于相同的线性模型类别,并且可以类似地求解。

为此,scikit-learn 提供了一个名为 PolynomialFeatures 的模块。此模块将输入数据矩阵转换为给定度的新数据矩阵。

Parameters

下表包含 PolynomialFeatures 模块使用的参数

Sr.No

Parameter & Description

1

degree − 整数,默认值 = 2它表示多项式特征的度。

2

interaction_only − 布尔值,默认值为 false默认情况下,它为 false,但如果设置为 true,则会生成大多数度不同输入特征的乘积的特征。此类特征称为交互特征。

3

include_bias - 布尔值,默认值为 true 它包括偏差列,即所有多项式幂为零的特征。

4

order - str 在 {‘C’, ‘F’} 中,默认值为 ‘C’ 此参数表示稠密情况下的输出数组的顺序。‘F’ 顺序表示计算速度更快,但另一方面,它可能会减慢后续估计器的速度。

Attributes

下表包含 PolynomialFeatures 模块使用的属性

Sr.No

Attributes & Description

1

powers_ - 数组,形状 (n_output_features, n_input_features) 它显示 powers_ [i,j] 是第 i 个输出中第 j 个输入的指数。

2

n_input_features _ - 整数 名称暗示了这一点,它给出了输入特征的总数。

3

n_output_features _ - 整数 名称暗示了这一点,它给出了多项式输出特征的总数。

Implementation Example

以下 Python 脚本使用 PolynomialFeatures 转换器将数组从 8 转换为形状 (4,2) −

from sklearn.preprocessing import PolynomialFeatures
import numpy as np
Y = np.arange(8).reshape(4, 2)
poly = PolynomialFeatures(degree=2)
poly.fit_transform(Y)

Output

array(
   [
      [ 1., 0., 1., 0., 0., 1.],
      [ 1., 2., 3., 4., 6., 9.],
      [ 1., 4., 5., 16., 20., 25.],
      [ 1., 6., 7., 36., 42., 49.]
   ]
)

Streamlining using Pipeline tools

上述预处理(即将输入数据矩阵转换为给定次数的新数据矩阵)可以用 Pipeline 工具简化,这些工具主要用于将多个估计器链接为一个。

Example

以下使用 Scikit-learn 的管道工具的 Python 脚本简化了预处理(将拟合到 3 阶多项式数据)。

#First, import the necessary packages.
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
import numpy as np

#Next, create an object of Pipeline tool
Stream_model = Pipeline([('poly', PolynomialFeatures(degree=3)), ('linear', LinearRegression(fit_intercept=False))])

#Provide the size of array and order of polynomial data to fit the model.
x = np.arange(5)
y = 3 - 2 * x + x ** 2 - x ** 3
Stream_model = model.fit(x[:, np.newaxis], y)

#Calculate the input polynomial coefficients.
Stream_model.named_steps['linear'].coef_

Output

array([ 3., -2., 1., -1.])

以上输出结果表明,在多项式特征上训练的线性模型能够恢复确切的输入多项式系数。

Scikit Learn - Stochastic Gradient Descent

在这里,我们将了解 Sklearn 中的一种优化算法,称为随机梯度下降 (SGD)。

随机梯度下降 (SGD) 是一种简单而有效的优化算法,用于查找最小化成本函数的函数参数/系数的值。换句话说,它用于在凸损失函数(如 SVM 和逻辑回归)下对线性分类器进行判别学习。它已成功应用于大型数据集,因为对系数的更新对每个训练实例执行,而不是在实例结束时执行。

SGD Classifier

随机梯度下降 (SGD) 分类器基本上实现了支持各种损失函数和分类惩罚的普通 SGD 学习例程。Scikit-learn 提供 ` SGDClassifier ` 模块来实现 SGD 分类。

Parameters

下表包含 ` SGDClassifier ` 模块使用的参数 -

Sr.No

Parameter & Description

1

` loss ` - str,默认值 = 'hinge’它表示在实现时要使用的损失函数。默认值为 'hinge',它将为我们提供线性 SVM。可使用的其他选项为 - ` log ` - 此损失将为我们提供逻辑回归,即概率分类器。` modified_huber ` - 一个平滑损失,它使容忍离群点与概率估计一起。` squared_hinge ` - 类似于“hinge”损失,但它是二次惩罚的。 ` perceptron ` - 如名称所示,它是一个线性损失,它被感知器算法使用。

2

` penalty ` - str,'none','l2','l1','elasticnet’它是模型中使用的正则化项。默认情况下,它是 L2。我们可以使用 L1 或 'elasticnet',但两者都可能使模型稀疏,因此无法用 L2 实现。

3

` alpha ` - float,默认值为 0.0001Alpha,乘以正则化项的常数,是调整参数,它决定了我们想要对模型进行多少惩罚。默认值为 0.0001。

4

` l1_ratio ` - float,默认值为 0.15这称为 ElasticNet 混合参数。它的范围是 0 < = l1_ratio < = 1。如果 l1_ratio = 1,则惩罚将是 L1 惩罚。如果 l1_ratio = 0,则惩罚将是 L2 惩罚。

5

` fit_intercept ` - 布尔值,默认值为 True此参数指定应将常数(偏差或截距)添加到决策函数中。如果没有截距将在计算中使用,并且假设数据已经居中,如果设置为 false。

6

` tol ` - 浮点数或无,可选,默认值为 1.e-3此参数表示迭代的停止标准。其默认值为 False,但如果设置为 None,则在 n_iter_no_change 个连续历元中达到 𝒍loss > *best_loss - tol 时,迭代将停止。

7

` shuffle ` - 布尔值,可选,默认值为 True此参数表示我们是否希望在每个历元后对我们的训练数据进行洗牌。

8

` verbose ` - 整数,默认值为 0它表示冗余级别。它的默认值为 0。

9

` epsilon ` - 浮点数,默认值为 0.1此参数指定不敏感区域的宽度。如果 loss = 'epsilon-insensitive',则当前预测与正确标签之间的任何差异小于阈值将被忽略。

10

max_iter − int, optional, default = 1000 As name suggest, it represents the maximum number of passes over the epochs i.e. training data.

11

warm_start − bool, optional, default = false With this parameter set to True, we can reuse the solution of the previous call to fit as initialization. If we choose default i.e. false, it will erase the previous solution.

12

random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options. int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random.

13

n_jobs − int or none, optional, Default = None It represents the number of CPUs to be used in OVA (One Versus All) computation, for multi-class problems. The default value is none which means 1.

14

learning_rate − string, optional, default = ‘optimal’ If learning rate is ‘constant’, eta = eta0; If learning rate is ‘optimal’, eta = 1.0/(alpha*(t+t0)), where t0 is chosen by Leon Bottou; If learning rate = ‘invscalling’, eta = eta0/pow(t, power_t). If learning rate = ‘adaptive’, eta = eta0.

15

eta0 − double, default = 0.0 It represents the initial learning rate for above mentioned learning rate options i.e. ‘constant’, ‘invscalling’, or ‘adaptive’.

16

power_t − idouble, default =0.5 It is the exponent for ‘incscalling’ learning rate.

17

early_stopping − bool, default = False This parameter represents the use of early stopping to terminate training when validation score is not improving. Its default value is false but when set to true, it automatically set aside a stratified fraction of training data as validation and stop training when validation score is not improving.

18

validation_fraction − float, default = 0.1 It is only used when early_stopping is true. It represents the proportion of training data to set asides as validation set for early termination of training data..

19

n_iter_no_change − int, default=5 It represents the number of iteration with no improvement should algorithm run before early stopping.

20

classs_weight − dict, {class_label: weight} or “balanced”, or None, optional This parameter represents the weights associated with classes. If not provided, the classes are supposed to have weight 1.

20

warm_start − bool, optional, default = false With this parameter set to True, we can reuse the solution of the previous call to fit as initialization. If we choose default i.e. false, it will erase the previous solution.

21

average − iBoolean or int, optional, default = false It represents the number of CPUs to be used in OVA (One Versus All) computation, for multi-class problems. The default value is none which means 1.

Attributes

Following table consist the attributes used by SGDClassifier module −

Sr.No

Attributes & Description

1

coef_ − array, shape (1, n_features) if n_classes==2, else (n_classes, n_features) This attribute provides the weight assigned to the features.

2

intercept_ − array, shape (1,) if n_classes==2, else (n_classes,) It represents the independent term in decision function.

3

n_iter_ − int It gives the number of iterations to reach the stopping criterion.

Implementation Example

Like other classifiers, Stochastic Gradient Descent (SGD) has to be fitted with following two arrays −

  1. An array X holding the training samples. It is of size [n_samples, n_features].

  2. An array Y holding the target values i.e. class labels for the training samples. It is of size [n_samples].

Example

使用 SGDClassifier 线性模型 − 的 Python 脚本如下:

import numpy as np
from sklearn import linear_model
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
Y = np.array([1, 1, 2, 2])
SGDClf = linear_model.SGDClassifier(max_iter = 1000, tol=1e-3,penalty = "elasticnet")
SGDClf.fit(X, Y)

Output

SGDClassifier(
   alpha = 0.0001, average = False, class_weight = None,
   early_stopping = False, epsilon = 0.1, eta0 = 0.0, fit_intercept = True,
   l1_ratio = 0.15, learning_rate = 'optimal', loss = 'hinge', max_iter = 1000,
   n_iter = None, n_iter_no_change = 5, n_jobs = None, penalty = 'elasticnet',
   power_t = 0.5, random_state = None, shuffle = True, tol = 0.001,
   validation_fraction = 0.1, verbose = 0, warm_start = False
)

Example

现在,在拟合模型后,可以预测新值如下所示:

SGDClf.predict([[2.,2.]])

Output

array([2])

Example

对于上述示例,我们可以借助以下 Python 脚本获取权重向量:

SGDClf.coef_

Output

array([[19.54811198, 9.77200712]])

Example

同样,我们可以借助以下 Python 脚本获取截距值:

SGDClf.intercept_

Output

array([10.])

Example

我们可以使用以下 Python 脚本中使用的 SGDClassifier.decision_function 来获取到超平面的有符号距离:

SGDClf.decision_function([[2., 2.]])

Output

array([68.6402382])

SGD Regressor

随机梯度下降 (SGD) 回归器基本执行一个朴素的 SGD 学习例程,支持各种损失函数和惩罚项来拟合线性回归模型。Scikit-learn 提供了 SGDRegressor 模块来实现 SGD 回归。

Parameters

SGDRegressor 所使用的参数与 SGDClassifier 模块中使用的参数几乎相同。不同之处在于“损失”参数。对于 SGDRegressor 模块的损失参数,正值如下:

  1. squared_loss − 它指的是普通的最小二乘拟合。

  2. huber: SGDRegressor − 通过从均方差损失切换到线性损失来纠正距离超过 epsilon 值的异常值。“huber” 的作用是修改“squared_loss”,以便算法较少关注纠正异常值。

  3. epsilon_insensitive − 实际上,它忽略了小于 epsilon 的误差。

  4. squared_epsilon_insensitive − 它与 epsilon_insensitive 相同。唯一的区别是它在线性损失超过 epsilon 容差时变成平方损失。

另一个区别是,名为“power_t”的参数的默认值是 0.25,而不是如 SGDClassifier 中的 0.5。此外,它没有“class_weight”和“n_jobs”参数。

Attributes

SGDRegressor 的属性也与 SGDClassifier 模块的属性相同。相反,它具有三个额外的属性,如下所示:

  1. average_coef_ − array, shape(n_features,)

顾名思义,它提供了分配给特征的平均权重。

  1. average_intercept_ − array, shape(1,)

顾名思义,它提供了平均截距项。

  1. t_ − int

它提供了在训练阶段执行的权重更新次数。

Note − 在将参数“average”启用为 True 后,属性 average_coef_ 和 average_intercept_ 将生效。

Implementation Example

使用 SGDRegressor 线性模型的 Python 脚本如下:

import numpy as np
from sklearn import linear_model
n_samples, n_features = 10, 5
rng = np.random.RandomState(0)
y = rng.randn(n_samples)
X = rng.randn(n_samples, n_features)
SGDReg =linear_model.SGDRegressor(
   max_iter = 1000,penalty = "elasticnet",loss = 'huber',tol = 1e-3, average = True
)
SGDReg.fit(X, y)

Output

SGDRegressor(
   alpha = 0.0001, average = True, early_stopping = False, epsilon = 0.1,
   eta0 = 0.01, fit_intercept = True, l1_ratio = 0.15,
   learning_rate = 'invscaling', loss = 'huber', max_iter = 1000,
   n_iter = None, n_iter_no_change = 5, penalty = 'elasticnet', power_t = 0.25,
   random_state = None, shuffle = True, tol = 0.001, validation_fraction = 0.1,
   verbose = 0, warm_start = False
)

Example

现在,一旦拟合,我们可以借助以下 Python 脚本获取权重向量:

SGDReg.coef_

Output

array([-0.00423314, 0.00362922, -0.00380136, 0.00585455, 0.00396787])

Example

同样,我们可以借助以下 Python 脚本获取截距值:

SGReg.intercept_

Output

SGReg.intercept_

Example

我们可以在训练阶段借助以下 Python 脚本获取权重更新次数−

SGDReg.t_

Output

61.0

Pros and Cons of SGD

ESG 的优点如下 −

  1. 随机梯度下降 (SGD) 非常高效。

  2. 由于可以对代码进行调整,因此非常容易实现。

SGD 的缺点如下 −

  1. 随机梯度下降 (SGD) 需要多个超参数,如正则化参数。

  2. 它对特征缩放很敏感。

Scikit Learn - Support Vector Machines

本章讨论了一种称为支持向量机 (SVM) 的机器学习方法。

Introduction

支持向量机 (SVM) 是强大而灵活的监督式机器学习方法,用于分类、回归和异常值检测。SVM 在高维空间中非常高效,通常用于分类问题。SVM 很流行且内存高效,因为它们在决策函数中使用训练点子集。

SVM 的主要目标是将数据集划分为多个类别,以便找到 maximum marginal hyperplane (MMH) ,这可以通过以下两步完成 −

  1. 支持向量机会首先迭代生成超平面,以最佳方式分隔类别。

  2. 之后,它将选择正确隔离类别的超平面。

SVM 中的一些重要概念如下 −

  1. Support Vectors − 它们可以定义为最接近超平面的数据点。支持向量有助于决定分隔线。

  2. Hyperplane − 分隔具有不同类别的对象的集合的决策平面或空间。

  3. Margin − 不同类别最接近数据点上的两条线之间的间隔称为间隔。

以下图表将让您深入了解这些 SVM 概念−

marginal hyperplane

Scikit-learn 中的 SVM 同时支持稀疏和密集样本向量作为输入。

Classification of SVM

Scikit-learn 提供了三个类,即 SVC, NuSVCLinearSVC ,它们可以执行多类分类。

SVC

C 支持向量分类,其实现基于 libsvm 。scikit-learn 使用的模块是 sklearn.svm.SVC 。此类根据一对一方案处理多类支持。

Parameters

下表包含 sklearn.svm.SVC 类使用的参数:

Sr.No

Parameter & Description

1

C - float,可选,默认 = 1.0 它是误差项的惩罚参数。

2

kernel - 字符串,可选,默认 = “rbf” 此参数指定算法中要使用的核类型。我们可以在以下任意一种中进行选择: ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ 。核心的默认值是 ‘rbf’

3

degree - int,可选,默认 = 3 它表示“poly”核函数的次数,并且所有其他核将忽略它。

4

gamma - {“scale”、“auto”} 或 float,它是内核“rbf”、“poly”和“sigmoid”的内核系数。

5

optinal default - =“scale” 如果你选择默认值,即 gamma = “scale”,则 SVC 要使用的 gamma 值为 1/(𝑛𝑓𝑒𝑎𝑡𝑢𝑟𝑒𝑠∗𝑋.𝑣𝑎𝑟())。另一方面,如果 gamma = ‘auto’,则使用 1/𝑛𝑓𝑒𝑎𝑡𝑢𝑟𝑒𝑠。

6

coef0 - float,可选,默认 = 0.0 核函数中的独立项,仅在“poly”和“sigmoid”中显着。

7

tol - float,可选,默认 = 1.e-3 此参数表示迭代的停止准则。

8

shrinking - 布尔值,可选,默认 = True 此参数表示我们是否要使用启发式收缩。其默认值为 false。

9

verbose - 布尔值,默认:false 它启用或禁用详细输出。其默认值是 false。

10

probability - 布尔值,可选,默认 = true 此参数启用或禁用概率估计。默认值是 false,但必须在调用拟合之前启用它。

11

max_iter - int,可选,默认 = -1 如名称所示,它表示求解器中迭代的最大次数。值 -1 意味着对迭代次数没有限制。

12

cache_size - float,可选 此参数将指定内核高速缓存的大小。值将以 MB(兆字节)表示。

13

random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options − int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random.

14

class_weight - {dict,'balanced'},可选 此参数将针对 SVC 将类 j 的参数 C 设置为 𝑐𝑙𝑎𝑠𝑠_𝑤𝑒𝑖𝑔ℎ𝑡[𝑗]∗𝐶。如果我们使用默认选项,则意味着所有类都被认为具有权重一。另一方面,如果你选择 class_weight:balanced ,则它将使用 y 的值来自动调整权重。

15

decision_function_shape - ovo','ovr',默认 = 'ovr' 此参数将决定算法是否将返回 ‘ovr’ (一对多)与其他所有分类器形状相同的判决函数或 libsvm 的原始 ovo (一对一)判决函数。

16

break_ties - 布尔值,可选,默认 = false True - 预测将根据决策函数的置信度值打破平局 False - 预测将在绑定的类中返回第一个类。

Attributes

下表包含 sklearn.svm.SVC 类使用的属性:

Sr.No

Attributes & Description

1

support_ - 类数组,形状 = [n_SV] 它返回支持向量的索引。

2

support_vectors_ - 与数组类似,形状 = [n_SV, n_features],返回支持向量。

3

n_support_ - 与数组类似,dtype=int32,形状 = [n_class],表示每个类的支持向量数量。

4

dual_coef_ - 数组,形状 = [n_class-1,n_SV],这是决策函数中支持向量的系数。

5

coef_ - 数组,形状 = [n_class * (n_class-1)/2, n_features],此属性仅可用于线性内核,提供分配给特征的权重。

6

intercept_ - 数组,形状 = [n_class * (n_class-1)/2],表示决策函数中的独立项(常数)。

7

fit_status_ - int,如果正确拟合,输出将为 0。如果拟合不正确,输出将为 1。

8

classes_ - 形状 = [n_classes] 的数组,给出类的标签。

Implementation Example

与其他分类器类似,SVC 还必须使用以下两个数组进行拟合 -

  1. 数组 X ,保存训练样本。其大小为 [n_samples, n_features]。

  2. 数组 Y ,保存目标值,即训练样本的类标签。其大小为 [n_samples]。

以下 Python 脚本使用 sklearn.svm.SVC 类 -

import numpy as np
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
y = np.array([1, 1, 2, 2])
from sklearn.svm import SVC
SVCClf = SVC(kernel = 'linear',gamma = 'scale', shrinking = False,)
SVCClf.fit(X, y)

Output

SVC(C = 1.0, cache_size = 200, class_weight = None, coef0 = 0.0,
   decision_function_shape = 'ovr', degree = 3, gamma = 'scale', kernel = 'linear',
   max_iter = -1, probability = False, random_state = None, shrinking = False,
   tol = 0.001, verbose = False)

Example

现在,一旦拟合,我们可以借助以下 Python 脚本获取权重向量:

SVCClf.coef_

Output

array([[0.5, 0.5]])

Example

同样,我们可以获得其他属性的值,如下所示 -

SVCClf.predict([[-0.5,-0.8]])

Output

array([1])

Example

SVCClf.n_support_

Output

array([1, 1])

Example

SVCClf.support_vectors_

Output

array(
   [
      [-1., -1.],
      [ 1., 1.]
   ]
)

Example

SVCClf.support_

Output

array([0, 2])

Example

SVCClf.intercept_

Output

array([-0.])

Example

SVCClf.fit_status_

Output

0

NuSVC

NuSVC 是核支持向量分类。它是 scikit-learn 提供的用于执行多类分类的另一个类。它类似于 SVC,但 NuSVC 接受略有不同的参数集。与 SVC 不同的参数如下 -

  1. nu - float,可选,默认值 = 0.5

它表示训练误差的上限和支持向量数量的下限。其值应在 (o,1] 区间内。

其他参数和属性与 SVC 相同。

Implementation Example

我们还可以使用 sklearn.svm.NuSVC 类实现相同的示例。

import numpy as np
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
y = np.array([1, 1, 2, 2])
from sklearn.svm import NuSVC
NuSVCClf = NuSVC(kernel = 'linear',gamma = 'scale', shrinking = False,)
NuSVCClf.fit(X, y)

Output

NuSVC(cache_size = 200, class_weight = None, coef0 = 0.0,
   decision_function_shape = 'ovr', degree = 3, gamma = 'scale', kernel = 'linear',
   max_iter = -1, nu = 0.5, probability = False, random_state = None,
   shrinking = False, tol = 0.001, verbose = False)

我们可以像使用 SVC 一样获得其余属性的输出。

LinearSVC

它就是线性支持向量分类。它类似于 SVC,其 kernel = ‘linear’。它们之间的区别在于 LinearSVC 根据 liblinear 实现,而 SVC 根据 libsvm 实现。这就是 LinearSVC 在惩罚和损失函数的选择方面具有更大灵活性的原因。它的可扩展性也更高,适用于大量样本。

如果我们讨论其参数和属性,那么它不支持 ‘kernel’ ,因为它假定为线性,并且还缺少 support_, support_vectors_, n_support_, fit_status_dual_coef_ 等属性。

不过,它支持 penaltyloss 参数,如下所示:

  1. penalty − string, L1 or L2(default = ‘L2’) 此参数用于指定罚则(正则化)中使用的范数(L1 或 L2)。

  2. loss − string, hinge, squared_hinge (default = squared_hinge) 它代表损失函数,其中“铰链”是标准 SVM 损失,“平方铰链”是铰链损失的平方。

Implementation Example

以下 Python 脚本使用 sklearn.svm.LinearSVC 类:

from sklearn.svm import LinearSVC
from sklearn.datasets import make_classification
X, y = make_classification(n_features = 4, random_state = 0)
LSVCClf = LinearSVC(dual = False, random_state = 0, penalty = 'l1',tol = 1e-5)
LSVCClf.fit(X, y)

Output

LinearSVC(C = 1.0, class_weight = None, dual = False, fit_intercept = True,
   intercept_scaling = 1, loss = 'squared_hinge', max_iter = 1000,
   multi_class = 'ovr', penalty = 'l1', random_state = 0, tol = 1e-05, verbose = 0)

Example

现在,在拟合模型后,可以预测新值如下所示:

LSVCClf.predict([[0,0,0,0]])

Output

[1]

Example

对于上述示例,我们可以借助以下 Python 脚本获取权重向量:

LSVCClf.coef_

Output

[[0. 0. 0.91214955 0.22630686]]

Example

同样,我们可以借助以下 Python 脚本获取截距值:

LSVCClf.intercept_

Output

[0.26860518]

Regression with SVM

如前所述,SVM 用于分类和回归问题。Scikit-learn 的支持向量分类 (SVC) 方法还可以扩展以解决回归问题。该扩展方法称为支持向量回归 (SVR)。

Basic similarity between SVM and SVR

由 SVC 创建的模型仅取决于训练数据的一个子集。为什么?因为用于构建模型的成本函数不关心位于裕度之外的训练数据点。

然而,由 SVR(支持向量回归)生成的模型也仅取决于训练数据的一个子集。为什么?因为用于构建模型的成本函数会忽略任何接近模型预测的训练数据点。

Scikit-learn 提供了三个类,即 SVR, NuSVR and LinearSVR ,作为 SVR 的三个不同实现。

SVR

它是基于 libsvm 实现的 Epsilon 支持向量回归。与 SVC 相反,该模型中有两个自由参数,即 ‘C’‘epsilon’

  1. epsilon − float,可选,默认 = 0.1

它表示 epsilon-SVR 模型中的 epsilon,并指定 epsilon 管,在该管中,损失函数中与实际值距离 epsilon 之内的预测点不会产生罚则。

其他参数和属性与我们在 SVC 中使用的类似。

Implementation Example

以下 Python 脚本使用 sklearn.svm.SVR 类:

from sklearn import svm
X = [[1, 1], [2, 2]]
y = [1, 2]
SVRReg = svm.SVR(kernel = ’linear’, gamma = ’auto’)
SVRReg.fit(X, y)

Output

SVR(C = 1.0, cache_size = 200, coef0 = 0.0, degree = 3, epsilon = 0.1, gamma = 'auto',
   kernel = 'linear', max_iter = -1, shrinking = True, tol = 0.001, verbose = False)

Example

现在,一旦拟合,我们可以借助以下 Python 脚本获取权重向量:

SVRReg.coef_

Output

array([[0.4, 0.4]])

Example

同样,我们可以获得其他属性的值,如下所示 -

SVRReg.predict([[1,1]])

Output

array([1.1])

同样,我们还可以获得其他属性的值。

NuSVR

NuSVR 是 Nu 支持向量回归。它类似于 NuSVC,但 NuSVR 使用参数 nu 来控制支持向量的数量。此外,与 NuSVC 不同(其中 nu 替换了 C 参数),这里它替换了 epsilon

Implementation Example

以下 Python 脚本使用 sklearn.svm.SVR 类:

from sklearn.svm import NuSVR
import numpy as np
n_samples, n_features = 20, 15
np.random.seed(0)
y = np.random.randn(n_samples)
X = np.random.randn(n_samples, n_features)
NuSVRReg = NuSVR(kernel = 'linear', gamma = 'auto',C = 1.0, nu = 0.1)^M
NuSVRReg.fit(X, y)

Output

NuSVR(C = 1.0, cache_size = 200, coef0 = 0.0, degree = 3, gamma = 'auto',
   kernel = 'linear', max_iter = -1, nu = 0.1, shrinking = True, tol = 0.001,
   verbose = False)

Example

现在,一旦拟合,我们可以借助以下 Python 脚本获取权重向量:

NuSVRReg.coef_

Output

array(
   [
      [-0.14904483, 0.04596145, 0.22605216, -0.08125403, 0.06564533,
      0.01104285, 0.04068767, 0.2918337 , -0.13473211, 0.36006765,
      -0.2185713 , -0.31836476, -0.03048429, 0.16102126, -0.29317051]
   ]
)

同样,我们还可以获得其他属性的值。

LinearSVR

它是线性支持向量回归。它类似于 SVR(kernel =“linear”)。它们之间的区别在于, LinearSVR 是根据 liblinear 实现的,而 SVC 是根据 libsvm 实现的。这就是为什么 LinearSVR 在罚则和损失函数的选择上更灵活的原因。它也能更好地扩展到大量样本。

如果我们讨论其参数和属性,那么它不支持 ‘kernel’ ,因为它假定为线性,并且还缺少 support_, support_vectors_, n_support_, fit_status_dual_coef_ 等属性。

不过,它支持以下“损失”参数:

  1. loss - 字符串,可选,默认 = ‘epsilon_insensitive’

它表示 epsilon_insensitive 损失为 L1 损失且平方 epsilon_insensitive 损失为 L2 损失的损失函数。

Implementation Example

以下 Python 脚本使用 sklearn.svm.LinearSVR 类 -

from sklearn.svm import LinearSVR
from sklearn.datasets import make_regression
X, y = make_regression(n_features = 4, random_state = 0)
LSVRReg = LinearSVR(dual = False, random_state = 0,
loss = 'squared_epsilon_insensitive',tol = 1e-5)
LSVRReg.fit(X, y)

Output

LinearSVR(
   C=1.0, dual=False, epsilon=0.0, fit_intercept=True,
   intercept_scaling=1.0, loss='squared_epsilon_insensitive',
   max_iter=1000, random_state=0, tol=1e-05, verbose=0
)

Example

现在,在拟合模型后,可以预测新值如下所示:

LSRReg.predict([[0,0,0,0]])

Output

array([-0.01041416])

Example

对于上述示例,我们可以借助以下 Python 脚本获取权重向量:

LSRReg.coef_

Output

array([20.47354746, 34.08619401, 67.23189022, 87.47017787])

Example

同样,我们可以借助以下 Python 脚本获取截距值:

LSRReg.intercept_

Output

array([-0.01041416])

Scikit Learn - Anomaly Detection

在这里,我们将学习 Sklearn 中的异常检测以及如何在数据点识别中使用它。

异常检测是一种用于识别数据集中的数据点与其他数据不符的技术。它在业务中有许多应用,例如欺诈检测、入侵检测、系统运行状况监控、监测和预测性维护。异常值(也被称为离群点)可分为以下三类:

  1. Point anomalies − 它发生在单个数据实例被视为与其他数据相关的异常情况。

  2. Contextual anomalies − 这种异常是特定于上下文的。如果数据实例在特定上下文中异常,则会出现这种情况。

  3. Collective anomalies − 它发生在相关数据实例的集合与整个数据集(而不是单个值)相关的异常情况。

Methods

可以使用 outlier detectionnovelty detection 这两种方法进行异常检测。有必要了解它们之间的区别。

Outlier detection

The training data contains outliers that are far from the rest of the data. Such outliers are defined as observations. That’s the reason, outlier detection estimators always try to fit the region having most concentrated training data while ignoring the deviant observations. It is also known as unsupervised anomaly detection.

Novelty detection

It is concerned with detecting an unobserved pattern in new observations which is not included in training data. Here, the training data is not polluted by the outliers. It is also known as semi-supervised anomaly detection.

There are set of ML tools, provided by scikit-learn, which can be used for both outlier detection as well novelty detection. These tools first implementing object learning from the data in an unsupervised by using fit () method as follows −

estimator.fit(X_train)

Now, the new observations would be sorted as inliers (labeled 1) or outliers (labeled -1) by using predict() method as follows −

estimator.fit(X_test)

The estimator will first compute the raw scoring function and then predict method will make use of threshold on that raw scoring function. We can access this raw scoring function with the help of score_sample method and can control the threshold by contamination parameter.

We can also define decision_function method that defines outliers as negative value and inliers as non-negative value.

estimator.decision_function(X_test)

Sklearn algorithms for Outlier Detection

Let us begin by understanding what an elliptic envelop is.

Fitting an elliptic envelop

This algorithm assume that regular data comes from a known distribution such as Gaussian distribution. For outlier detection, Scikit-learn provides an object named covariance.EllipticEnvelop.

This object fits a robust covariance estimate to the data, and thus, fits an ellipse to the central data points. It ignores the points outside the central mode.

Parameters

Following table consist the parameters used by sklearn. covariance.EllipticEnvelop method −

Sr.No

Parameter & Description

1

store_precision − Boolean, optional, default = True We can specify it if the estimated precision is stored.

2

assume_centered − Boolean, optional, default = False If we set it False, it will compute the robust location and covariance directly with the help of FastMCD algorithm. On the other hand, if set True, it will compute the support of robust location and covarian.

3

support_fraction − float in (0., 1.), optional, default = None This parameter tells the method that how much proportion of points to be included in the support of the raw MCD estimates.

4

contamination − float in (0., 1.), optional, default = 0.1 It provides the proportion of the outliers in the data set.

5

random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options − int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random.

Attributes

Following table consist the attributes used by sklearn. covariance.EllipticEnvelop method −

Sr.No

Attributes & Description

1

support_ − array-like, shape(n_samples,) It represents the mask of the observations used to compute robust estimates of location and shape.

2

location_ − array-like, shape (n_features) It returns the estimated robust location.

3

covariance_ − array-like, shape (n_features, n_features) It returns the estimated robust covariance matrix.

4

precision_ – 类似数组,形状 (n_features, n_features)返回估计的 pseudo 逆矩阵。

5

offset_ – float用于基于原始分数定义决策函数。

Implementation Example

import numpy as np^M
from sklearn.covariance import EllipticEnvelope^M
true_cov = np.array([[.5, .6],[.6, .4]])
X = np.random.RandomState(0).multivariate_normal(mean = [0, 0], cov=true_cov,size=500)
cov = EllipticEnvelope(random_state = 0).fit(X)^M
# Now we can use predict method. It will return 1 for an inlier and -1 for an outlier.
cov.predict([[0, 0],[2, 2]])

Output

array([ 1, -1])

Isolation Forest

对于高维数据集,一种用于极值检测的高效方法是使用随机森林。scikit-learn 提供了通过随机选择一个特征来隔离观测的 ensemble.IsolationForest 方法。之后,它会随机选择一个介于所选特征的最大值和最小值之间的值。

此处,为了隔离样本所需的拆分次数相当于从根节点到终止节点的路径长度。

Parameters

以下表格包含 sklearn. ensemble.IsolationForest 方法使用到的参数−

Sr.No

Parameter & Description

1

n_estimators – int,可选,默认= 100它表示集成中的基本估计器的数量。

2

max_samples – int 或 float,可选,默认= “auto”它表示从 X 中提取的样本数量,用于训练每个基本估计器。如果我们选择 int 作为其值,则将提取 max_samples 个样本。如果我们选择 float 作为其值,则将提取 max_samples ∗ 𝑋.shape[0] 个样本。如果我们选择 auto 作为其值,则将提取 max_samples = min(256,n_samples)。

3

support_fraction − float in (0., 1.), optional, default = None This parameter tells the method that how much proportion of points to be included in the support of the raw MCD estimates.

4

contamination – auto 或 float,可选,默认= auto它提供了数据集中极值所占的比例。如果将它设置为默认值(即 auto),将按照原始论文中的方式确定阈值。如果设置为 float,则污染的范围将介于 [0,0.5] 内。

5

random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options − int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random.

6

max_features – int 或 float,可选(默认= 1.0)它表示从 X 中提取的特征数量,用于训练每个基本估计器。如果我们选择 int 作为其值,则将提取 max_features 个特征。如果我们选择 float 作为其值,则将提取 max_features * X.shape[𝟏] 个样本。

7

bootstrap – 布尔值,可选(默认= False)其默认选项为 False,这意味着采样将无放回地执行。另一方面,如果设置为 True,这意味着将基于通过放回抽样得到的训练数据的随机子集对各个树进行拟合。

8

n_jobs – int 或 None,可选(默认= None)它表示在 fit()predict() 方法中并行运行的作业数。

9

verbose – int,可选(默认= 0)此参数控制树构建过程的详细程度。

10

warm_start – 布尔值,可选(默认= False)如果 warm_start = true,我们可以重复使用以前的调用解决方案进行拟合,并且可以向集成中添加更多估计器。但是如果设置为 false,我们需要拟合一个全新的森林。

Attributes

以下表格包含 sklearn. ensemble.IsolationForest 方法使用到的属性−

Sr.No

Attributes & Description

1

estimators_ – DecisionTreeClassifier 的列表提供所有拟合的子估计器的集合。

2

max_samples_ – 整数它提供了实际使用的样本数。

3

offset_ – float用于基于原始分数定义决策函数。

Implementation Example

以下 Python 脚本将使用 sklearn. ensemble.IsolationForest 方法对给定数据拟合 10 棵树

from sklearn.ensemble import IsolationForest
import numpy as np
X = np.array([[-1, -2], [-3, -3], [-3, -4], [0, 0], [-50, 60]])
OUTDClf = IsolationForest(n_estimators = 10)
OUTDclf.fit(X)

Output

IsolationForest(
   behaviour = 'old', bootstrap = False, contamination='legacy',
   max_features = 1.0, max_samples = 'auto', n_estimators = 10, n_jobs=None,
   random_state = None, verbose = 0
)

Local Outlier Factor

局部离群因子 (LOF) 算法是另一种用于在高维度数据上执行离群检测的高效算法。scikit-learn 提供了 neighbors.LocalOutlierFactor 方法,它计算一个称为局部离群因子的分数,反映观测异常程度。此算法的主要逻辑是检测密度远低于其邻居的样本。这就是为什么它测量给定数据点相对于其邻居的局部密度偏差的原因。

Parameters

以下表格包含 sklearn. neighbors.LocalOutlierFactor 方法使用到的参数

Sr.No

Parameter & Description

1

n_neighbors - 整型,可选,默认值为 20,它表示 kneighbors 查询中默认使用的邻居数量。如果使用 . 则会使用所有样本。

2

algorithm - 可选,用于计算最近邻居的算法。如果选择 ball_tree,它将使用 BallTree 算法。如果选择 kd_tree,它将使用 KDTree 算法。如果选择 brute,它将使用暴力搜索算法。如果选择 auto,它将根据传递给 fit() 方法的值决定最合适的算法。

3

leaf_size - 整型,可选,默认值为 30,此参数的值可能会影响构建和查询的速度。它还影响存储树所需的内存。此参数传递给 BallTree 或 KdTree 算法。

4

contamination – auto 或 float,可选,默认= auto它提供了数据集中极值所占的比例。如果将它设置为默认值(即 auto),将按照原始论文中的方式确定阈值。如果设置为 float,则污染的范围将介于 [0,0.5] 内。

5

metric - 字符串或可调用,默认值,它表示用于距离计算的度量。

6

P - 整型,可选(默认值为 2),它是 Minkowski 度量的参数。P=1 等效于使用曼哈顿距离,即 L1,而 P=2 等效于使用欧几里得距离,即 L2。

7

novelty - 布尔值(默认值为 False),默认情况下,LOF 算法用于异常检测,但如果我们设置 novelty = true,则可以将其用于新颖性检测。

8

n_jobs - 整型或无,可选(默认值为无),它表示 fit() 和 predict() 方法并行运行的作业数。

Attributes

下表包含 sklearn.neighbors.LocalOutlierFactor 方法使用的属性:

Sr.No

Attributes & Description

1

negative_outlier_factor_ - numpy 数组,形状(n_samples,),提供训练样本的相反 LOF。

2

n_neighbors_ - 整型,提供用于邻居查询的实际邻居数。

3

offset_ - 浮点数,用于从原始分数中定义二进制标签。

Implementation Example

下面给出的 Python 脚本将使用 sklearn.neighbors.LocalOutlierFactor 方法从与我们的数据集对应的任何数组构建 NeighborsClassifier 类。

from sklearn.neighbors import NearestNeighbors
samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
LOFneigh = NearestNeighbors(n_neighbors = 1, algorithm = "ball_tree",p=1)
LOFneigh.fit(samples)

Output

NearestNeighbors(
   algorithm = 'ball_tree', leaf_size = 30, metric='minkowski',
   metric_params = None, n_jobs = None, n_neighbors = 1, p = 1, radius = 1.0
)

Example

现在,我们可以通过使用以下 Python 脚本,询问这个已构建的分类器离 [0.5, 1., 1.5] 最近的点。

print(neigh.kneighbors([[.5, 1., 1.5]])

Output

(array([[1.7]]), array([[1]], dtype = int64))

One-Class SVM

Schölkopf 等人提出的单类 SVM 是无监督异常检测。它在高维数据中也非常有效,并估计高维分布的支持。它在 Sklearn.svm.OneClassSVM 对象的 Support Vector Machines 模块中实现。为了定义一个边界,它需要一个核(最常用的 RBF)和一个标量参数。

为了更好地理解,让我们用 svm.OneClassSVM 对象拟合我们的数据:

Example

from sklearn.svm import OneClassSVM
X = [[0], [0.89], [0.90], [0.91], [1]]
OSVMclf = OneClassSVM(gamma = 'scale').fit(X)

现在,我们可以为输入数据获取 score_samples,如下所示:

OSVMclf.score_samples(X)

Output

array([1.12218594, 1.58645126, 1.58673086, 1.58645127, 1.55713767])

Scikit Learn - K-Nearest Neighbors (KNN)

本章将帮助您理解 Sklearn 中的最近邻方法。

基于邻居的学习方法有两种类型,即 supervisedunsupervised. 。基于受监督邻居的学习既能用于分类,也能用于回归预测问题,但主要用于工业中的分类预测问题。

基于邻居的学习方法没有专门的训练阶段,会在分类时使用所有数据进行训练。它也不会对基础数据做出任何假设。这就是为什么它们本质上是惰性和非参数化的原因。

最近邻方法背后的主要原则是 −

  1. 找到与新数据点距离最近的一组预定义训练样本

  2. 根据这些训练样本预测标签。

此处,样本数量可以是用户定义的常数,如 K-最近邻学习,或根据点局部密度而变化,如基于半径的邻近学习。

sklearn.neighbors Module

Scikit-learn 拥有 sklearn.neighbors 模块,可为无监督和有监督的基于邻居的学习方法提供功能。对于输入,该模块中的类可以处理 NumPy 数组或 scipy.sparse 矩阵。

Types of algorithms

可在基于邻居方法的实现中使用的不同类型的算法如下 −

Brute Force

对数据集中所有点对之间的距离进行蛮力计算提供了一种最简单的邻近搜索实现。在数学上,对于 D 维中的 N 个样本,蛮力方法的规模是 0[DN2]

对于小数据样本,此算法可能非常有用,但随着样本数量的增长,它将变得不可行。可以使用关键字 algorithm=’brute’ 来启用蛮力邻近搜索。

K-D Tree

为了解决蛮力方法的计算效率低的问题而发明的一棵基于树的数据结构是 KD 树数据结构。基本上,KD 树是一种称为 K 维树的二叉树结构。它通过将参数空间沿数据轴递归地划分为嵌套正交区域,并填充数据点来划分数据轴。

Advantages

以下是一些 K-D 树算法的优点 −

Construction is fast − 由于划分仅沿着数据轴执行,因此 K-D 树的构建非常快。

Less distance computations − 该算法只需要很少的距离计算即可确定查询点的最近邻。它只需要 𝑶[𝐥𝐨𝐠 (𝑵)] 距离计算。

Disadvantages

Fast for only low-dimensional neighbor searches − 它对于低维(D < 20)邻域搜索非常快,但随着 D 的增长,它变得效率低下。由于划分仅沿着数据轴执行,因此

可以通过编写关键字 algorithm=’kd_tree’ 启用 K-D 树邻近搜索。

Ball Tree

众所周知,KD 树在高维度中效率低下,因此,为了解决 KD 树的这种低效性,开发了 Ball 树数据结构。在数学上,它以一种递归的方式将数据划分为由质心 C 和半径 r 定义的节点,使得节点中的每个点都位于由质心 C 和半径 r 定义的超球体中。它使用三角不等式(如下所示),该不等式减少了邻近搜索的候选点数量

Advantages

以下是 Ball Tree 算法的一些优点 −

Efficient on highly structured data − 由于 ball 树以一系列嵌套超球体的形式对数据进行分区,因此它对高度结构化的数据来说效率很高。

Out-performs KD-tree − 球树在高纬度中优于 KD 树,因为它具有球树节点球形的几何形状。

Disadvantages

Costly − 将数据划分为一系列嵌套的超球,使其构建非常费时费力。

通过编写关键词 algorithm=’ball_tree’ 可以启用球树邻居搜索。

Choosing Nearest Neighbors Algorithm

选择给定数据集的最佳算法取决于以下因素 −

Number of samples (N) and Dimensionality (D)

在选择最近邻算法时,这些是最重要的因素。这是因为以下原因 −

  1. 蛮力算法的查询时间以 O[DN] 速度增长。

  2. 球树算法的查询时间以 O[D log(N)] 速度增长。

  3. KD 树算法的查询时间随 D 的变化方式非常奇怪,很难描述。当 D < 20 时,开销为 O[D log(N)],并且此算法非常高效。另一方面,当 D > 20 时效率不高,因为开销增加到接近 O[DN]。

Data Structure

另一个影响这些算法性能的因素是数据的内在维度或稀疏性。这是因为球树和 KD 树算法的查询时间会受到它的极大影响。而蛮力算法的查询时间不受数据结构改变的影响。通常,球树和 KD 树算法在稀疏数据和较小的内在维度上实施时会产生更快的查询时间。

Number of Neighbors (k)

查询点请求的邻居数 (k) 会影响球树和 KD 树算法的查询时间。随着邻居数 (k) 的增加,它们的查询时间会变慢。而蛮力算法的查询时间将不受 k 值的影响。

Number of query points

由于它们需要构建阶段,因此如果查询点数量很大,则 KD 树和球树算法都会很有效。另一方面,如果查询点数量较少,则蛮力算法的性能会优于 KD 树和球树算法。

Scikit Learn - KNN Learning

k-NN(k-近邻),最简单的机器学习算法之一,本质上是非参数化和惰性的。非参数化意味着对底层数据分布没有假设,即,模型结构由数据集确定。惰性或基于实例的学习意味着,出于模型生成目的,它不需要任何训练数据点,而整个训练数据都用于测试阶段。

k-NN 算法包含以下两个步骤:

Step 1

在此步骤中,它计算并存储训练集中每个样本的 k 个最近近邻。

Step 2

在此步骤中,对于未标记的样本,它从数据集中检索 k 个最近近邻。然后,在这些 k 个最近近邻中,它通过投票(获得多数票的类别获胜)来预测类别。

实现了 k-近邻算法的模块 sklearn.neighbors 提供了基于 unsupervisedsupervised 近邻的学习方法的功能。

无监督最近近邻实现了不同的算法(BallTree、KDTree 或 Brute Force)来查找每个样本的最近近邻。此无监督版本基本上只是步骤 1,如上所述,并且是需要邻域搜索的许多算法(KNN 和 K-means 是最著名的算法)的基础。简单来说,它是非监督学习器,用于实现邻域搜索。

另一方面,基于监督最近近邻的学习用于分类和回归。

Unsupervised KNN Learning

如前所述,存在许多算法(如 KNN 和 K-Means 算法)需要最近邻邻搜索。这就是为什么 Scikit-learn 决定将其邻域搜索部分实现为其自己的“学习器”的原因。将邻域搜索作为独立学习器的原因是,计算用于找到最近邻的 all pair-wise 距离明显不是非常有效的。让我们看看 Sklearn 用于实现无监督最近邻学习的模块以及示例。

Scikit-learn module

sklearn.neighbors.NearestNeighbors 是用于实现无监督最近邻学习的模块。它使用名为 BallTree、KDTree 或 Brute Force 的特定最近邻算法。换言之,它作为这三个算法的统一接口。

Parameters

下表包含 NearestNeighbors 模块所使用的参数:

Sr.No

Parameter & Description

1

n_neighbors - int,可选要获取的邻域数。默认值为 5。

2

radius - float,可选它限制要返回的邻域的距离。默认值为 1.0。

3

algorithm - {‘auto’,‘ball_tree’,‘kd_tree’,‘brute’},可选此参数将用于计算最近邻的算法(BallTree、KDTree 或 Brute-force)。如果你提供“auto”,它将尝试根据传递给 fit 方法的值来决定最合适的算法。

4

leaf_size - int,可选它会影响构建和查询的速度以及存储树所需的内存。它被传递给 BallTree 或 KDTree。尽管最优值取决于问题的性质,但其默认值为 30。

5

metric - 字符串或可调用函数这是用于计算点之间距离的度量。我们可以将它传递为字符串或可调用函数。在可调用函数的情况下,会对每一对行调用该度量,并记录结果值。这比将度量名称作为字符串传递效率低。我们可以从 scikit-learn 或 scipy.spatial.distance 中选择度量,有效值如下:Scikit-learn - [‘cosine’,‘manhattan’,‘Euclidean’,‘l1’,‘l2’,‘cityblock’]Scipy.spatial.distance - [‘braycurtis’,‘canberra’,‘chebyshev’,‘dice’,‘hamming’,‘jaccard’,‘correlation’,‘kulsinski’,‘mahalanobis’,‘minkowski’,‘rogerstanimoto’,‘russellrao’,‘sokalmicheme’,’sokalsneath’,‘seuclidean’,‘sqeuclidean’,‘yule’]。默认度量为“Minkowski”。

6

P - 整数,可选这是 Minkowski 度量的参数。默认值为 2,等效于使用 Euclidean_distance(l2)。

7

metric_params - 字典,可选这是度量函数的附加关键字参数。默认值为 None。

8

N_jobs - 整数或 None,可选它表示用于邻居搜索的并行作业数。默认值为 None。

Implementation Example

下面的示例将使用 sklearn.neighbors.NearestNeighbors 模块在两组数据之间找出最近邻点。

首先,我们需要导入所需的模块和包−

from sklearn.neighbors import NearestNeighbors
import numpy as np

现在,在导入包之后,定义我们希望在其中查找最近邻点的两个数据集 −

Input_data = np.array([[-1, 1], [-2, 2], [-3, 3], [1, 2], [2, 3], [3, 4],[4, 5]])

接下来,按如下所示应用非监督式学习算法 −

nrst_neigh = NearestNeighbors(n_neighbors = 3, algorithm = 'ball_tree')

然后,使用输入数据集拟合模型。

nrst_neigh.fit(Input_data)

现在,找出数据集的 K-近邻点。它将返回每个点的邻居的索引和距离。

distances, indices = nbrs.kneighbors(Input_data)
indices

Output

array(
   [
      [0, 1, 3],
      [1, 2, 0],
      [2, 1, 0],
      [3, 4, 0],
      [4, 5, 3],
      [5, 6, 4],
      [6, 5, 4]
   ], dtype = int64
)
distances

Output

array(
   [
      [0. , 1.41421356, 2.23606798],
      [0. , 1.41421356, 1.41421356],
      [0. , 1.41421356, 2.82842712],
      [0. , 1.41421356, 2.23606798],
      [0. , 1.41421356, 1.41421356],
      [0. , 1.41421356, 1.41421356],
      [0. , 1.41421356, 2.82842712]
   ]
)

上面的输出显示每个点的最近邻点都是该点本身,即为零。这是因为查询集与训练集匹配。

Example

我们还可以通过生成稀疏图来显示相邻点之间的连接,如下所示 −

nrst_neigh.kneighbors_graph(Input_data).toarray()

Output

array(
   [
      [1., 1., 0., 1., 0., 0., 0.],
      [1., 1., 1., 0., 0., 0., 0.],
      [1., 1., 1., 0., 0., 0., 0.],
      [1., 0., 0., 1., 1., 0., 0.],
      [0., 0., 0., 1., 1., 1., 0.],
      [0., 0., 0., 0., 1., 1., 1.],
      [0., 0., 0., 0., 1., 1., 1.]
   ]
)

一旦我们拟合了非监督式 NearestNeighbors 模型,数据将存储在一个基于为参数 ‘algorithm’ 设置的值的数据结构中。然后,我们可以在需要邻居搜索的模型中使用此非监督式学习器的 kneighbors

Complete working/executable program

from sklearn.neighbors import NearestNeighbors
import numpy as np
Input_data = np.array([[-1, 1], [-2, 2], [-3, 3], [1, 2], [2, 3], [3, 4],[4, 5]])
nrst_neigh = NearestNeighbors(n_neighbors = 3, algorithm='ball_tree')
nrst_neigh.fit(Input_data)
distances, indices = nbrs.kneighbors(Input_data)
indices
distances
nrst_neigh.kneighbors_graph(Input_data).toarray()

Supervised KNN Learning

基于监督邻域的学习用于以下方面 −

  1. 带离散标签数据的分类

  2. 带连续标签数据的回归。

Nearest Neighbor Classifier

我们借助以下两个特征来理解基于邻居的分类 −

  1. 它从每个点的最近邻点的简单多数投票中计算得出。

  2. 它只是存储训练数据实例,这就是它是一种非泛化学习类型的原因。

Scikit-learn modules

以下是 scikit-learn 使用的两种不同类型的最近邻分类器——

S.No.

Classifiers & Description

1.

KNeighborsClassifier 此分类器名称中的 K 表示 k 个最近邻,其中 k 是用户指定的整数值。因此,顾名思义,此分类器基于 k 个最近邻实现学习。k 的值的选取取决于数据。

2.

RadiusNeighborsClassifier 此分类器名称中的 Radius 表示指定半径 r 内的最近邻域,其中 r 是用户指定的浮点值。因此,顾名思义,此分类器基于每个训练点固定半径 r 内的邻居数实现学习。

Nearest Neighbor Regressor

它用于数据标签本质上是连续的情况下。分配的数据标签基于其最近邻的标签均值计算。

以下是 scikit-learn 使用的两种不同类型的最近邻回归器——

KNeighborsRegressor

此回归器名称中的 K 表示 k 个最近邻,其中 kinteger value 指定的用户。因此,顾名思义,此回归器基于 k 个最近邻实现学习。k 的值的选取取决于数据。让我们借助一个实现示例进一步理解这一点。

以下是 scikit-learn 使用的两种不同类型的最近邻回归器——

Implementation Example

在此示例中,我们将使用 scikit-learn KNeighborsRegressor 在数据集上(即 Iris Flower 数据集)实现 KNN。

首先,按如下方式导入鸢尾花数据集——

from sklearn.datasets import load_iris
iris = load_iris()

现在,我们需要将数据分成训练数据和测试数据。我们将使用 Sklearn train_test_split 函数将数据分成 70(训练数据)和 20(测试数据)的比率——

X = iris.data[:, :4]
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)

接下来,我们将借助 Sklearn 预处理模块进行数据缩放,如下所示——

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

接下来,从 Sklearn 导入 KNeighborsRegressor 类,并按如下方式提供邻居值。

Example

import numpy as np
from sklearn.neighbors import KNeighborsRegressor
knnr = KNeighborsRegressor(n_neighbors = 8)
knnr.fit(X_train, y_train)

Output

KNeighborsRegressor(
   algorithm = 'auto', leaf_size = 30, metric = 'minkowski',
   metric_params = None, n_jobs = None, n_neighbors = 8, p = 2,
   weights = 'uniform'
)

Example

现在,我们按如下方式查找 MSE(均方误差)——

print ("The MSE is:",format(np.power(y-knnr.predict(X),4).mean()))

Output

The MSE is: 4.4333349609375

Example

现在,使用它按如下方式预测值——

X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
from sklearn.neighbors import KNeighborsRegressor
knnr = KNeighborsRegressor(n_neighbors = 3)
knnr.fit(X, y)
print(knnr.predict([[2.5]]))

Output

[0.66666667]

Complete working/executable program

from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data[:, :4]
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

import numpy as np
from sklearn.neighbors import KNeighborsRegressor
knnr = KNeighborsRegressor(n_neighbors=8)
knnr.fit(X_train, y_train)

print ("The MSE is:",format(np.power(y-knnr.predict(X),4).mean()))

X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
from sklearn.neighbors import KNeighborsRegressor
knnr = KNeighborsRegressor(n_neighbors=3)
knnr.fit(X, y)
print(knnr.predict([[2.5]]))

RadiusNeighborsRegressor

此回归器名称中的 Radius 表示指定半径 r 内的最近邻域,其中 r 是用户指定的浮点值。因此,顾名思义,此回归器基于每个训练点固定半径 r 内的邻居数实现学习。让我们借助一个实现示例进一步理解这一点——

Implementation Example

在此示例中,我们将使用 scikit-learn RadiusNeighborsRegressor 在数据集上(即 Iris Flower 数据集)实现 KNN。

首先,按如下方式导入鸢尾花数据集——

from sklearn.datasets import load_iris
iris = load_iris()

现在,我们需要将数据分成训练数据和测试数据。我们将使用 Sklearn train_test_split 函数将数据分成 70(训练数据)和 20(测试数据)的比率——

X = iris.data[:, :4]
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)

接下来,我们将借助 Sklearn 预处理模块进行数据缩放,如下所示——

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

接下来,从 Sklearn 导入 RadiusneighborsRegressor 类,并按如下方式提供半径值——

import numpy as np
from sklearn.neighbors import RadiusNeighborsRegressor
knnr_r = RadiusNeighborsRegressor(radius=1)
knnr_r.fit(X_train, y_train)

Example

现在,我们按如下方式查找 MSE(均方误差)——

print ("The MSE is:",format(np.power(y-knnr_r.predict(X),4).mean()))

Output

The MSE is: The MSE is: 5.666666666666667

Example

现在,使用它按如下方式预测值——

X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
from sklearn.neighbors import RadiusNeighborsRegressor
knnr_r = RadiusNeighborsRegressor(radius=1)
knnr_r.fit(X, y)
print(knnr_r.predict([[2.5]]))

Output

[1.]

Complete working/executable program

from sklearn.datasets import load_iris

iris = load_iris()

X = iris.data[:, :4]
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
import numpy as np
from sklearn.neighbors import RadiusNeighborsRegressor
knnr_r = RadiusNeighborsRegressor(radius = 1)
knnr_r.fit(X_train, y_train)
print ("The MSE is:",format(np.power(y-knnr_r.predict(X),4).mean()))
X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
from sklearn.neighbors import RadiusNeighborsRegressor
knnr_r = RadiusNeighborsRegressor(radius = 1)
knnr_r.fit(X, y)
print(knnr_r.predict([[2.5]]))

Scikit Learn - Classification with Naïve Bayes

朴素贝叶斯方法是一组基于应用贝叶斯定理的监督学习算法,其有一个强假设,即所有预测变量彼此独立,即一个类别中的特征的存在与同一类别中任何其他特征的存在无关。这是一个朴素的假设,这就是为什么这些方法被称为朴素贝叶斯方法。

贝叶斯定理陈述了以下关系,以找到类的后验概率,即标签和某些观察到的特征的概率,$P\left(\begin{array}{c} Y\arrowvert features\end{array}\right)$。

此处,$P\left(\begin{array}{c} Y\arrowvert features\end{array}\right)$ 是类的后验概率。

$P\left(\begin{array}{c} Y\end{array}\right)$ 是类的先验概率。

$P\left(\begin{array}{c} features\arrowvert Y\end{array}\right)$ 是给定类的预测变量的概率即似然度。

$P\left(\begin{array}{c} features\end{array}\right)$ 是预测变量的先验概率。

Scikit-learn 提供了不同的朴素贝叶斯分类器模型,即高斯、多项式、补集和伯努利。所有这些模型主要根据它们对 𝑷$P\left(\begin{array}{c} features\arrowvert Y\end{array}\right)$,即给定类的预测变量的概率的分布的假设而有所不同。

Sr.No

Model & Description

1

Gaussian Naïve Bayes 高斯朴素贝叶斯分类器假设每个标签的数据都来自一个简单的正态分布。

2

Multinomial Naïve Bayes 它假设特征是从一个简单多项式分布中抽取的。

3

Bernoulli Naïve Bayes 此模型中的假设是特征本质上是二进制(0 和 1)。伯努利朴素贝叶斯分类的一种应用是使用“词袋”模型进行文本分类

4

Complement Naïve Bayes 它旨在纠正多项式贝叶斯分类器做出的严格假设。这种 NB 分类器适用于不平衡数据集

Building Naïve Bayes Classifier

我们还可以在 Scikit-learn 数据集上应用朴素贝叶斯分类器。在下面的示例中,我们应用 GaussianNB 并拟合 Scikit-leran 的 breast_cancer 数据集。

Example

Import Sklearn
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
label_names = data['target_names']
labels = data['target']
feature_names = data['feature_names']
features = data['data']
   print(label_names)
   print(labels[0])
   print(feature_names[0])
   print(features[0])
train, test, train_labels, test_labels = train_test_split(
   features,labels,test_size = 0.40, random_state = 42
)
from sklearn.naive_bayes import GaussianNB
GNBclf = GaussianNB()
model = GNBclf.fit(train, train_labels)
preds = GNBclf.predict(test)
print(preds)

Output

[
   1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1
   1 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1
   1 1 1 0 0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0
   1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0
   1 1 0 1 1 0 0 0 1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1
   0 1 1 0 0 1 0 1 1 0 1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1
   1 1 1 1 1 1 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0 0 0 1 1 0
   1 0 1 1 1 1 0 1 1 0 1 1 1 0 1 0 0 1 1 1 1 1 1 1 1 0 1
   1 1 1 1 0 1 0 0 1 1 0 1
]

以上输出包含一系列 0 和 1,这些基本上是来自肿瘤类别(恶性和良性)的预测值。

Scikit Learn - Decision Trees

在本章中,我们将学习 Sklearn 中的学习方法,称为决策树。

决策树 (DT) 是最强大的非参数监督学习方法。它们可用于分类和回归任务。DT 的主要目标是创建一个模型,通过学习从数据特征中推导出的简单决策规则来预测目标变量值。决策树有两个主要实体;一个是数据分裂的根节点,另一个是决策节点或叶节点,在这些节点中我们得到了最终输出。

Decision Tree Algorithms

不同的决策树算法如下 −

ID3

它是由 Ross Quinlan 在 1986 年开发的。它也被称为 Iterative Dichotomiser 3。此算法的主要目标是为每个节点找到那些分类特征,这些特征将产生分类目标的最大信息增益。

它允许树长到最大尺寸,然后为了提高树对未见数据的能力,应用了一个剪枝步骤。此算法的输出将是一棵多向树。

C4.5

It is the successor to ID3 and dynamically defines a discrete attribute that partition the continuous attribute value into a discrete set of intervals. That’s the reason it removed the restriction of categorical features. It converts the ID3 trained tree into sets of ‘IF-THEN’ rules.

In order to determine the sequence in which these rules should applied, the accuracy of each rule will be evaluated first.

C5.0

It works similar as C4.5 but it uses less memory and build smaller rulesets. It is more accurate than C4.5.

CART

It is called Classification and Regression Trees alsgorithm. It basically generates binary splits by using the features and threshold yielding the largest information gain at each node (called the Gini index).

Homogeneity depends upon Gini index, higher the value of Gini index, higher would be the homogeneity. It is like C4.5 algorithm, but, the difference is that it does not compute rule sets and does not support numerical target variables (regression) as well.

Classification with decision trees

In this case, the decision variables are categorical.

Sklearn Module − The Scikit-learn library provides the module name DecisionTreeClassifier for performing multiclass classification on dataset.

Parameters

Following table consist the parameters used by sklearn.tree.DecisionTreeClassifier module −

Sr.No

Parameter & Description

1

criterion − string, optional default= “gini” It represents the function to measure the quality of a split. Supported criteria are “gini” and “entropy”. The default is gini which is for Gini impurity while entropy is for the information gain.

2

splitter − string, optional default= “best” It tells the model, which strategy from “best” or “random” to choose the split at each node.

3

max_depth − int or None, optional default=None This parameter decides the maximum depth of the tree. The default value is None which means the nodes will expand until all leaves are pure or until all leaves contain less than min_smaples_split samples.

4

min_samples_split − int, float, optional default=2 This parameter provides the minimum number of samples required to split an internal node.

5

min_samples_leaf − int, float, optional default=1 This parameter provides the minimum number of samples required to be at a leaf node.

6

min_weight_fraction_leaf − float, optional default=0. With this parameter, the model will get the minimum weighted fraction of the sum of weights required to be at a leaf node.

7

max_features − int, float, string or None, optional default=None It gives the model the number of features to be considered when looking for the best split.

8

random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options − int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random.

9

max_leaf_nodes − int or None, optional default=None This parameter will let grow a tree with max_leaf_nodes in best-first fashion. The default is none which means there would be unlimited number of leaf nodes.

10

min_impurity_decrease − float, optional default=0. This value works as a criterion for a node to split because the model will split a node if this split induces a decrease of the impurity greater than or equal to min_impurity_decrease value.

11

min_impurity_split − float, default=1e-7 It represents the threshold for early stopping in tree growth.

12

class_weight − 字典、字典列表,“平衡”或 None,默认值=None它表示与类关联的权重。形式为 {class_label: weight}。如果我们使用默认选项,这意味着所有类都应具有权重一。另一方面,如果您选择 class_weight: balanced ,它会使用 y 的值自动调整权重。

13

presort − 布尔值,可选,默认值=False它告诉该模型是否对数据进行预排序以加快在装配中找到最佳拆分的操作。默认值是 false,但如果设置为 true,它可能会减慢训练流程。

Attributes

下表包含 sklearn.tree.DecisionTreeClassifier 模块使用的属性 -

Sr.No

Parameter & Description

1

feature_importances_ - 形状 =[n_features] 的阵列此属性将返回特征重要性。

2

classes_: - 形状为 [n_classes] 的阵列或此类阵列的列表它表示类别标签,即单输出问题,或类标签的阵列列表,即多输出问题。

3

max_features_ − 整数它表示 max_features 参数推论出的值。

4

n_classes_ − 整数或列表它表示类数,即单输出问题,或每个输出的类数列表,即多输出问题。

5

n_features_ − 整数在执行 fit() 方法时,它给出 features 的数量。

6

n_outputs_ − 整数在执行 fit() 方法时,它给出 outputs 的数量。

Methods

下表包含 sklearn.tree.DecisionTreeClassifier 模块使用的属性 -

Sr.No

Parameter & Description

1

apply (self, X[, check_input])此方法将返回叶子索引。

2

decision_path (self, X[, check_input])顾名思义,此方法将返回树中的决策路径

3

fit (self, X, y[, sample_weight, …])fit() 方法将根据给定的训练集 (X, y) 构建决策树分类器。

4

get_depth (self)顾名思义,此方法将返回决策树的深度

5

get_n_leaves (self)顾名思义,此方法将返回决策树的叶数。

6

get_params (self[, deep])我们可以使用此方法来获取估计器的参数。

7

predict (self, X[, check_input])它将预测 X 的类值。

8

predict_log_proba (self, X)它将预测 X 提供的输入样本的类对数概率。

9

predict_proba (self, X[, check_input])它将预测 X 提供的输入样本的类概率。

10

score (self、X、y[、sample_weight]),如名字表示的那样,score() 方法会返回给定测试数据和标签上的平均准确度。

11

set_params (self、**params),我们可以使用此方法设置估计器的参数。

Implementation Example

下面的 Python 脚本将会用 sklearn.tree.DecisionTreeClassifier 模块,为我们的数据集(有 25 个样本以及两个特征,即“身高”和“头发长度”)构建一个用于预测男性或女性的分类器 −

from sklearn import tree
from sklearn.model_selection import train_test_split
X=[[165,19],[175,32],[136,35],[174,65],[141,28],[176,15]
,[131,32],[166,6],[128,32],[179,10],[136,34],[186,2],[12
6,25],[176,28],[112,38],[169,9],[171,36],[116,25],[196,2
5], [196,38], [126,40], [197,20], [150,25], [140,32],[136,35]]
Y=['Man','Woman','Woman','Man','Woman','Man','Woman','Ma
n','Woman','Man','Woman','Man','Woman','Woman','Woman','
Man','Woman','Woman','Man', 'Woman', 'Woman', 'Man', 'Man', 'Woman', 'Woman']
data_feature_names = ['height','length of hair']
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.3, random_state = 1)
DTclf = tree.DecisionTreeClassifier()
DTclf = clf.fit(X,Y)
prediction = DTclf.predict([[135,29]])
print(prediction)

Output

['Woman']

我们也可以使用以下 python predict_proba() 方法预测每个类的概率,如下所示 −

Example

prediction = DTclf.predict_proba([[135,29]])
print(prediction)

Output

[[0. 1.]]

Regression with decision trees

在这种情况下,决策变量是连续的。

Sklearn Module - Scikit-learn 库提供了模块名称 DecisionTreeRegressor ,以将决策树应用于回归问题。

Parameters

DecisionTreeRegressor 使用的参数与 DecisionTreeClassifier 模块中使用的参数基本相同。区别在于“标准”参数。对于 DecisionTreeRegressor 模块 ‘criterion :string,可选的默认值为 “mse”的参数有以下值 −

  1. mse - 它代表均方误差。它等于方差缩减作为特征选择标准。它最小化 L2 损失,使用每个终端节点的平均值。

  2. freidman_mse - 它也使用均方误差,但使用 Friedman 的改进分数。

  3. mae - 它代表平均绝对误差。它最小化 L1 损失,使用每个终端节点的中位数。

另一个区别是它没有 ‘class_weight’ 参数。

Attributes

DecisionTreeRegressor 的属性也与 DecisionTreeClassifier 模块的属性相同。区别是它没有 ‘classes_’‘n_classes_ 的属性。

Methods

DecisionTreeRegressor 的方法也与 DecisionTreeClassifier 模块的方法相同。区别是它没有 ‘predict_log_proba()’‘predict_proba()’ 属性。

Implementation Example

决策树回归模型中的 fit() 方法会获取 y 的浮点值。让我们使用 Sklearn.tree.DecisionTreeRegressor 看看一个简单的实现示例 −

from sklearn import tree
X = [[1, 1], [5, 5]]
y = [0.1, 1.5]
DTreg = tree.DecisionTreeRegressor()
DTreg = clf.fit(X, y)

一旦拟合,我们就可以使用此回归模型如下所示进行预测:

DTreg.predict([[4, 5]])

Output

array([1.5])

Scikit Learn - Randomized Decision Trees

本章将帮助你理解 Sklearn 中的随机决策树。

Randomized Decision Tree algorithms

众所周知,DT 通常通过递归分割数据来训练,但由于容易过拟合,它们已通过在数据的各种子样本上训练许多树而转化为随机森林。 sklearn.ensemble 模块具有基于随机决策树的以下两种算法 -

The Random Forest algorithm

对于考虑的每个特征,它计算局部最优特征/分割组合。在随机森林中,集合中的每个决策树都是通过从训练集中有放回地抽取样本构建的,然后从每个样本中获取预测,最后通过投票的方式选择最佳解。它既可用于分类任务,也可用于回归任务。

Classification with Random Forest

为了创建随机森林分类器,Scikit-learn 模块提供 sklearn.ensemble.RandomForestClassifier 。在构建随机森林分类器时,此模块使用的主要参数是 ‘max_features’‘n_estimators’

在此, ‘max_features’ 是拆分节点时要考虑的随机特征子集的大小。如果我们将此参数的值选择为 none,那么它将考虑所有特征,而不是随机子集。另一方面, n_estimators 是森林中的树的数量。树的数量越多,结果会越好。但计算也会花费更长时间。

Implementation example

在下面的示例中,我们通过使用 sklearn.ensemble.RandomForestClassifier 来构建随机森林分类器,并通过使用 cross_val_score 模块来检查其准确性。

from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
X, y = make_blobs(n_samples = 10000, n_features = 10, centers = 100,random_state = 0) RFclf = RandomForestClassifier(n_estimators = 10,max_depth = None,min_samples_split = 2, random_state = 0)
scores = cross_val_score(RFclf, X, y, cv = 5)
scores.mean()

Output

0.9997

Example

我们还可以使用 sklearn 数据集来构建随机森林分类器。与下面的示例一样,我们正在使用鸢尾花数据集。我们还将找到它的准确度得分和混淆矩阵。

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

path = "https://archive.ics.uci.edu/ml/machine-learning-database
s/iris/iris.data"
headernames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']
dataset = pd.read_csv(path, names = headernames)
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)
RFclf = RandomForestClassifier(n_estimators = 50)
RFclf.fit(X_train, y_train)
y_pred = RFclf.predict(X_test)
result = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(result)
result1 = classification_report(y_test, y_pred)
print("Classification Report:",)
print (result1)
result2 = accuracy_score(y_test,y_pred)
print("Accuracy:",result2)

Output

Confusion Matrix:
[[14 0 0]
[ 0 18 1]
[ 0 0 12]]
Classification Report:
                  precision recall f1-score support
Iris-setosa       1.00        1.00  1.00     14
Iris-versicolor   1.00        0.95  0.97     19
Iris-virginica    0.92        1.00  0.96     12

micro avg         0.98        0.98  0.98     45
macro avg         0.97        0.98  0.98     45
weighted avg      0.98        0.98  0.98     45

Accuracy: 0.9777777777777777

Regression with Random Forest

为了创建随机回归森林,Scikit-learn 模块提供了 sklearn.ensemble.RandomForestRegressor 。在构建随机森林回归器时,它将使用 sklearn.ensemble.RandomForestClassifier 使用的相同参数。

Implementation example

在下面的示例中,我们通过使用 sklearn.ensemble.RandomForestregressor 来构建随机森林回归器,并通过使用 predict() 方法对其进行预测。

from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression
X, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False)
RFregr = RandomForestRegressor(max_depth = 10,random_state = 0,n_estimators = 100)
RFregr.fit(X, y)

Output

RandomForestRegressor(
   bootstrap = True, criterion = 'mse', max_depth = 10,
   max_features = 'auto', max_leaf_nodes = None,
   min_impurity_decrease = 0.0, min_impurity_split = None,
   min_samples_leaf = 1, min_samples_split = 2,
   min_weight_fraction_leaf = 0.0, n_estimators = 100, n_jobs = None,
   oob_score = False, random_state = 0, verbose = 0, warm_start = False
)

拟合完成后,可以预测回归模型,如下所示:

print(RFregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))

Output

[98.47729198]

Extra-Tree Methods

对于每个要考虑的特征,它为拆分选择一个随机值。使用额外树方法的好处是,它可以进一步减少模型的方差。使用这些方法的缺点是,它会略微增加方差。

Classification with Extra-Tree Method

为了使用 Extra-tree 方法创建分类器,Scikit-learn 模块提供了 sklearn.ensemble.ExtraTreesClassifier 。它使用 sklearn.ensemble.RandomForestClassifier 使用的相同参数。唯一区别在于,按照上面讨论的方式,它们构建树。

Implementation example

在下面的示例中,我们通过使用 sklearn.ensemble.ExtraTreeClassifier 来构建随机森林分类器,并通过使用 cross_val_score 模块来检查其准确性。

from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_blobs
from sklearn.ensemble import ExtraTreesClassifier
X, y = make_blobs(n_samples = 10000, n_features = 10, centers=100,random_state = 0)
ETclf = ExtraTreesClassifier(n_estimators = 10,max_depth = None,min_samples_split = 10, random_state = 0)
scores = cross_val_score(ETclf, X, y, cv = 5)
scores.mean()

Output

1.0

Example

我们还可以使用 sklearn 数据集来使用 Extra-Tree 方法构建分类器。与下面的示例一样,我们正在使用 Pima-Indian 数据集。

from pandas import read_csv

from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import ExtraTreesClassifier
path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names=headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]
seed = 7
kfold = KFold(n_splits=10, random_state=seed)
num_trees = 150
max_features = 5
ETclf = ExtraTreesClassifier(n_estimators=num_trees, max_features=max_features)
results = cross_val_score(ETclf, X, Y, cv=kfold)
print(results.mean())

Output

0.7551435406698566

Regression with Extra-Tree Method

为了创建 Extra-Tree 回归,Scikit-learn 模块提供了 sklearn.ensemble.ExtraTreesRegressor 。在构建随机森林回归器时,它将使用 sklearn.ensemble.ExtraTreesClassifier 使用的相同参数。

Implementation example

在下面的示例中,我们应用 sklearn.ensemble.ExtraTreesregressor 以及我们在创建随机森林回归器时使用的相同数据。让我们看看输出中的差异

from sklearn.ensemble import ExtraTreesRegressor
from sklearn.datasets import make_regression
X, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False)
ETregr = ExtraTreesRegressor(max_depth = 10,random_state = 0,n_estimators = 100)
ETregr.fit(X, y)

Output

ExtraTreesRegressor(bootstrap = False, criterion = 'mse', max_depth = 10,
   max_features = 'auto', max_leaf_nodes = None,
   min_impurity_decrease = 0.0, min_impurity_split = None,
   min_samples_leaf = 1, min_samples_split = 2,
   min_weight_fraction_leaf = 0.0, n_estimators = 100, n_jobs = None,
   oob_score = False, random_state = 0, verbose = 0, warm_start = False)

Example

拟合完成后,可以预测回归模型,如下所示:

print(ETregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))

Output

[85.50955817]

Scikit Learn - Boosting Methods

在本章中,我们将了解 Sklearn 中的提升方法,它能够构建集成模型。

提升方法以增量方式构建集成模型。其主要原则是逐步构建模型,通过顺序训练每个基础模型估计器。为了构建强大的集成,这些方法在基本上结合了多个弱学习器,并在训练数据的多轮迭代中对它们进行顺序训练。sklearn.ensemble 模块具有以下两种提升方法。

AdaBoost

它是其中一种最成功的提升集成方法,其主要原理是它为数据集中的实例赋予权重的方式。这是算法在构建后续模型时为什么需要较少关注实例的原因。

Classification with AdaBoost

为了创建 AdaBoost 分类器,Scikit-learn 模块提供 sklearn.ensemble.AdaBoostClassifier 。在构建此分类器时,此模块使用 base_estimator 作为主要参数。在此处,base_estimator 是 base estimator 的值,它用于构建提升集成。如果我们将此参数的值选择为“none”,则基础估计器将为 DecisionTreeClassifier(max_depth=1)

Implementation example

在以下示例中,我们将通过使用 sklearn.ensemble.AdaBoostClassifier 来构建 AdaBoost 分类器,并且还将预测和检查其分数。

from sklearn.ensemble import AdaBoostClassifier
from sklearn.datasets import make_classification
X, y = make_classification(n_samples = 1000, n_features = 10,n_informative = 2, n_redundant = 0,random_state = 0, shuffle = False)
ADBclf = AdaBoostClassifier(n_estimators = 100, random_state = 0)
ADBclf.fit(X, y)

Output

AdaBoostClassifier(algorithm = 'SAMME.R', base_estimator = None,
learning_rate = 1.0, n_estimators = 100, random_state = 0)

Example

拟合完成后,可以预测新值,如下所示:

print(ADBclf.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))

Output

[1]

Example

现在,可以检查分数,如下所示:

ADBclf.score(X, y)

Output

0.995

Example

我们还可使用 sklearn 数据集,通过使用 Extra-Tree 方法来构建分类器。例如,在下面给出的示例中,我们正在使用 Pima-Indian 数据集。

from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import AdaBoostClassifier
path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names = headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]
seed = 5
kfold = KFold(n_splits = 10, random_state = seed)
num_trees = 100
max_features = 5
ADBclf = AdaBoostClassifier(n_estimators = num_trees, max_features = max_features)
results = cross_val_score(ADBclf, X, Y, cv = kfold)
print(results.mean())

Output

0.7851435406698566

Regression with AdaBoost

为了使用 Ada Boost 方法创建回归器,Scikit-learn 库提供了 sklearn.ensemble.AdaBoostRegressor 。在构建回归器时,它将使用 sklearn.ensemble.AdaBoostClassifier 使用的相同参数。

Implementation example

在以下示例中,我们将通过使用 sklearn.ensemble.AdaBoostregressor 来构建 AdaBoost 回归器,并且还通过使用 predict() 方法预测新值。

from sklearn.ensemble import AdaBoostRegressor
from sklearn.datasets import make_regression
X, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False)
ADBregr = RandomForestRegressor(random_state = 0,n_estimators = 100)
ADBregr.fit(X, y)

Output

AdaBoostRegressor(base_estimator = None, learning_rate = 1.0, loss = 'linear',
n_estimators = 100, random_state = 0)

Example

拟合完成后,可以预测回归模型,如下所示:

print(ADBregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))

Output

[85.50955817]

Gradient Tree Boosting

它也称为 Gradient Boosted Regression Trees (GRBT)。它基本上是任意可微损失函数的提升的概括。它以弱预测模型集成体的形式生成预测模型。它可用于回归和分类问题。它们的优势主要在于它们自然地处理混合类型数据。

Classification with Gradient Tree Boost

为了创建梯度树提升分类器,Scikit-learn 模块提供了 sklearn.ensemble.GradientBoostingClassifier 。在构建此分类器时,此模块使用 n_estimators 作为主要参数。在此处,“损失”是需要优化的损失函数的值。如果我们选择 loss = deviance,则它指的是针对具有概率输出的分类的偏差。

另一方面,如果我们将此参数的值选择为指数,则它将恢复 AdaBoost 算法。参数 n_estimators 将控制弱学习器的数量。名为 learning_rate (在 (0.0, 1.0] 范围内)的超参数将通过收缩控制过拟合。

Implementation example

在以下示例中,我们将通过使用 sklearn.ensemble.GradientBoostingClassifier 来构建梯度提升分类器。我们将使用 50 个弱学习器来拟合此分类器。

from sklearn.datasets import make_hastie_10_2
from sklearn.ensemble import GradientBoostingClassifier
X, y = make_hastie_10_2(random_state = 0)
X_train, X_test = X[:5000], X[5000:]
y_train, y_test = y[:5000], y[5000:]

GDBclf = GradientBoostingClassifier(n_estimators = 50, learning_rate = 1.0,max_depth = 1, random_state = 0).fit(X_train, y_train)
GDBclf.score(X_test, y_test)

Output

0.8724285714285714

Example

我们还可以使用 sklearn 数据集,以使用梯度提升分类器来构建分类器。在下例中,我们正在使用 Pima-Indian 数据集。

from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import GradientBoostingClassifier
path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names = headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]
seed = 5
kfold = KFold(n_splits = 10, random_state = seed)
num_trees = 100
max_features = 5
ADBclf = GradientBoostingClassifier(n_estimators = num_trees, max_features = max_features)
results = cross_val_score(ADBclf, X, Y, cv = kfold)
print(results.mean())

Output

0.7946582356674234

Regression with Gradient Tree Boost

为了通过梯度树提升方法创建回归器,Scikit-learn library 提供了 sklearn.ensemble.GradientBoostingRegressor 。它可以通过参数名称 loss 指定用于回归的损失函数。loss 的默认值为“ls”。

Implementation example

在下例中,我们通过使用 sklearn.ensemble.GradientBoostingregressor 构建了梯度提升回归器,并还通过使用 mean_squared_error() 方法找到了均方误差。

import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.datasets import make_friedman1
from sklearn.ensemble import GradientBoostingRegressor
X, y = make_friedman1(n_samples = 2000, random_state = 0, noise = 1.0)
X_train, X_test = X[:1000], X[1000:]
y_train, y_test = y[:1000], y[1000:]
GDBreg = GradientBoostingRegressor(n_estimators = 80, learning_rate=0.1,
max_depth = 1, random_state = 0, loss = 'ls').fit(X_train, y_train)

一旦拟合,我们就可以按如下内容找到均方误差:

mean_squared_error(y_test, GDBreg.predict(X_test))

Output

5.391246106657164

Scikit Learn - Clustering Methods

在这里,我们将研究 Sklearn 中的聚类方法,这将有助于识别数据样本中的相似性。

聚类方法是最有用的无监督 ML 方法之一,用于查找数据样本之间的相似性和关系模式。找到后,它们将根据特征将这些样本聚类到相似组中。聚类确定了现有未标记数据中的固有分组,这就是它很重要的原因。

Scikit-learn 库有 sklearn.cluster ,可以对未标记数据执行聚类。该模块下,scikit-leran 具有以下聚类方法:

KMeans

该算法计算质心并进行迭代,直到找到最优质心。它需要指定聚类数,这就是它假定聚类数已知的原因。该算法的主要逻辑是根据最小化标准(称为惯性)将数据聚类到 n 个相等方差组中,从而将样本分隔开。算法识别的聚类数由“K”表示。

Scikit-learn 有模块 sklearn.cluster.KMeans 来执行 K 均值聚类。在计算聚类中心和惯性值时,名为 sample_weight 的参数允许模块 sklearn.cluster.KMeans 将更多权重分配给某些样本。

Affinity Propagation

此算法基于“信息传递”的概念,在样本的不同对之间传递信息,直到收敛。它不要求在运行算法之前指定聚类数。该算法具有 O(N2T) 量级的复杂度,这是它最大的缺点。

Scikit-learn 有模块 sklearn.cluster.AffinityPropagation 来执行 Affinity Propagation 聚类。

Mean Shift

此算法主要发现样本平滑密度中的 blobs 。它通过将点移向数据点的最高密度,迭代地将数据点分配给聚类。它不依赖于参数 bandwidth 来指定搜索区域的大小,而是自动设置聚类数。

Scikit-learn 有模块 sklearn.cluster.MeanShift 来执行均值偏移聚类。

Spectral Clustering

在聚类之前,此算法基本上使用特征值,即数据的相似性矩阵频谱,在更少维度上执行降维。当聚类数很多时,不建议使用此算法。

Scikit-learn 有模块 sklearn.cluster.SpectralClustering 来执行谱聚类。

Hierarchical Clustering

此算法通过连续合并或拆分聚类来构建嵌套聚类。此聚类层次结构表示为树状图,即树。它分为以下两类:

Agglomerative hierarchical algorithms - 在这种分层算法中,每个数据点都被视为单个聚类。然后,它连续聚合成对聚类。这使用了自下而上的方法。

Divisive hierarchical algorithms - 在此分层算法中,所有数据点都被视为一大堆聚类。在此聚类过程中,使用自上而下的方法,将一大堆聚类分成各种小聚类。

Scikit-learn 有 sklearn.cluster.AgglomerativeClustering 模块,可用于执行凝聚层次聚类。

DBSCAN

它代表 “Density-based spatial clustering of applications with noise” 。此算法基于“聚类”和“噪音”的直观概念,其中聚类是数据空间中较低密度的密集区域,由较低密度的数据点区域分隔。

Scikit-learn 有 sklearn.cluster.DBSCAN 模块,可用于执行 DBSCAN 聚类。此算法使用两个重要参数,即 min_samples 和 eps,以定义密集。

参数 min_samples 值越大或参数 eps 值越小,将表明形成聚类所需的较高密度数据点。

OPTICS

它代表 “Ordering points to identify the clustering structure” 。此算法还会在空间数据中找到基于密度的聚类。其基本工作逻辑类似于 DBSCAN。

它通过以下方式解决 DBSCAN 算法的一个主要弱点——在密度不一致的数据中检测有意义的聚类问题:以空间上最接近的点成为排序中的邻居的方式来对数据库的点进行排序。

Scikit-learn 有 sklearn.cluster.OPTICS 模块,可用于执行 OPTICS 聚类。

BIRCH

它代表使用层次结构进行平衡迭代减少和聚类。用于对大型数据集执行层次聚类。它为给定数据构建一个名为 CFT (即 Characteristics Feature Tree )的树。

CFT 的优点在于,称为 CF(特征特性)节点的数据节点包含聚类所需的必要信息,从而进一步避免了在内存中保存整个输入数据的需要。

Scikit-learn 有 sklearn.cluster.Birch 模块,可用于执行 BIRCH 聚类。

Comparing Clustering Algorithms

下表将对 scikit-learn 中的聚类算法进行比较(基于参数、可伸缩性和度量)。

Sr.No

Algorithm Name

Parameters

Scalability

Metric Used

1

K-Means

No. of clusters

Very large n_samples

The distance between points.

2

Affinity Propagation

Damping

它不适用于 n_samples。

Graph Distance

3

Mean-Shift

Bandwidth

它不适用于 n_samples。

The distance between points.

4

Spectral Clustering

No.of clusters

对于 n_samples 具有中等可伸缩性。对于 n_clusters 具有小级别可伸缩性。

Graph Distance

5

Hierarchical Clustering

距离阈值或聚类数

Large n_samples Large n_clusters

The distance between points.

6

DBSCAN

Size of neighborhood

极大数量级的 n_samples 和中等数量级的 n_clusters。

Nearest point distance

7

OPTICS

Minimum cluster membership

极大数量级的 n_samples 和大量级的 n_clusters。

The distance between points.

8

BIRCH

Threshold, Branching factor

Large n_samples Large n_clusters

点之间的欧几里德距离。

K-Means Clustering on Scikit-learn Digit dataset

在此示例中,我们将对 digits 数据集应用 K-means 聚类。此算法将识别类似数字,而无需使用原始的标签信息。实现是在 Jupyter notebook 上完成的。

%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape

Output

1797, 64)

该输出显示,digit 数据集包含 1797 个样本,具有 64 个特征。

Example

现在,执行 K-Means 聚类,如下所示:−

kmeans = KMeans(n_clusters = 10, random_state = 0)
clusters = kmeans.fit_predict(digits.data)
kmeans.cluster_centers_.shape

Output

(10, 64)

该输出显示,K-Means 聚类创建了 10 个具有 64 个特征的聚类。

Example

fig, ax = plt.subplots(2, 5, figsize = (8, 3))
centers = kmeans.cluster_centers_.reshape(10, 8, 8)
for axi, center in zip(ax.flat, centers):
axi.set(xticks = [], yticks = [])
axi.imshow(center, interpolation = 'nearest', cmap = plt.cm.binary)

Output

以下输出包含图片,显示了 K-Means 聚类学习到的聚类中心。

clusters centers

接下来,下面的 Python 脚本将学习到的聚类标签(通过 K-Means)与其中找到的真实标签匹配 −

from scipy.stats import mode
labels = np.zeros_like(clusters)
for i in range(10):
mask = (clusters == i)
labels[mask] = mode(digits.target[mask])[0]

我们还可以借助下面提到的命令检查准确性。

from sklearn.metrics import accuracy_score
accuracy_score(digits.target, labels)

Output

0.7935447968836951

Complete Implementation Example

%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np

from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape
kmeans = KMeans(n_clusters = 10, random_state = 0)
clusters = kmeans.fit_predict(digits.data)
kmeans.cluster_centers_.shape
fig, ax = plt.subplots(2, 5, figsize = (8, 3))
centers = kmeans.cluster_centers_.reshape(10, 8, 8)
for axi, center in zip(ax.flat, centers):
   axi.set(xticks=[], yticks = [])
   axi.imshow(center, interpolation = 'nearest', cmap = plt.cm.binary)
from scipy.stats import mode
labels = np.zeros_like(clusters)
for i in range(10):
   mask = (clusters == i)
   labels[mask] = mode(digits.target[mask])[0]
from sklearn.metrics import accuracy_score
accuracy_score(digits.target, labels)

Scikit Learn - Clustering Performance Evaluation

有各种函数可以帮助我们评估聚类算法的性能。

以下是 Scikit-learn 提供的一些用于评估聚类性能的重要且使用最广泛的函数 −

Adjusted Rand Index

Rand Index 是一个计算两个聚类之间相似性度量的函数。对于此计算,Rand 索引考虑了所有样本对,并计算在预测聚类和真实聚类中分配到相似或不同聚类中的对数。然后,通过使用以下公式将原始 Rand 索引得分“调整为机会”,得到调整后的 Rand 索引得分 −

它有两个参数,即 labels_true (即 ground truth 类标签)和 labels_pred (即要评估的聚类标签)。

Example

from sklearn.metrics.cluster import adjusted_rand_score

   labels_true = [0, 0, 1, 1, 1, 1]
   labels_pred = [0, 0, 2, 2, 3, 3]

adjusted_rand_score(labels_true, labels_pred)

Output

0.4444444444444445

完美的标签会得到 1 分,而错误的标签或独立的标签会得到 0 或负分。

Mutual Information Based Score

互信息是一个计算两个分配一致性的函数。它忽略了排列。有以下版本可用 −

Normalized Mutual Information (NMI)

Scikit learn 具有 sklearn.metrics.normalized_mutual_info_score 模块。

Example

from sklearn.metrics.cluster import normalized_mutual_info_score

   labels_true = [0, 0, 1, 1, 1, 1]
   labels_pred = [0, 0, 2, 2, 3, 3]

normalized_mutual_info_score (labels_true, labels_pred)

Output

0.7611702597222881

Adjusted Mutual Information (AMI)

Scikit learn 具有 sklearn.metrics.adjusted_mutual_info_score 模块。

Example

from sklearn.metrics.cluster import adjusted_mutual_info_score

   labels_true = [0, 0, 1, 1, 1, 1]
   labels_pred = [0, 0, 2, 2, 3, 3]

adjusted_mutual_info_score (labels_true, labels_pred)

Output

0.4444444444444448

Fowlkes-Mallows Score

Fowlkes-Mallows 函数测量一组点的两个聚类的相似性。它可以定义为成对精度和召回率的几何平均值。

在数学上,

此处, TP = True Positive − 属于真实标签和预测标签中相同聚类的点对数。

FP = False Positive − 属于真实标签中相同聚类的点对数,但不属于预测标签中相同聚类的点对数。

FN = False Negative − 属于预测标签中相同聚类的点对数,但不属于真实标签中相同聚类的点对数。

Scikit learn 具有 sklearn.metrics.fowlkes_mallows_score 模块 −

Example

from sklearn.metrics.cluster import fowlkes_mallows_score

   labels_true = [0, 0, 1, 1, 1, 1]
   labels_pred = [0, 0, 2, 2, 3, 3]

fowlkes_mallows__score (labels_true, labels_pred)

Output

0.6546536707079771

Silhouette Coefficient

Silhouette 函数将使用所有样本的平均类内距离和每个样本的平均最近类距离计算所有样本的平均 Silhouette 系数。

在数学上,

此处,a 是类内距离。

并且,b 是平均最近类距离。

Scikit learn 具有 sklearn.metrics.silhouette_score 模块 −

Example

from sklearn import metrics.silhouette_score
from sklearn.metrics import pairwise_distances
from sklearn import datasets
import numpy as np
from sklearn.cluster import KMeans
dataset = datasets.load_iris()
X = dataset.data
y = dataset.target

kmeans_model = KMeans(n_clusters = 3, random_state = 1).fit(X)
labels = kmeans_model.labels_
silhouette_score(X, labels, metric = 'euclidean')

Output

0.5528190123564091

Contingency Matrix

此矩阵将报告(true,predicted)中每个可信对的交集基数。分类问题的混淆矩阵是一个方阵 Contingency。

Scikit learn 具有 sklearn.metrics.contingency_matrix 模块。

Example

from sklearn.metrics.cluster import contingency_matrix
x = ["a", "a", "a", "b", "b", "b"]
y = [1, 1, 2, 0, 1, 2]
contingency_matrix(x, y)

Output

array([
   [0, 2, 1],
   [1, 1, 1]
])

以上输出的第一行显示了三个真实集群为“a”的样本中,没有一个在 0 中,其中两个在 1 中,一个在 2 中。另一方面,第二行显示了三个真实集群为“b”的样本中,有 1 个在 0 中,有 1 个在 1 中,有 1 个在 2 中。

Scikit Learn - Dimensionality Reduction using PCA

降维是一种无监督机器学习方法,用于通过选择一组主特征来减少每个数据样本的特征变量数。主成分分析 (PCA) 是用于降维的流行算法之一。

Exact PCA

Principal Component Analysis (PCA) 用于使用数据的 Singular Value Decomposition (SVD) 进行线性维数化约,以将其投影到较低维的空间。使用 PCA 进行分解时,在应用 SVD 之前,先对输入数据进行居中,但没有针对各特征进行缩放。

Scikit-learn ML 库提供 sklearn.decomposition.PCA 模块,该模块实现为一个转换器对象,并在其 fit() 方法中学习 n 个分量。它还可用于新数据,将其投影到这些分量上。

Example

以下示例将使用 sklearn.decomposition.PCA 模块从 Pima Indians Diabetes 数据集中找出最佳的 5 个主成分。

from pandas import read_csv
from sklearn.decomposition import PCA
path = r'C:\Users\Leekha\Desktop\pima-indians-diabetes.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', ‘class']
dataframe = read_csv(path, names = names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
pca = PCA(n_components = 5)
fit = pca.fit(X)
print(("Explained Variance: %s") % (fit.explained_variance_ratio_))
print(fit.components_)

Output

Explained Variance: [0.88854663 0.06159078 0.02579012 0.01308614 0.00744094]
[
   [-2.02176587e-03 9.78115765e-02 1.60930503e-02 6.07566861e-029.93110844e-01 1.40108085e-02 5.37167919e-04 -3.56474430e-03]
   [-2.26488861e-02 -9.72210040e-01 -1.41909330e-01 5.78614699e-029.46266913e-02 -4.69729766e-02 -8.16804621e-04 -1.40168181e-01]
   [-2.24649003e-02 1.43428710e-01 -9.22467192e-01 -3.07013055e-012.09773019e-02 -1.32444542e-01 -6.39983017e-04 -1.25454310e-01]
   [-4.90459604e-02 1.19830016e-01 -2.62742788e-01 8.84369380e-01-6.55503615e-02 1.92801728e-01 2.69908637e-03 -3.01024330e-01]
   [ 1.51612874e-01 -8.79407680e-02 -2.32165009e-01 2.59973487e-01-1.72312241e-04 2.14744823e-02 1.64080684e-03 9.20504903e-01]
]

Incremental PCA

Incremental Principal Component Analysis (IPCA) 用于解决主成分分析 (PCA) 最大局限性,即 PCA 仅支持批处理,意味着所有要处理的输入数据均应装入内存。

Scikit-learn ML 库提供 sklearn.decomposition.IPCA 模块,可以通过使用其 partial_fit 方法对按顺序获取的数据块进行分块,或者启用 np.memmap (一个内存映射文件),而不将整个文件加载到内存中,从而实现免内存 PCA。

与 PCA 相同,使用 IPCA 进行分解时,在应用 SVD 之前,先对输入数据进行居中,但没有针对各特征进行缩放。

Example

以下示例将在 Sklearn digit 数据集上使用 sklearn.decomposition.IPCA 模块。

from sklearn.datasets import load_digits
from sklearn.decomposition import IncrementalPCA
X, _ = load_digits(return_X_y = True)
transformer = IncrementalPCA(n_components = 10, batch_size = 100)
transformer.partial_fit(X[:100, :])
X_transformed = transformer.fit_transform(X)
X_transformed.shape

Output

(1797, 10)

在这里,我们可以对较小的分批数据进行部分拟合(正如我们在每个分批上所做的那样),或者你可以让 fit() 函数将数据分成批次。

Kernel PCA

Kernel 主成分分析(PCA),作为 PCA 的扩展,利用内核获得非线性降维。它同时支持 transform and inverse_transform

Scikit-learn ML 库提供了 sklearn.decomposition.KernelPCA 模块。

Example

以下示例将在 Sklearn 数字数据集上使用 sklearn.decomposition.KernelPCA 模块。我们使用 sigmoid 核。

from sklearn.datasets import load_digits
from sklearn.decomposition import KernelPCA
X, _ = load_digits(return_X_y = True)
transformer = KernelPCA(n_components = 10, kernel = 'sigmoid')
X_transformed = transformer.fit_transform(X)
X_transformed.shape

Output

(1797, 10)

PCA using randomized SVD

使用随机 SVD 的主成分分析(PCA)用于将数据投影到更低维度的空间,同时保留大部分方差,即将与较低奇异值相关联的奇异向量删除。在这里,可以选择性参数 svd_solver=’randomized’ 的模块 sklearn.decomposition.PCA 为我们带来了很大帮助。

Example

以下示例将使用带选择性参数 svd_solver=’randomized’ 的模块 sklearn.decomposition.PCA ,在 Pima 印第安人糖尿病数据集中找到最佳 7 个主成分。

from pandas import read_csv
from sklearn.decomposition import PCA
path = r'C:\Users\Leekha\Desktop\pima-indians-diabetes.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = read_csv(path, names = names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
pca = PCA(n_components = 7,svd_solver = 'randomized')
fit = pca.fit(X)
print(("Explained Variance: %s") % (fit.explained_variance_ratio_))
print(fit.components_)

Output

Explained Variance: [8.88546635e-01 6.15907837e-02 2.57901189e-02 1.30861374e-027.44093864e-03 3.02614919e-03 5.12444875e-04]
[
   [-2.02176587e-03 9.78115765e-02 1.60930503e-02 6.07566861e-029.93110844e-01 1.40108085e-02 5.37167919e-04 -3.56474430e-03]
   [-2.26488861e-02 -9.72210040e-01 -1.41909330e-01 5.78614699e-029.46266913e-02 -4.69729766e-02 -8.16804621e-04 -1.40168181e-01]
   [-2.24649003e-02 1.43428710e-01 -9.22467192e-01 -3.07013055e-012.09773019e-02 -1.32444542e-01 -6.39983017e-04 -1.25454310e-01]
   [-4.90459604e-02 1.19830016e-01 -2.62742788e-01 8.84369380e-01-6.55503615e-02 1.92801728e-01 2.69908637e-03 -3.01024330e-01]
   [ 1.51612874e-01 -8.79407680e-02 -2.32165009e-01 2.59973487e-01-1.72312241e-04 2.14744823e-02 1.64080684e-03 9.20504903e-01]
   [-5.04730888e-03 5.07391813e-02 7.56365525e-02 2.21363068e-01-6.13326472e-03 -9.70776708e-01 -2.02903702e-03 -1.51133239e-02]
   [ 9.86672995e-01 8.83426114e-04 -1.22975947e-03 -3.76444746e-041.42307394e-03 -2.73046214e-03 -6.34402965e-03 -1.62555343e-01]
]