正则化方法及Python实现

正则化有助于克服过度拟合模型的问题。过度拟合是偏差和方差平衡的概念。如果过度拟合,机器学习模型将具有较低的准确性。当我们的机器学习模型试图从数据中学习更多属性时,就会添加来自训练数据的噪声。这里的噪声意味着数据点并不真正呈现数据的真实属性。
它将系数估计值调整或收缩为零。

在上面的图形中,您可以更好地理解这一点。
不同的正则化技术:
- L1和L2正则化
- Dropout
- 数据增强
- 提前停止(Early stopping)
正则化对系数进行惩罚。在深度学习中,它实际上惩罚了节点的权重矩阵。
L1和L2正则化:
它是最常见的正则化类型。在回归模型中,L1正则化称为Lasso回归,L2称为岭回归。
成本函数=损失(交叉熵)+正则化
在机器学习中,这个拟合过程涉及到损失函数RSS(残差平方和)。
Lasso(L1 Normalization)

Ridge (L2 Normalization)

'y'表示学习关系,' β'表示不同变量或预测变量(x)的系数估计。 λ是调整参数,决定了我们想要多大程度地惩罚模型的灵活性。
这两者的区别在于惩罚项。Ridge将系数的平方大小作为惩罚项加到损失函数上。 Lasso (Least Absolute Shrinkage and Selection Operator)增加系数的绝对值。
如果机器学习数据集中有大量特征,那么对于特征选择,Lasso会将不太重要的特征系数缩小为零。
Dropout
它是深度学习中最常用的正则化方法。在每次迭代中,dropout选择一些节点并将其连同所有传入和传出的连接一起丢弃。每个迭代都有不同的节点集和输出。在机器学习中,这被称为ensemble,当它们捕捉到更多的随机性时,性能会更好。

数据增强
减少过度拟合最简单的方法是增加训练数据的大小。在机器学习中,我们无法增加训练数据的大小,因为标记数据太昂贵。
但是,现在让我们考虑我们处理的是图像。有几种方法可以增加训练数据的大小——旋转图像、翻转、缩放等。
这种技术称为数据增强。这通常会提高模型的准确性。它可以被视为一个强制性的技巧,以改善我们的预测。
Early stopping
Early stopping是一种交叉验证策略,我们将训练集的一部分作为验证集。当我们发现验证集上的性能变差时,我们会立即停止对机器学习模型的训练。这被称为Early stopping。

在上图中,我们将在虚线处停止训练,因为之后我们的机器学习模型将开始对训练数据进行过度拟合。
下面是所有上述方法函数实现的python示例代码。
# Below is pseudo code for implementation of Lasso and Ridge
# import the required library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
import seaborn as sns
# For lasso and Ridge
from sklearn.linear_model import (LinearRegression,Ridge,Lasso,RandomizedLasso)
# For cross Validation
from sklearn.model_selection import cross_val_score
# for dropout
from keras.layers.core import Dropout
# For data augumentation
from keras.preprocessing.image import ImageDataGenerator
# For early stopping
from keras.callbacks import EarlyStopping
# read the dataset
data = pd.read_csv('PATH_OF_CSV_FILE')
########################## Data Preprocessing ##################################
# drop the column those are binary formated
data = data.drop(['LIST_OF_INDEPENDENT_VARIABLE'],axis=1)
# Use the seaborn plotter to plot the data
pt = sns.pairplot(data[['LIST_OF_INDEPENDENT_VARIABLE_TO_PLOT']], hue='_SET_YOUR_HUE_', palette='_SELECT_YOURSELF_',size=1.4)
pt.set(xticklabels=[])
# extract the target variable -- choosen by you -- into an array
y = data._YOUR__SELECTED_INDEPENDENT_VARIABLE_.values
# is an array with the price variable
# drop the column those are binary formated
data = data.drop(['LIST_OF_INDEPENDENT_VARIABLE'],axis=1)
# Create a matrix from the remaining data
X = data.as_matrix()
# Store the column/feature names into a list "colnames"
colnames = data.columns
########################## Lasso regularization ##############################
# create a lasso regressor
lasso = Lasso(alpha=0.2, normalize=True)
# Fit the regressor to the data
lasso.fit(X,y)
# Compute the coefficients
lasso_coef = lasso.coef_
# Plot the graph for this Lasso
plt.plot(range(len(colnames)), lasso_coef)
plt.xticks(range(len(colnames)), colnames.values, rotation=60)
plt.margins(0.02)
plt.show()
# Also Get the cross validation score
############################ Cross Validation ################################
# Create a linear regression object: reg
reg = LinearRegression()
# Compute 5-fold cross-validation scores: cv_scores
cv_scores = cross_val_score(reg, X, y, cv=5)
# Print the 5-fold cross-validation scores
print(cv_scores)
# find the mean of our cv scores here
print("Average 5-Fold CV Score: {}".format(np.mean(cv_scores)))
######################## Ridge Regression ####################################
# Create an array of alphas and lists to store scores
alpha_space = np.logspace(-4, 0, 50)
ridge_scores = []
ridge_scores_std = []
# Create a ridge regressor: ridge
ridge = Ridge(normalize=True)
# Compute scores over range of alphas
for alpha in alpha_space:
# Specify the alpha value to use: ridge.alpha
ridge.alpha = alpha
# Perform 10-fold CV: ridge_cv_scores
ridge_cv_scores = cross_val_score(ridge, X, y, cv=10)
# Append the mean of ridge_cv_scores to ridge_scores
ridge_scores.append(np.mean(ridge_cv_scores))
# Append the std of ridge_cv_scores to ridge_scores_std
ridge_scores_std.append(np.std(ridge_cv_scores))
# Use this function to create a plot
def display_plot(cv_scores, cv_scores_std):
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(alpha_space, cv_scores)
std_error = cv_scores_std / np.sqrt(10)
ax.fill_between(alpha_space, cv_scores + std_error, cv_scores - std_error, alpha=0.2)
ax.set_ylabel('CV Score +/- Std Error')
ax.set_xlabel('Alpha')
ax.axhline(np.max(cv_scores), linestyle='--', color='.5')
ax.set_xlim([alpha_space[0], alpha_space[-1]])
ax.set_xscale('log')
plt.show()
# Display the plot
display_plot(ridge_scores, ridge_scores_std)
##################################### Dropout ########################################
# Implement the dropout layer
model = Sequential([
Dense(output_dim=hidden1_num_units, input_dim=input_num_units, activation='relu'),
Dropout(0.25),
Dense(output_dim=output_num_units, input_dim=hidden5_num_units, activation='softmax'),
])
##################################### Data Augumentation ##############################
# For data Augumentation
datagen = ImageDataGenerator(horizontal flip=True)
datagen.fit(train)
#################################### Early Stopping ###################################
# For early stopping implementation
EarlyStopping(monitor='val_err', patience=5)



您可以根据您的数据集更改变量名称,并根据您的偏好修改代码,您也可以实现自己的正则化方法。