赞
踩
答:在采用基于梯度更新的学习方法(包括线性回归,逻辑回归,支持向量机,神经网络等)对模型求解的过程中,未归一化的数值特征在学习时,梯度下降较为抖动,模型难以收敛(通常需要较长的时间模型才能收敛);而归一化之后的数值特征则可以使梯度下降较为稳定,进而减少梯度计算的次数,也更容易收敛。
(王)归一化的作用:(1)使数据分布更规则,使梯度下降更稳定,加快模型收敛。
(2)某些机器学习算法对数据分布有要求。数据集的标准化是许多机器学习估计器的共同要求:如果单个特征或多或少看起来不像标准正态分布数据,则它们可能表现不佳。
(3)学习算法(例如支持向量机的 RBF 内核或线性模型的 l1 和 l2 正则化器)的目标函数中使用的许多元素都假设所有特征以零为中心,并且具有相同方向的方差。如果一个特征的方差比其他特征大几个数量级,它可能会支配目标函数并使估计器无法按预期正确地从其他特征中学习。
特征归一化是将所有特征都统一到一个大致相同的数值区间内,通常为[0, 1]。常用的特征归一化方法有:
Preprocessing and Normalization
The sklearn.preprocessing
module includes scaling, centering, normalization, binarization methods.
最小最大归一化
概念
通过将每个特征缩放到给定的范围来变换特征。
实现
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:
- NaNs are treated as missing values: disregarded in fit, and maintained in transform.
- scaler.fit_transform(X) = X * self.scale_ + self.min_
标准化
概念
通过去除均值和按单位方差缩放来标准化特征。
应用
实现
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.
正则化
概念
将样本单独归一化到单位范数。
解释
实现
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.
概念
将分类特征编码为一个独热数字数组。
实现
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)
Matrix Decomposition
该模块的大部分算法可以看作是降维技术。
主成分分析
解释
实现
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) # 返回每个样本的对数似然估计。
Manifold Learning
流形学习
The sklearn.manifold
module implements data embedding techniques.
实现
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)
对数据进行局部线性嵌入分析。
答:One-hot 主要用来编码类别特征,即采用虚拟变量(dummy variables) 对类别进行编码。它的作用是避免因将类别用数字作为表示而给函数带来抖动。直接使用数字会给将人工误差而导致的假设引入到类别特征中,比如类别之间的大小关系,以及差异关系等等。
答:数据不平衡主要指的是在有监督机器学习任务中,样本标签值的分布不均匀。这将使得模型更倾向于将结果预测为样本标签分布较多的值,从而使得少数样本的预测性能下降。绝大多数常见的机器学习算法对于不平衡数据集都不能很好地工作。
解决方法:
答:决策树的学习过程本质上是选择合适的特征,分裂并构建树节点的过程;而分裂节点的标准是由树构建前后的目标增益(比如信息增益和信息增益率)决定的。这些指标与特征值之间的数值范围差异并无关系。
Metrics
The sklearn.metrics module includes score functions, performance metrics and pairwise metrics and distance computations.
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
构建一个显示主要分类指标的文本报告。
实现
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': { ... }, ... } """
实现
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得分的加权平均值。 """
概念
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
"""
实现
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。
"""
实现
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),或者一个浮点值数组,每个目标对应一个。 """
实现
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。
"""
实现
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),或者一个浮点值数组,每个目标对应一个。 """
解释
最好的分数是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值。
概念
两个聚类之间的互信息。
互信息是对同一数据的两个标签之间相似性的度量。
实现
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).
概念
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代表完美匹配。
"""
概念
计算 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 分数。
"""
概念
计算 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 分数。
"""
推导证明上式:
过拟合是指模型对于训练数据拟合呈过当的情况,反映到评估指标上,就是模型在训练集上的表现好,但是在测试集和新数据上的表现较差。欠拟合指的是模型在训练和预测时表现都不好。
用模型在数据上的偏差和方差指标来表示就是:欠拟合时候,偏差比较大;而过拟合时,偏差较小但方差较大。
降低过拟合和欠拟合的方法
降低过拟合的方法:
降低欠拟合的方法:
后验概率实际上就是条件概率。
模型选择
实现
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
"""
答:所谓逻辑回归是一种特殊的广义线性回归,我们可以通过狭义线性回归到逻辑回归的转化过程来理解。狭义线性回归的表达式可表示为:y = w * x + b
逻辑回归可以表示为:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。