当前位置:   article > 正文

机器学习笔记_scaler.scale

scaler.scale

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逆标准化的结果。

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

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逆最小最大归一化的结果。

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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)
  • 1
  • 2
  • 3
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).
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

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

import numpy as np
from sklearn.metrics import accuracy_score

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

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': { ... },
  			  ...
			}			
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
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得分的加权平均值。		
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
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
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
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。
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
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),或者一个浮点值数组,每个目标对应一个。
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
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。
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
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),或者一个浮点值数组,每个目标对应一个。
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
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
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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
		互信息,一个非负值,用自然对数来度量。
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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代表完美匹配。
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
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 分数。
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
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
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2 机器学习模型

2.1 线性回归与逻辑回归

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

答:所谓逻辑回归是一种特殊的广义线性回归,我们可以通过狭义线性回归到逻辑回归的转化过程来理解。狭义线性回归的表达式可表示为:y = w * x + b
逻辑回归可以表示为:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/174575
推荐阅读
相关标签