机器学习笔记

1 机器学习基础

1.1 特征工程

1.1.1 问题:为什么要对特征做归一化?

答:在采用基于梯度更新的学习方法(包括线性回归,逻辑回归,支持向量机,神经网络等)对模型求解的过程中,未归一化的数值特征在学习时,梯度下降较为抖动,模型难以收敛(通常需要较长的时间模型才能收敛);而归一化之后的数值特征则可以使梯度下降较为稳定,进而减少梯度计算的次数,也更容易收敛。

(王)归一化的作用:(1)使数据分布更规则,使梯度下降更稳定,加快模型收敛。
(2)某些机器学习算法对数据分布有要求。数据集的标准化是许多机器学习估计器的共同要求:如果单个特征或多或少看起来不像标准正态分布数据,则它们可能表现不佳。
(3)学习算法(例如支持向量机的 RBF 内核或线性模型的 l1 和 l2 正则化器)的目标函数中使用的许多元素都假设所有特征以零为中心,并且具有相同方向的方差。如果一个特征的方差比其他特征大几个数量级,它可能会支配目标函数并使估计器无法按预期正确地从其他特征中学习。

概念

特征归一化是将所有特征都统一到一个大致相同的数值区间内,通常为[0, 1]。常用的特征归一化方法有:
在这里插入图片描述
在这里插入图片描述

应用
  1. 实践中,我们通常忽视数据分布的形状,通过上面的标准化使数据更集中。

1.1.2 sklearn.preprocessing

Preprocessing and Normalization

The sklearn.preprocessing module includes scaling, centering, normalization, binarization methods.

1. sklearn.preprocessing.MinMaxScaler

最小最大归一化

概念
通过将每个特征缩放到给定的范围来变换特征。

实现

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler(feature_range=(0, 1), *, copy=True, clip=False)
"""参数
# feature_range: tuple (min, max)
# copy: 如果False,不复制,原地操作。
"""

# 属性
scaler.min_				# 返回每个特征最小值的相对变化量:min - X.min(axis=0) * self.scale_
scaler.scale_			# 返回每个特征的相对缩放比例:(max - min) / (X.max(axis=0) - X.min(axis=0))
scaler.data_min_		# 返回每个特征的最小值
scaler.data_max_		# 返回每个特征的最大值
scaler.data_range_		# 返回每个特征的范围:(data_max_ - data_min_)
scaler.n_features_in_	# 返回归一化的特征个数

# 方法
scaler.fit(X[, y])						# 计算用于后面缩放的均值和标准差。
scaler.transform(X[, copy])				# 实现标准化。
scaler.fit_transform(X[, y])			# fit then transform
scaler.get_params([deep])				# 返回scaler的参数。
scaler.inverse_transform(X[, copy])		# 返回数据X逆标准化的结果。

Notes:

  1. NaNs are treated as missing values: disregarded in fit, and maintained in transform.
  2. scaler.fit_transform(X) = X * self.scale_ + self.min_
2. sklearn.preprocessing.StandardScaler

标准化

概念
通过去除均值和按单位方差缩放来标准化特征。

在这里插入图片描述

应用

  1. 数据集的标准化是许多机器学习估计器的共同要求:如果单个特征或多或少看起来不像标准正态分布数据,则它们可能表现不佳。(标准正态分布:均值为0方差为1的高斯分布。)
  2. 学习算法(例如支持向量机的 RBF 内核或线性模型的 l1 和 l2 正则化器)的目标函数中使用的许多元素都假设所有特征以零为中心,并且具有相同方向的方差。如果一个特征的方差比其他特征大几个数量级,它可能会支配目标函数并使估计器无法按预期正确地从其他特征中学习。
  3. 通过设定with_mean=False,也可以应用于稀疏的CSR或CSC矩阵,以避免破坏数据的稀疏结构。

实现

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler(*, copy=True, with_mean=True, with_std=True)
"""参数
# copy: 如果 copy = False,则不复制,原地操作。
# with_mean:如果 with_mean = True,则在缩放之前将数据居中。当尝试在稀疏矩阵上时,这不起作用(并且会引发异常),因为将它们居中需要构建	一个密集矩阵,在常见的用例中,它可能太大而无法放入内存。
# with_std:如果 with_std = True,则将数据缩放到单位方差(或等效地,单位标准差)。
"""

# 属性
scaler.scale_				# 返回标准差
scaler.mean_				# 返回均值
scaler.var_					# 返回方差
scaler.n_features_in_		# 返回特征数目
scaler.feature_names_in_	# 返回特征名称
scaler.n_samples_seen_		# 返回样本数

# 方法
scaler.fit(X[, y, sample_weight])		# 计算用于后面缩放的最小值和最大值。
scaler.transform(X[, copy])				# 实现最小最大归一化。
scaler.fit_transform(X[, y])			# fit then transform
scaler.get_params([deep])				# 返回scaler的参数。
scaler.inverse_transform(X[, copy])		# 返回数据X逆最小最大归一化的结果。

Notes:

NaNs are treated as missing values: disregarded in fit, and maintained in transform.

3. sklearn.preprocessing.Normalizer

正则化

概念
将样本单独归一化到单位范数。

解释

  1. 一个样本至少有一个非零分量独立于其他样本进行缩放,那么它的范数(l1, l2或inf)等于1。
  2. 例如,将输入按单位范数缩放是文本分类或聚类的一种常见操作。例如,两个l2正则化的TF-IDF向量的点积就是向量的余弦相似度,是信息检索界常用的向量空间模型的基本相似度度量。
    举例证明第2点:
    在这里插入图片描述

实现

from sklearn.preprocessing import Normalizer

normalizer = Normalizer(norm='l2', *, copy=True).fit(X)
"""参数
# norm: {‘l1’, ‘l2’, ‘max’}, default=’l2’
		用于对每个非零样本进行规范化的范数。
		如果 norm=’max’,值将按绝对值的最大值进行缩放。 
"""

# 方法
normalizer.fit(X[, y])				# Do nothing and return the estimator unchanged.
normalizer.transform(X[, copy])		# Scale each non zero row of X to unit norm.
normalizer.fit_transform(X[, y])	# Fit to data, then transform it.
normalizer.get_params([deep])		# Get parameters for this estimator.
4. sklearn.preprocessing.OneHotEncoder

概念
将分类特征编码为一个独热数字数组。

实现

from sklearn.preprocessing import OneHotEncoder

enc = OneHotEncoder(*, categories='auto', drop=None, sparse=True, dtype=<class 'numpy.float64'>, handle_unknown='error')
"""参数
# categories: ‘auto’ or a list of array-like, default=’auto’
# sparse: bool, default=True
		如果设置为True将返回稀疏矩阵,否则将返回一个数组。
"""


# 属性
enc.categories_		# 返回类别


# 方法
enc.fit(X[, y])
enc.transform(X)
enc.fit_transform(X[, y])
enc.inverse_transform(X)

1.1.3 sklearn.decomposition

Matrix Decomposition

该模块的大部分算法可以看作是降维技术。

1. sklearn.decomposition.PCA

主成分分析

解释

  1. 利用奇异值分解(SVD)将数据投影到低维空间进行线性降维。在应用SVD之前,输入数据是居中的,但不对每个特征进行缩放。

实现

from sklearn.decomposition import PCA

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

"""参数
# n_components: int, float or ‘mle’, default=None
				要保留的成分数量。默认保留全部成分。

"""

# 属性
pca.components_						# 特征空间的主轴,表示数据中最大方差的方向。
pca.explained_variance_				# 由每个选定成分解释的方差。
pca.explained_variance_ratio_		# 由每个选定成分解释的方差百分比。
pca.singular_values_				# 对应于每个选定成分的奇异值。

# 方法
pca.fit(X[, y])				# Fit the model with X.
pca.transform(X)			# Apply dimensionality reduction to X.
pca.fit_transform(X[, y])	# Fit the model with X and apply the dimensionality reduction on X.
pca.get_covariance()		# 利用生成模型计算数据协方差。
pca.get_precision()			# 利用生成模型计算数据精度矩阵。
pca.inverse_transform(X)	# 逆过程。
pca.score(X[, y])			# 返回所有样本的平均对数似然估计。
pca.score_samples(X)		# 返回每个样本的对数似然估计。

1.1.4 sklearn.manifold

Manifold Learning
流形学习

The sklearn.manifold module implements data embedding techniques.

1. sklearn.manifold.LocallyLinearEmbedding

实现

from sklearn.manifold import LocallyLinearEmbedding

lle = LocallyLinearEmbedding(*, n_neighbors=5, n_components=2, reg=0.001, eigen_solver='auto', tol=1e-06, max_iter=100, method='standard', hessian_tol=0.0001, modified_tol=1e-12, neighbors_algorithm='auto', random_state=None, n_jobs=None)
2. sklearn.manifold.locally_linear_embedding

对数据进行局部线性嵌入分析。

1.1.5 问题:One-hot 的作用是什么,为什么不直接使用数字作为表示?

答:One-hot 主要用来编码类别特征,即采用虚拟变量(dummy variables) 对类别进行编码。它的作用是避免因将类别用数字作为表示而给函数带来抖动。直接使用数字会给将人工误差而导致的假设引入到类别特征中,比如类别之间的大小关系,以及差异关系等等。

1.1.6 问题:什么是数据不平衡,如何解决?

答:数据不平衡主要指的是在有监督机器学习任务中,样本标签值的分布不均匀。这将使得模型更倾向于将结果预测为样本标签分布较多的值,从而使得少数样本的预测性能下降。绝大多数常见的机器学习算法对于不平衡数据集都不能很好地工作。
解决方法:

  1. 重新采样训练集
    a. 欠采样 –通过减少丰富类的大小来平衡数据集。
    b. 过采样 – 增加稀有样本,通过使用重复,自举或合成少数类。
  2. 设计使用不平衡数据集的模型
    a. 在代价函数增大对稀有类别分类错误的惩罚权重。

1.1.7 问题:对于树形结构为什么不需要归一化

答:决策树的学习过程本质上是选择合适的特征,分裂并构建树节点的过程;而分裂节点的标准是由树构建前后的目标增益(比如信息增益和信息增益率)决定的。这些指标与特征值之间的数值范围差异并无关系。

1.2 模型评估

1.2.1 sklearn.metrics

Metrics

The sklearn.metrics module includes score functions, performance metrics and pairwise metrics and distance computations.

1.2.1.1 Classification metrics
1. sklearn.metrics.accuracy_score

Accuracy classification score.

实现

from sklearn.metrics import accuracy_score

accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None)

"""参数
# y_true: 1d array-like, or label indicator array / sparse matrix
# y_pred: 1d array-like, or label indicator array / sparse matrix
# normalize: bool, default=True
			If False, return the number of correctly classified samples. Otherwise, return the fraction of correctly 
			classified samples.
# sample_weight: array-like of shape (n_samples,), default=None
"""

"""返回
# score: float
		If normalize == True, return the fraction of correctly classified samples (float), else returns the number of 
		correctly classified samples (int).
"""

在带二进制标签指示器的多标签情况下:

import numpy as np
from sklearn.metrics import accuracy_score

accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2)))

return:0.5

2. sklearn.metrics.classification_report

构建一个显示主要分类指标的文本报告。

实现

from sklearn.metrics import classification_report

classification_report(y_true, y_pred, *, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division='warn')

"""参数
# y_true: 1d array-like, or label indicator array / sparse matrix
# y_pred: 1d array-like, or label indicator array / sparse matrix
# labels: array-like of shape (n_labels,), default=None
			要包含在报告中的可选标签索引列表。
# target_names: list of str of shape (n_labels,), default=None
				可选的显示名称匹配的标签(相同的顺序)。
# sample_weight: array-like of shape (n_samples,), default=None
# digits: int, default=2
			用于格式化输出浮点值的位数。当 output_dict = True 时,该值将被忽略,返回值不会四舍五入。
# output_dict: bool, default=False
				If True, return output as dict.
# zero_division: “warn”, 0 or 1, default=”warn”
				设置当有零除法时返回的值。如果将其设置为“warn”,则其作用为0,但也会引发警告。
"""

"""返回
# report: str or dict
			Text summary of the precision, recall, F1 score for each class. Dictionary returned if output_dict is True.
			Dictionary has the following structure:
			{'label 1': {'precision':0.5,
             			 'recall':1.0,
             			 'f1-score':0.67,
             			 'support':1},
 			 'label 2': { ... },
  			  ...
			}			
"""
3. sklearn.metrics.f1_score

实现

from sklearn.metrics import f1_score

f1_score(y_true, y_pred, *, labels=None, pos_label=1, average='binary', sample_weight=None, zero_division='warn')

"""参数
# y_true: 1d array-like, or label indicator array / sparse matrix
# y_pred: 1d array-like, or label indicator array / sparse matrix
# labels: array-like, default=None
# average: {‘micro’, ‘macro’, ‘samples’,’weighted’, ‘binary’} or None, default=’binary’
			多类/多标签目标需要此参数。如果为None,则返回每个类的分数。否则,这决定了对数据执行的平均类型。
# sample_weight: array-like of shape (n_samples,), default=None
# zero_division: “warn”, 0 or 1, default=”warn”
				设置当有零除法时返回的值,即当所有的预测和标签都是负时。如果将其设置为“warn”,则其作用为0,但也会引发警告。
"""

"""返回
# f1_score: float or array of float, shape = [n_unique_labels]
			二元分类中正类的F1得分或多分类任务中每个类F1得分的加权平均值。		
"""
4. sklearn.metrics.roc_auc_score

概念
Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores.
Note

这个实现可以用于二分类、多分类和多标签分类,但有一些限制(参见参数)。

实现

from sklearn.metrics import roc_auc_score

roc_auc_score(y_true, y_score, *, average='macro', sample_weight=None, max_fpr=None, multi_class='raise', labels=None)

"""参数
# y_true: array-like of shape (n_samples,) or (n_samples, n_classes)
# y_score: array-like of shape (n_samples,) or (n_samples, n_classes)
# average: {‘micro’, ‘macro’, ‘samples’, ‘weighted’} or None, default=’macro’
"""

"""返回
# auc: float
"""
1.2.1.2 Regression metrics
1. sklearn.metrics.mean_absolute_error

实现

from sklearn.metrics import mean_absolute_error

metrics.mean_absolute_error(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average')

"""参数
# y_true: array-like of shape (n_samples,) or (n_samples, n_outputs)
# y_pred: array-like of shape (n_samples,) or (n_samples, n_outputs)
# sample_weight: array-like of shape (n_samples,), default=None
"""

"""返回
# loss: float or ndarray of floats
		MAE输出是非负浮点数,最好的值是0.0。
"""
2. sklearn.metrics.mean_squared_error

实现

from sklearn.metrics import mean_squared_error

metrics.mean_squared_error(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average', squared=True)

"""参数
# y_true: array-like of shape (n_samples,) or (n_samples, n_outputs)
# y_pred: array-like of shape (n_samples,) or (n_samples, n_outputs)
# sample_weight: array-like of shape (n_samples,), default=None
# squared: bool, default=True
			If True returns MSE value, if False returns RMSE value.
"""

"""返回
# loss: float or ndarray of floats
		一个非负的浮点值(最好的值是0.0),或者一个浮点值数组,每个目标对应一个。
"""
3. sklearn.metrics.mean_absolute_percentage_error

实现

from sklearn.metrics import mean_absolute_percentage_error

mean_absolute_percentage_error(y_true, y_pred, sample_weight=None, multioutput='uniform_average')

"""参数
# y_true: array-like of shape (n_samples,) or (n_samples, n_outputs)
# y_pred: array-like of shape (n_samples,) or (n_samples, n_outputs)
# sample_weight: array-like of shape (n_samples,), default=None
"""

"""返回
# loss: float or ndarray of floats in the range [0, 1/eps]
		MAPE输出是非负浮点数。最好的值是0.0。但是请注意,糟糕的预测可能导致任意大的MAPE值,特别是在一些y_true值非常接近于零的情况下。注
		意,当y_true为0时,返回一个大值而不是inf。
"""
4. sklearn.metrics.mean_squared_log_error

实现

from sklearn.metrics import mean_squared_log_error

mean_squared_log_error(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average', squared=True)

"""参数
# y_true: array-like of shape (n_samples,) or (n_samples, n_outputs)
# y_pred: array-like of shape (n_samples,) or (n_samples, n_outputs)
# sample_weight: array-like of shape (n_samples,), default=None
# squared: bool, default=True
			If True returns MSLE (mean squared log error) value. If False returns RMSLE (root mean squared log error) 
			value.
"""

"""返回
# loss: float or ndarray of floats
		一个非负的浮点值(最好的值是0.0),或者一个浮点值数组,每个目标对应一个。
"""
5. sklearn.metrics.r2_score

解释
最好的分数是1.0,它可能是负的(因为模型可能是任意更差的)。一个常数模型总是预测y的期望值,而与输入特征无关,它的得分是0.0。

实现

from sklearn.metrics import r2_score

r2_score(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average')

"""参数
# y_true: array-like of shape (n_samples,) or (n_samples, n_outputs)
# y_pred: array-like of shape (n_samples,) or (n_samples, n_outputs)
# sample_weight: array-like of shape (n_samples,), default=None
"""

"""返回
# z: float or ndarray of floats
"""

Notes

对于单个样本,这个指标没有定义,如果n_samples小于2,将返回一个NaN值。

1.2.1.3 Clustering metrics
1. sklearn.metrics.mutual_info_score

概念
两个聚类之间的互信息。
互信息是对同一数据的两个标签之间相似性的度量。
在这里插入图片描述

实现

from sklearn.metrics import mutual_info_score

mutual_info_score(labels_true, labels_pred, *, contingency=None)

"""参数
# labels_true: int array, shape = [n_samples]
# labels_pred: int array-like of shape (n_samples,)
"""

"""返回
# mi: float
		互信息,一个非负值,用自然对数来度量。
"""

Notes

The logarithm used is the natural logarithm (base-e).

2. sklearn.metrics.rand_score

概念
RI = (number of agreeing pairs) / (number of pairs)

实现

from sklearn.metrics import rand_score

rand_score(labels_true, labels_pred)

"""参数
# labels_true: array-like of shape (n_samples,), dtype=integral
# labels_pred: array-like of shape (n_samples,), dtype=integral
"""

"""返回
# RI: float
		相似度在0.0和1.0之间,都包括,1.0代表完美匹配。
"""
3. sklearn.metrics.calinski_harabasz_score

概念
计算 Calinski-Harabasz 分数。
它也被称为方差比准则。
该分数定义为簇内离散度和簇间离散度之间的比率。

实现

from sklearn.metrics import calinski_harabasz_score

calinski_harabasz_score(X, labels)

"""参数
# X: array-like of shape (n_samples, n_features)
# labels: array-like of shape (n_samples,)
"""

"""返回
# score: float
		Calinski-Harabasz 分数。
"""
4. sklearn.metrics.davies_bouldin_score

概念
计算 Davies-Bouldin 分数。
该分数定义为每个聚类与其最相似聚类之间的平均相似性度量,其中相似性是聚类内距离与聚类间距离的比率。因此,类间距离越远、类内分散越少的聚类得分越好。
最小值为零,值越低表示聚类效果越好。

实现

from sklearn.metrics import davies_bouldin_score

davies_bouldin_score(X, labels)

"""参数
# X: array-like of shape (n_samples, n_features)
# labels: array-like of shape (n_samples,)
"""

"""返回
# score: float
		Davies-Bouldin 分数。
"""

1.2.2 问题:请比较欧式距离与曼哈顿距离?

在这里插入图片描述

  • 在基于地图,导航等应用中,欧式距离表现得理想化和现实上的距离相差较大;而曼哈顿距离就较为合适。
  • 另外欧式距离根据各个维度上的距离自动地给每个维度计算了一个“贡献权重”,这个权重会因为各个维度上距离的变化而动态的发生变化;而曼哈顿距离的每个维度对最终的距离都有同样的贡献权重。

1.2.3 问题:为什么一些场景中使用余弦相似度而不是欧式距离?

在这里插入图片描述
推导证明上式:
在这里插入图片描述

1.2.4 问题:在模型评估过程中,过拟合和欠拟合具体指什么现象 ?

过拟合是指模型对于训练数据拟合呈过当的情况,反映到评估指标上,就是模型在训练集上的表现好,但是在测试集和新数据上的表现较差。欠拟合指的是模型在训练和预测时表现都不好。
用模型在数据上的偏差和方差指标来表示就是:欠拟合时候,偏差比较大;而过拟合时,偏差较小但方差较大。

降低过拟合和欠拟合的方法
降低过拟合的方法:

  1. 特征 - 减少不必要的特征
    (1) 根据特征的重要性,直接删除稀疏特征;
    (2) 通过收集更多的数据,或者用数据增广的方法,产生更多的训练数据;从而阻止模型学习不相关的特征。
  2. 模型复杂度 - 降低模型复杂度
    (1) 神经网络,减少网络层数和神经元个数
    (2) 决策树模型中降低树的深度,进行剪枝
  3. 正则化 - 加入正则化项并提高正则化项的系数
    (1) 对复杂模型和系数比较大的模型进行惩罚,使得算法倾向于训练简单的模型。
  4. 多模型决策
    (1) 采用 Bagging 或者 Stacking 的集成方法;将多个模型融合起来共同决策;以减少模型预测的 variance。
  5. 模型训练
    (1) 训练模型时采用早停策略或采用知识蒸馏方法进行训练。
  6. 数据目标 – 平滑目标
    (1) 比如用于分类任务的标签平滑方法,即在 One-hot 表示的 ground true 标签里面,将值为 1 那一位上的一小部分值减掉,均分到其他值为 0 的位值上。

降低欠拟合的方法:

  1. 特征 - 添加新特征
    (1) 比如上下文特征,ID 类特征, 组合特征等等
  2. 模型复杂度 - 增加模型复杂度
    (1) 比如在线性模型中添加高次项;
    (2) 在神经网络模型中增加网络层数或者神经元个数。
  3. 正则化 - 减少正则化项的系数

1.2.5 问题:L1 和 L2 正则先验分别服从什么分布?

在这里插入图片描述
在这里插入图片描述

后验概率实际上就是条件概率。

1.3 参数调优

1.3.1 sklearn.model_selection

模型选择

1.3.1.1 Hyper-parameter optimizers
1. sklearn.model_selection.GridSearchCV

实现

from sklearn.model_selection import GridSearchCV

clf = GridSearchCV(estimator, param_grid, *, scoring=None, n_jobs=None, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score=nan, return_train_score=False)

"""参数
# estimator: estimator object
			This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a
			score function, or scoring must be passed.
# param_grid: dict or list of dictionaries
"""

2 机器学习模型

2.1 线性回归与逻辑回归

2.1.1 问题:逻辑回归相比线性回归,有何异同?

答:所谓逻辑回归是一种特殊的广义线性回归,我们可以通过狭义线性回归到逻辑回归的转化过程来理解。狭义线性回归的表达式可表示为:y = w * x + b
逻辑回归可以表示为: 𝑦 = 𝑠𝑖𝑔𝑚𝑜𝑖𝑑(𝑤 ∗ 𝑥 + 𝑏)
逻辑回归的求值计算其实就是在线性回归的基础上,再做一个 sigmoid 计算。所以它们都可以用相同的方法比如梯度下降来求解参数。

2.1.2 问题:回归问题常用的性能度量指标?

答:注:将误差归为以下三个类别是为了帮助记忆和理解,在学术研究中并没有这样公认的分类。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.1.3 问题:常见分类问题的度量指标?

答:
在这里插入图片描述
在这里插入图片描述

2.1.4 问题:逻辑回归的损失函数?

在这里插入图片描述

2.1.5 问题:逻辑回归处理多标签分类问题时,一般怎么做?

在这里插入图片描述

2.1.6 sklearn.linear_model

Linear Models

2.1.6.1 Linear classifiers
1. sklearn.linear_model.LogisticRegression

实现

from sklearn.linear_model import LogisticRegression

clf = class sklearn.linear_model.LogisticRegression(penalty='l2', *, dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)

"""参数
# penalty: {‘l1’, ‘l2’, ‘elasticnet’, ‘none’}, default=’l2’
			'elasticnet': both L1 and L2 penalty terms are added.
# tol: float, default=1e-4
		停止标准。
# C: float, default=1.0
	正则化强度的逆;必须是正浮点数。与支持向量机一样,越小的值表示越强的正则化。
# fit_intercept: bool, default=True
				指定是否应该向决策函数中添加常数(也称为偏差或截距)。
# class_weight: dict or ‘balanced’, default=None
				与类关联的权重,形式为{class_label: weight}。如果没有给出,所有类的权重都应该是1。
				“balanced”模式使用y值自动调整权重与输入数据中的类频率成反比 n_samples / (n_classes * np.bincount(y))
# random_state: int, RandomState instance, default=None
# solver: {‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’}, default=’lbfgs’
			对于小数据集,‘liblinear’是个不错的选择;对于大数据集,‘sag’ 和 ‘saga’ 更快。 
			对于多分类问题,只有 ‘newton-cg’, ‘sag’, ‘saga’ 和 ‘lbfgs’ 可以处理多项损失。
			‘liblinear’ 仅限于 one-versus-rest 的情况。
# max_iter: int, default=100
			求解器收敛所采用的最大迭代次数。
# warm_start: bool, default=False
				当设置为True时,重用前一个调用的解决方案作为初始化,否则,只擦除前一个解决方案。对 'liblinear' 求解器无效。
# l1_ratio: float, default=None
			Elastic-Net 混合参数,0 <= l1_ratio <= 1。仅在 penalty='elasticnet' 时使用。当设置 l1_ratio=0 时,等价于使用
			penalty='l2'。当设置 l1_ratio=1 时,等价于使用 penalty='l1'。当 0 < l1_ratio <1 时,惩罚是L1和L2的混合。	
"""

# 属性
clf.classes_			# 分类器已知的类标签列表。
clf.coef_				# 决策函数中特征的系数。
clf.intercept_			# 决策函数中加入的截距(又称偏差)。
clf.n_features_in_		# 在fit期间看到的特征数量。
clf.feature_names_in_	# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。
clf.n_iter_				# 所有类的实际迭代次数。如果是二进制或多项式,则只返回1个元素。对于线性求解器,只给出了所有类的最大迭代次数。

# 方法
clf.fit(X, y[, sample_weight])
clf.get_params([deep])
clf.set_params(**params)
clf.decision_function(X)			# 预测样本的置信度。
clf.predict(X)						# 预测样本X中的类标签。
clf.predict_proba(X)				# 概率估算。
clf.predict_log_proba(X)			# 预测概率估计的对数。
clf.score(X, y[, sample_weight])	# 返回给定测试数据和标签的平均精度。

在这里插入图片描述

2. sklearn.linear_model.Perceptron

线性感知器分类器。

实现

from sklearn.linear_model import Perceptron

clf = Perceptron(*, penalty=None, alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=0.001, shuffle=True, verbose=0, eta0=1.0, n_jobs=None, random_state=0, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, class_weight=None, warm_start=False)

"""参数
# penalty: {‘l2’,’l1’,’elasticnet’}, default=None
# alpha: float, default=0.0001
		如果使用正则化,则乘以正则化项的常数。
# l1_ratio: float, default=0.15
			Elastic-Net 混合参数,0 <= l1_ratio <= 1。仅在 penalty='elasticnet' 时使用。当设置 l1_ratio=0 时,等价于使用
			penalty='l2'。当设置 l1_ratio=1 时,等价于使用 penalty='l1'。当 0 < l1_ratio <1 时,惩罚是L1和L2的混合。
# fit_intercept: bool, default=True
				是否应该估计截距。如果为False,则假设数据已经居中。
# max_iter: int, default=1000
# tol: float, default=1e-3
		停止标准。当不是None时,迭代将在 loss > previous_loss - tol 时停止。
# shuffle: bool, default=True
			训练数据是否应该在每个时代之后进行洗牌。
# random_state: int, RandomState instance, default=None			
				当shuffle设置为True时,用于洗牌训练数据。通过多个函数调用传递一个int类型的可重复输出。
# early_stopping: bool, default=False
					是否使用提前停止来终止训练。分数没有提高。如果设置为True,它将自动保留训练数据的分层部分作为验证,并且 tol 在 	
					n_iter_no_change连续epoch验证得分没有提高的情况下终止训练。
# n_iter_no_change: int, default=5					
					在提前停止之前等待没有改进的迭代次数。
# class_weight: dict, {class_label: weight} or “balanced”, default=None
				与类关联的权重。如果没有给出,所有类的权重都应该是1。
				“balanced”模式使用y值自动调整权重与输入数据中的类频率成反比 n_samples / (n_classes * np.bincount(y))
# warm_start: bool, default=False
				当设置为True时,重用前一个调用的解决方案作为初始化,否则,只擦除前一个解决方案。
"""

# 属性
clf.classes_			# 分类器已知的类标签列表。
clf.coef_				# 决策函数中特征的系数。
clf.intercept_			# 决策函数中加入的截距(又称偏差)。
clf.n_features_in_		# 在fit期间看到的特征数量。
clf.feature_names_in_	# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。
clf.n_iter_				# 达到停止准则的实际迭代次数。对于多分类拟合,它是每个二进制拟合上的最大值。
clf.t_					# 在训练期间进行的权重更新次数。与(n_iter_ * n_samples)相同。
clf.loss_function_		# 确定算法输出和目标值之间的损失或差异的函数。

# 方法
clf.fit(X, y[, coef_init, intercept_init,])	# 用随机梯度下降拟合线性模型。
clf.get_params([deep])
clf.set_params(**params)
clf.decision_function(X)						# 预测样本的置信度。
clf.predict(X)									# 预测样本X中的类标签。
clf.score(X, y[, sample_weight])				# 返回给定测试数据和标签的平均精度。
2.1.6.2 Classical linear regressors
1. sklearn.linear_model.LinearRegression

普通最小二乘线性回归。

实现

from sklearn.linear_model import LinearRegression

reg = LinearRegression(*, fit_intercept=True, normalize='deprecated', copy_X=True, n_jobs=None, positive=False)

"""参数
# fit_intercept: bool, default=True	
				是否计算该模型的截距。如果设置为False,将不会在计算中使用截距(即数据将居中)。
# ncopy_X: bool, default=True				
			如果为True, X将被复制;否则,它可能会被覆盖。
"""

# 属性
reg.coef_				# 线性回归问题的估计系数。如果在fit(y 2D)期间传递了多个目标,这是一个形状为(n_targets, n_features)的2D数
						# 组,而如果只传递了一个目标,这是一个长度为n_features的1D数组。
reg.intercept_			# 线性模型中的独立项。如果fit_intercept = False,则设置为0.0。
reg.n_features_in_		# 在fit期间看到的特征数量。
reg.feature_names_in_	# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。
reg.rank_				# 矩阵X的秩,仅当X密集时可用。
reg.singular_			# X的奇异值,仅当X密集时可用。

# 方法
reg.fit(X, y[, sample_weight])					# Fit linear model.
reg.get_params([deep])
reg.set_params(**params)
reg.predict(X)									# 使用线性模型进行预测。
reg.score(X, y[, sample_weight])				# 返回预测的决定系数。

2.2 朴素贝叶斯

2.2.1 问题:写出全概率公式&贝叶斯公式?

在这里插入图片描述

2.2.2 问题:朴素贝叶斯为什么“朴素 naive”?

答:朴素贝叶斯,(Navie Bayesian)中的朴素可以理解为是“简单、理想化”的意思,因为“朴素”是假设了样本特征之间是相互独立、没有相关关系。这个假设在现实世界中是很不真实的,属性之间并不是都是互相独立的,有些属性也会存在相关性,所以说朴素贝叶斯是一种很“朴素”的算法。

2.2.3 问题:朴素贝叶斯的工作流程是怎样的?

答:朴素贝叶斯的工作流程可以分为三个阶段进行,分别是准备阶段、分类器训练阶段和应用阶段。

准备阶段: 这个阶段的任务是为朴素贝叶斯分类做必要的准备,主要工作是根据具体情况确定特征属性,并对每个特征属性进行适当划分,去除高度相关性的属性(如果两个属性具有高度相关性的话,那么该属性将会在模型中发挥了 2 次作用,会使得朴素贝叶斯所预测的结果向该属性所希望的方向偏离,导致分类出现偏差),然后由人工对一部分待分类项进行分类,形成训练样本集合。这一阶段的输入是所有待分类数据,输出是特征属性和训练样本。(这一阶段是整个朴素贝叶斯分类中唯一需要人工完成的阶段,其质量对整个过程将有重要影响。)

分类器训练阶段: 这个阶段的任务就是生成分类器,主要工作是计算每个类别在训练样本中的出现频率及每个特征属性划分对每个类别的条件概率估计,并将结果记录。其输入是特征属性和训练样本,输出是分类器。从公式上理解,朴素贝叶斯分类器模型的训练目的就是要计算一个后验概率𝑃(𝑐|𝑥)使得在给定特征的情况下,模型可以估计出每个类别出现的概率情况。
在这里插入图片描述

因为𝑃(𝑥)是一个先验概率,它对所有类别来说是相同的;而我们在预测的时候会比较每个类别相对的概率情况,选取最大的那个作为输出值。所以我们可以不计算𝑃(𝑥)。贝叶斯学习的过程就是要根据训练数据统计计算先验概率𝑃(𝑐)和后验概率𝑃(𝑥𝑖|𝑐)。

应用阶段: 这个阶段的任务是使用分类器对待分类项进行分类,其输入是分类器和待分类项,输出是待分类项与类别的映射关系。并选出概率值最高所对应的类别;用公式表示即为:
在这里插入图片描述

2.2.4 问题:朴素贝叶斯有没有超参数可以调?

答:基础朴素贝叶斯模型的训练过程,本质上是通过数学统计方法从训练数据中统计先验概率𝑃(𝑐)和后验概率𝑃(𝑥𝑖|𝑐);而这个过程是不需要超参数调节的。所以朴素贝叶斯模型没有可调节的超参数。虽然在实际应用中朴素贝叶斯会与拉普拉斯平滑修正(Laplacian Smoothing Correction)一起使用,而拉普拉斯平滑修正方法中有平滑系数这一超参数,但是这并不属于朴素贝叶斯模型本身的范畴。

2.2.5 问题:朴素贝叶斯对异常值敏不敏感?

答:基础的朴素贝叶斯模型的训练过程,本质上是通过数学统计方法从训练数据中统计先验概率𝑃(𝑐)和后验概率𝑃(𝑥𝑖|𝑐);少数的异常值,不会对统计结果造成比较大的影响。所以朴素贝叶斯模型对异常值不敏感。

2.2.6 sklearn.naive_bayes

Naive Bayes

sklearn.naive_bayes 模块实现朴素贝叶斯算法。这些都是基于强(朴素)特征独立假设的贝叶斯定理的监督学习方法。

1. sklearn.naive_bayes.BernoulliNB

概念
多元伯努利模型的朴素贝叶斯分类器。

解释
与多项分类器一样,该分类器适用于离散数据。两者的区别在于,MultinomialNB只处理出现次数,而BernoulliNB是为二进制/布尔特性设计的。

实现

from sklearn.naive_bayes import BernoulliNB

clf = BernoulliNB(*, alpha=1.0, binarize=0.0, fit_prior=True, class_prior=None)

"""参数
# alpha: float, default=1.0
		添加的(Laplace/Lidstone)平滑参数(0表示不平滑)。
# binarize: float or None, default=0.0		
			样本特征二值化(映射到布尔值)的阈值。如果为None,则假定输入已经由二进制向量组成。
# fit_prior: bool, default=True			
			是否学习类别的先验概率。如果是False,将使用统一的先验。
# class_prior: array-like of shape (n_classes,), default=None			
				类别的先验概率。如果指定先验值,则不根据数据进行调整。
"""

# 属性
clf.class_count_		# 在拟合过程中遇到的每个类的样本数量。该值由提供的样本权重进行加权。
clf.class_log_prior_	# 每个类别的对数概率(平滑)。
clf.classes_			# 分类器已知的类标签。
clf.feature_count_		# 在拟合过程中遇到的每个(类,特征)的样本数。该值由提供的样本权重进行加权。
clf.feature_log_prob_	# 给定类别的特征的经验对数概率P(x_i|y)。
clf.n_features_in_		# 在fit期间看到的特征数量。
clf.feature_names_in_	# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。

# 方法
clf.fit(X, y[, sample_weight])					# Fit Naive Bayes classifier according to X, y.
clf.get_params([deep])
clf.set_params(**params)
clf.predict(X)									# Perform classification on an array of test vectors X.
clf.predict_proba(X)							# Return probability estimates for the test vector X.
clf.predict_log_proba(X)						# Return log-probability estimates for the test vector X.
clf.score(X, y[, sample_weight])				# 返回给定测试数据和标签的平均精度。
2. sklearn.naive_bayes.CategoricalNB

概念
Naive Bayes classifier for categorical features.

解释
分类朴素贝叶斯分类器适用于具有分类分布的离散特征的分类。每个特征的类别都是从分类分布中提取的。

实现

from sklearn.naive_bayes import CategoricalNB

clf = CategoricalNB(*, alpha=1.0, fit_prior=True, class_prior=None, min_categories=None)

"""参数
# alpha: float, default=1.0
		添加的(Laplace/Lidstone)平滑参数(0表示不平滑)。
# fit_prior: bool, default=True			
			是否学习类别的先验概率。如果是False,将使用统一的先验。
# class_prior: array-like of shape (n_classes,), default=None			
				类别的先验概率。如果指定先验值,则不根据数据进行调整。
"""

# 属性
clf.class_count_		# 在拟合过程中遇到的每个类的样本数量。该值由提供的样本权重进行加权。
clf.class_log_prior_	# 每个类别的对数概率(平滑)。
clf.classes_			# 分类器已知的类标签。
clf.feature_log_prob_	# 给定类别的特征的经验对数概率P(x_i|y)。
clf.n_features_in_		# 在fit期间看到的特征数量。
clf.feature_names_in_	# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。

# 方法
clf.fit(X, y[, sample_weight])					# Fit Naive Bayes classifier according to X, y.
clf.get_params([deep])
clf.set_params(**params)
clf.predict(X)									# Perform classification on an array of test vectors X.
clf.predict_proba(X)							# Return probability estimates for the test vector X.
clf.predict_log_proba(X)						# Return log-probability estimates for the test vector X.
clf.score(X, y[, sample_weight])				# 返回给定测试数据和标签的平均精度。
3. sklearn.naive_bayes.ComplementNB

解释
Complement朴素贝叶斯分类器的设计是为了纠正标准多项式朴素贝叶斯分类器的“严格假设”。它特别适合于不平衡的数据集。

实现

from sklearn.naive_bayes import ComplementNB

clf = ComplementNB(*, alpha=1.0, fit_prior=True, class_prior=None, norm=False)

"""参数
# alpha: float, default=1.0
		添加的(Laplace/Lidstone)平滑参数(0表示不平滑)。
# fit_prior: bool, default=True			
			仅用于训练集中单个类的边缘情况。
# class_prior: array-like of shape (n_classes,), default=None			
				类别的先验概率。
# norm: bool, default=False
		是否对权重进行第二次标准化。
"""

# 属性
clf.class_count_		# 在拟合过程中遇到的每个类的样本数量。该值由提供的样本权重进行加权。
clf.class_log_prior_	# 每个类别的对数概率(平滑)。仅用于训练集中单个类的边缘情况。
clf.classes_			# 分类器已知的类标签。
clf.feature_all_		# 在拟合过程中遇到的每个特征的样本数量。该值由提供的样本权重进行加权。
clf.feature_count_		# 在拟合过程中遇到的每个(类,特征)的样本数。该值由提供的样本权重进行加权。
clf.feature_log_prob_	# class complements的经验权重。
clf.n_features_in_		# 在fit期间看到的特征数量。
clf.feature_names_in_	# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。

# 方法
clf.fit(X, y[, sample_weight])					# Fit Naive Bayes classifier according to X, y.
clf.get_params([deep])
clf.set_params(**params)
clf.predict(X)									# Perform classification on an array of test vectors X.
clf.predict_proba(X)							# Return probability estimates for the test vector X.
clf.predict_log_proba(X)						# Return log-probability estimates for the test vector X.
clf.score(X, y[, sample_weight])				# 返回给定测试数据和标签的平均精度。
4. sklearn.naive_bayes.GaussianNB

实现

from sklearn.naive_bayes import GaussianNB

clf = GaussianNB(*, priors=None, var_smoothing=1e-09)

"""参数
# priors: array-like of shape (n_classes,)
			类别的先验概率。如果指定先验值,则不根据数据进行调整。
# var_smoothing: float, default=1e-9			
				所有特征中最大方差的部分,添加到方差中以保证计算的稳定性。
"""

# 属性
clf.class_count_		# 每个类中观察到的训练样本数。
clf.class_prior_		# 每个类别的概率。
clf.classes_			# 分类器已知的类标签。
clf.epsilon_			# 方差和的绝对值。
clf.n_features_in_		# 在fit期间看到的特征数量。
clf.feature_names_in_	# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。
clf.var_				# 每个类的每个特征的方差。
clf.theta_				# 每个类的每个特征的均值。

# 方法
clf.fit(X, y[, sample_weight])					# Fit Gaussian Naive Bayes according to X, y.
clf.get_params([deep])
clf.set_params(**params)
clf.predict(X)									# Perform classification on an array of test vectors X.
clf.predict_proba(X)							# Return probability estimates for the test vector X.
clf.predict_log_proba(X)						# Return log-probability estimates for the test vector X.
clf.score(X, y[, sample_weight])				# 返回给定测试数据和标签的平均精度。
5. sklearn.naive_bayes.MultinomialNB

概念
多项式模型的朴素贝叶斯分类器。

解释
多项式朴素贝叶斯分类器适用于具有离散特征的分类(例如,用于文本分类的词数)。多项式分布通常需要整数特征计数。然而,在实践中,分数计数(如tf-idf)也可能起作用。

实现

from sklearn.naive_bayes import MultinomialNB

clf = MultinomialNB(*, alpha=1.0, fit_prior=True, class_prior=None)

"""参数
# alpha: float, default=1.0
		添加的(Laplace/Lidstone)平滑参数(0表示不平滑)。
# fit_prior: bool, default=True			
			是否学习类别的先验概率。如果是False,将使用统一的先验。
# class_prior: array-like of shape (n_classes,), default=None			
				类别的先验概率。如果指定先验值,则不根据数据进行调整。
"""

# 属性
clf.class_count_		# 在拟合过程中遇到的每个类的样本数量。该值由提供的样本权重进行加权。
clf.class_log_prior_	# 每个类别的对数概率(平滑)。
clf.classes_			# 分类器已知的类标签。
clf.feature_count_		# 在拟合过程中遇到的每个(类,特征)的样本数。该值由提供的样本权重进行加权。
clf.feature_log_prob_	# 给定类别的特征的经验对数概率P(x_i|y)。
clf.n_features_in_		# 在fit期间看到的特征数量。
clf.feature_names_in_	# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。

# 方法
clf.fit(X, y[, sample_weight])					# Fit Naive Bayes classifier according to X, y.
clf.get_params([deep])
clf.set_params(**params)
clf.predict(X)									# Perform classification on an array of test vectors X.
clf.predict_proba(X)							# Return probability estimates for the test vector X.
clf.predict_log_proba(X)						# Return log-probability estimates for the test vector X.
clf.score(X, y[, sample_weight])				# 返回给定测试数据和标签的平均精度。

2.3 K-Means

2.3.1 问题:简述 Kmeans 流程?

Kmeans 算法的基本流程如下:

  1. 随机初始化 k 个中心点;
  2. 计算所有样本分别到 k 个中心点的距离;
  3. 比较每个样本到 k 个中心点的距离,并将样本分类到距离最近的中心点所在的类别中;
  4. k 个类别组成的样本点重新计算中心点;
  5. 重复 2-4,直到中心点不再变化。 其中,k 表示预设的类别个数;两点的距离由欧式距离的平方表示;中心点的计算方式为:在表示中心点向量的每一个方向上计算当前类所有样本的均值。由于 Kmeans 的初始化中心点位置是随机的,而在 Kmeans 的优化过程中,每个中心点只在较小的距离范围内更新,所以算法的效果依赖于中心点初始化的效果。对于此问题的一个改进策略在 Kmeans++算法中提出。

Kmeans++ 的算法思想是使得初始化的聚类中心点之间的距离尽可能地远,目标是对Kmeans 算法的初始化进行优化。其具体流程为:
1.随机初始化一个中心;
2.对于每个样本 x,计算距离它最近的中心点的欧式距离 D(x),每个样本被选为中心点的概率为:

在这里插入图片描述

按照轮盘赌选择法(roulette wheel selection)选择出下一个中心点;
3.重复步骤 2,直到选出所有的中心点。

2.3.2 问题:Kmeans 对异常值是否敏感,为何?

Kmeans 对异常值较为敏感,因为一个集合内元素的均值易受到一个极大值的影响。如图中展示的结果,因为有了一个异常值,这个元素集合的中心点严重偏离了大多数点所在的位置区域;因此在有异常值影响的情况下,均值所计算出来的中心位置不能够反映真实的类别中心。
在这里插入图片描述

2.3.3 问题:如何评估聚类效果?

聚类往往不像分类一样有一个最优化目标和学习过程,而是一个统计方法,将相似的数据和不相似的数据分开。所以,评估聚类效果可以从以下维度入手:
1. 聚类趋势(对数据进行评估)
霍普金斯统计量(Hopkins Statistic)评估给定数据集是否存在有意义的可聚类的非随机结构。如果一个数据集是由随机、均匀的点生成的,虽然也可以产生聚类结果,但该结果没有意义。聚类的前提需要数据是非均匀分布的。该值在区间[0, 1]之间,[0.01, 0.3]表示数据接近随机分布,该值为 0.5 时数据是均匀分布的,[0.7, 0.99]表示聚类趋势很强。

2. 判定聚类的簇数是否为最佳
可用业务分析法,观察法,手肘法和 Gap Statistic 方法找到最佳的分类数,然后将这个分类数与实际簇数做比较 (见超参数 k 如何选择?)

3. 聚类质量
因为没有标签,所以一般通过评估类的分离情况来决定聚类质量。类内部的样本距离越小,类之间的距离越大,则表示聚类效果越好。

2.3.4 问题:超参数 k 如何选择?

1. 根据业务
比如业务需要把用户分成高中低三种,则 k 选择为 3。

2. 观察法
对于低纬度数据适用;对数据进行可视化或者 PCA 降维可视化之后,可大致观测出数据分布自然区分的类别数。

3. 手肘法
所有样本点到它所存在的聚类中心点的距离之和,作为模型好坏的衡量标准。具体步骤为:
在这里插入图片描述

4. Gap Statistic
在这里插入图片描述

2.3.5 问题:Kmeans 算法的优缺点?

在这里插入图片描述

2.3.6 sklearn.cluster

1. sklearn.cluster.KMeans

实现

from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters=8, *, init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True, algorithm='auto')

"""参数
# n_clusters: int, default=8
			要形成的簇的数量以及要产生的质心的数量。
# init: {‘k-means++’, ‘random’}, callable or array-like of shape (n_clusters, n_features), default=’k-means++’
# n_init: int, default=10
		使用不同质心种子运行k-means算法的次数。最终结果将是n_init连续运行的最佳输出。
# max_iter: int, default=300
			k-means算法在一次运行中的最大迭代次数。
# tol: float, default=1e-4			
		对于两个连续迭代的簇中心差异的Frobenius范数的相对误差来声明收敛。
# random_state: int, RandomState instance or None, default=None		
				确定质心初始化的随机数生成。使用一个int值来确定随机方式。
"""

# 属性
kmeans.cluster_centers_			# 聚类中心坐标。
kmeans.labels_					# 每个点的标签。
kmeans.inertia_					# 样本到它们最近的聚类中心的距离的平方和,如果提供了样本权重,则用样本权重进行加权。
kmeans.n_iter_					# 运行的迭代次数。
kmeans.n_features_in_			# 在fit期间看到的特征数量。
kmeans.feature_names_in_		# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。

# 方法
kmeans.fit(X[, y, sample_weight])				# 计算k-means聚类。
kmeans.transform(X)								# 将X转换为聚类-距离空间。
kmeans.fit_transform(X[, y, sample_weight])		# 计算聚类并将X转换为聚类-距离空间。
kmeans.get_params([deep])
kmeans.set_params(**params)
kmeans.predict(X[, sample_weight])				# 预测X中每个样本所属的最接近的聚类。
kmeans.score(X[, y, sample_weight])				# 与k-means目标上的X值相反。
kmeans.fit_predict(X[, y, sample_weight])		# 计算每个样本的聚类中心并预测聚类索引。
2. sklearn.cluster.DBSCAN

解释
Good for data which contains clusters of similar density.

实现

from sklearn.cluster import DBSCAN

clustering = DBSCAN(eps=0.5, *, min_samples=5, metric='euclidean', metric_params=None, algorithm='auto', leaf_size=30, p=None, n_jobs=None)

"""参数
# eps: float, default=0.5
		两个样本被认为互为领域的最大距离。这不是聚类内样本的距离的最大界限。这是为你的数据集和距离函数适当选择的最重要的DBSCAN参数。
# min_samples: int, default=5		
			作为核心点的一个邻域内的样本数(或总权重)。这包括点本身。
# p: float, default=None
	用于计算点之间距离的闵可夫斯基度量的指数。如果为None,则p=2(相当于欧几里得距离)。
"""

# 属性
clustering.labels_					# 给fit()的数据集中每个点的聚类标签。噪声样本被标记为-1。
clustering.n_features_in_			# 在fit期间看到的特征数量。
clustering.feature_names_in_		# 在fit期间看到的特征名称。仅当X的特性名称全部为字符串时才定义。

# 方法
clustering.fit(X[, y, sample_weight])			# 根据特征或距离矩阵进行DBSCAN聚类。
clustering.fit_predict(X[, y, sample_weight])	# 根据数据或距离矩阵计算聚类并预测标签。
clustering.get_params([deep])
clustering.set_params(**params)

2.4 SVM

2.4.1 问题:请简述 SVM 原理?

答:SVM 是一种二类分类模型。它的基本模型是在特征空间中寻找间隔最大化的分离超平面的线性分类器。

  • 当训练样本线性可分时,通过硬间隔最大化,学习一个线性分类器,即线性可分支持向量机。
  • 当训练数据近似线性可分时,引入松弛变量,通过软间隔最大化,学习一个线性分类器,即线性支持向量机。
  • 当训练数据线性不可分时,通过使用核技巧及软间隔最大化,学习非线性支持向量机。

2.4.2 问题:SVM 为什么采用间隔最大化?

答:当训练数据线性可分时,存在无穷多个分离超平面可以将两类数据正确分开。感知机利用误分类最小策略,求得分离超平面,不过此时的解有无穷多个。线性可分支持向量机利用间隔最大化求得最优分离超平面,这时,解是唯一的。另一方面,此时的分隔超平面所产生的分类结果是鲁棒的,对未知实例的泛化能力最强。

2.4.3 问题:SVM 为什么要引入核函数?

当样本在原始空间线性不可分时,可将样本从原始空间映射到一个更高维的特征空间,使得样本在这个特征空间内线性可分。而引入这样的映射后,在所要求解的问题中,无需求解真正的映射函数,而只需要知道其核函数。核函数的定义为:𝐾(𝑥, 𝑦) = < 𝜙(𝑥),𝜙(𝑦) >,即在特征空间的内积等于它们在原始样本空间中通过核函数 𝐾 计算的结果。
SVM 引入核函数之后,一方面数据变成了高维空间中线性可分的数据;另一方面不需要求解具体的映射函数,只需要给定具体的核函数即可,这样使得求解的难度大大降低。
在这里插入图片描述

2.4.4 问题:SVM 核函数之间的区别?

SVM 常用的核函数有线性核函数,多项式核函数,高斯核(RBF),拉普拉斯核和Sigmoid 核函数。其中多项式核函数,高斯核(RBF),拉普拉斯核和 Sigmoid 核函数通常用来处理线性不可分的情形。而一般选择核函数时通常考虑线性核和高斯核,也就是线性核与 RBF 核。 线性核:主要用于线性可分的情形,参数少,速度快,对于一般数据,分类效果已经很理想了。 RBF 核:主要用于线性不可分的情形,参数多,分类结果非常依赖于参数。有很多人是通过训练数据的交叉验证来寻找合适的参数,不过这个过程比较耗时。

2.4.5 问题:为什么 SVM 对缺失数据和噪声数据敏感 ?

这里说的缺失数据是指缺失某些特征数据,向量数据不完整。
SVM 没有处理缺失值的策略。而 SVM 希望样本在特征空间中线性可分,所以特征空间的好坏对 SVM 的性能很重要。缺失特征数据将影响训练结果的好坏。
另外,SVM 对噪声数据也较为敏感;原因是 SVM 的决策只基于少量的支持向量,若噪音样本出现在支持向量中,容易对决策造成影响,即影响目标函数中损失项的收敛,所以 SVM 对噪声敏感。

2.4.6 问题:SVM 算法的优缺点?

优点:
1.可以有效解决高维特征的分类和回归问题;
2.无需依赖全体样本,只依赖支持向量;
3.有大量的核技巧可以使用,从而可以应对线性不可分问题;
4.对于样本量中等偏小的情况,仍然有较好的效果。
缺点:
1.如果特征维度远大于样本个数,SVM 表现一般;
2.SVM 在样本巨大且使用核函数时,计算量很大;
3.在应对非线性可分数据时,核函数的选择依旧没有统一的标准;
4.SVM 对缺失和噪声数据敏感;
5.特征的多样性限制了 SVM 的使用,因为 SVM 本质上是属于一个几何模型,这个模型需要用 Kernel 定义样本之间的相似度(线性 SVM 中的内积),而我们无法预先为所有特征设定一个统一的相似度计算方法。这样的数学模型使得 SVM更适合去处理“同性质”的特征。

2.5 决策树

2.5.1 sklearn.tree

Decision Trees

1. sklearn.tree.DecisionTreeClassifier

实现

from sklearn.tree import DecisionTreeClassifier

clf = DecisionTreeClassifier(*, criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, class_weight=None, ccp_alpha=0.0)

"""参数
# criterion: {“gini”, “entropy”}, default=”gini”
			测量分裂质量的方法。
# splitter: {“best”, “random”}, default=”best”
			用于在每个节点上选择分割的策略。
# max_depth: int, default=None
			树的最大深度。如果为None,则节点将被拆分,直到所有叶子都是纯的,或者直到所有叶子包含小于min_samples_split样本。
# min_samples_split: int or float, default=2
					拆分内部节点所需的最小样本数:
					- If int, then consider min_samples_split as the minimum number.
					- If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the
			  		  minimum number of samples for each split.
# min_samples_leaf: int or float, default=1
					在一个叶子节点上所需的最小样本数。在任何深度上的分裂点只有它在每个左右分支中至少留下 min_samples_leaf 训练样本时        			
					才会被考虑。这可能有平滑模型的效果,特别是在回归中。
					- If int, then consider min_samples_leaf as the minimum number.
					- If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the
						minimum number of samples for each node. 
# min_weight_fraction_leaf: float, default=0.0
							一个叶子节点所需要的(所有输入样本的)权重总和中的最小权重分数。当没有提供sample_weight时,样本具有相同的
							权重。
"""


# 属性
clf.feature_importances_		# 返回特征的重要度。


# 方法
clf.fit(X, y[, sample_weight, check_input,])		# Build a decision tree classifier from the training set (X, y).
clf.apply(X[, check_input])							# Return the index of the leaf that each sample is predicted as.
clf.cost_complexity_pruning_path(X, y[,])			# 计算最小代价复杂度剪枝时的剪枝路径。
clf.decision_path(X[, check_input])					# 返回树中的决策路径。
clf.get_depth()										# 返回决策树的深度。
clf.get_n_leaves()									# 返回决策树的叶子节点数。
clf.predict(X[, check_input])						# Predict class or regression value for X.
clf.predict_log_proba(X)							# Predict class log-probabilities of the input samples X.
clf.predict_proba(X[, check_input])					# Predict class probabilities of the input samples X.
clf.score(X, y[, sample_weight])					# 返回给定测试数据和标签的平均准确率。
clf.get_params([deep])								# Get parameters for this estimator.
clf.set_params(**params)							# Set the parameters of this estimator.

2. sklearn.tree.DecisionTreeRegressor

实现

from sklearn.tree import DecisionTreeRegressor

regressor = DecisionTreeRegressor(*, criterion='squared_error', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, ccp_alpha=0.0)

"""参数
# criterion: {“squared_error”, “friedman_mse”, “absolute_error”, “poisson”}, default=”squared_error”
				测量分裂质量的方法。
# splitter: {“best”, “random”}, default=”best”
			用于在每个节点上选择分割的策略。
# max_depth: int, default=None
			树的最大深度。如果为None,则节点将被拆分,直到所有叶子都是纯的,或者直到所有叶子包含小于min_samples_split样本。
# min_samples_split: int or float, default=2
					拆分内部节点所需的最小样本数:
					- If int, then consider min_samples_split as the minimum number.
					- If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the
			  		  minimum number of samples for each split.
# min_samples_leaf: int or float, default=1
					在一个叶子节点上所需的最小样本数。在任何深度上的分裂点只有它在每个左右分支中至少留下 min_samples_leaf 训练样本时        			
					才会被考虑。这可能有平滑模型的效果,特别是在回归中。
					- If int, then consider min_samples_leaf as the minimum number.
					- If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the
						minimum number of samples for each node. 
# min_weight_fraction_leaf: float, default=0.0
							一个叶子节点所需要的(所有输入样本的)权重总和中的最小权重分数。当没有提供sample_weight时,样本具有相同的
							权重。
"""

# 属性
regressor.feature_importances_		# 返回特征的重要度。


# 方法
regressor.fit(X, y[, sample_weight, check_input,])  # Build a decision tree classifier from the training set (X, y).
regressor.apply(X[, check_input])					  # Return the index of the leaf that each sample is predicted as.
regressor.cost_complexity_pruning_path(X, y[,])	  # 计算最小代价复杂度剪枝时的剪枝路径。
regressor.decision_path(X[, check_input])			  # 返回树中的决策路径。
regressor.get_depth()								  # 返回决策树的深度。
regressor.get_n_leaves()							  # 返回决策树的叶子节点数。
regressor.predict(X[, check_input])					  # Predict class or regression value for X.
regressor.score(X, y[, sample_weight])				  # 返回预测的决定系数。
regressor.get_params([deep])						  # Get parameters for this estimator.
regressor.set_params(**params)						  # Set the parameters of this estimator.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

淘淘图兔兔呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值