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

它将系数估计值调整或收缩为零。

在上面的图形中,您可以更好地理解这一点。

不同的正则化技术:

  1. L1和L2正则化
  2. Dropout
  3. 数据增强
  4. 提前停止(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 libraryimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import preprocessingimport seaborn as sns# For lasso and Ridgefrom sklearn.linear_model import (LinearRegression,Ridge,Lasso,RandomizedLasso)# For cross Validationfrom sklearn.model_selection import cross_val_score# for dropoutfrom keras.layers.core import Dropout# For data augumentationfrom keras.preprocessing.image import ImageDataGenerator# For early stoppingfrom keras.callbacks import EarlyStopping# read the dataset data = pd.read_csv('PATH_OF_CSV_FILE')########################## Data Preprocessing ################################### drop the column those are binary formateddata = data.drop(['LIST_OF_INDEPENDENT_VARIABLE'],axis=1)# Use the seaborn plotter to plot the datapt = 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 formateddata = data.drop(['LIST_OF_INDEPENDENT_VARIABLE'],axis=1)# Create a matrix from the remaining dataX = data.as_matrix()# Store the column/feature names into a list "colnames"colnames = data.columns########################## Lasso regularization ############################### create a lasso regressorlasso = Lasso(alpha=0.2, normalize=True)# Fit the regressor to the datalasso.fit(X,y)# Compute the coefficientslasso_coef = lasso.coef_# Plot the graph for this Lassoplt.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: regreg = LinearRegression()# Compute 5-fold cross-validation scores: cv_scorescv_scores = cross_val_score(reg, X, y, cv=5)# Print the 5-fold cross-validation scoresprint(cv_scores)# find the mean of our cv scores hereprint("Average 5-Fold CV Score: {}".format(np.mean(cv_scores)))######################## Ridge Regression ##################################### Create an array of alphas and lists to store scoresalpha_space = np.logspace(-4, 0, 50)ridge_scores = []ridge_scores_std = []# Create a ridge regressor: ridgeridge = Ridge(normalize=True)# Compute scores over range of alphasfor 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 plotdisplay_plot(ridge_scores, ridge_scores_std)##################################### Dropout ######################################### Implement the dropout layermodel = 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 Augumentationdatagen = ImageDataGenerator(horizontal flip=True)datagen.fit(train)#################################### Early Stopping #################################### For early stopping implementationEarlyStopping(monitor='val_err', patience=5)

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

python正则_正则化方法及Python实现相关推荐

  1. python正则化函数_正则化方法及Python实现

    正则化有助于克服过度拟合模型的问题.过度拟合是偏差和方差平衡的概念.如果过度拟合,机器学习模型将具有较低的准确性.当我们的机器学习模型试图从数据中学习更多属性时,就会添加来自训练数据的噪声.这里的噪声 ...

  2. ubuntu更改默认python版本_更改Ubuntu默认python版本的方法

    1.查看基本信息 # 列出所有已安装python ls /usr/bin/python* #查看默认的 Python 版本信息: python --version 2.基于用户修改 默认Python ...

  3. python 示例_带有示例的Python File write()方法

    python 示例 文件write()方法 (File write() Method) write() method is an inbuilt method in Python, it is use ...

  4. python 示例_带有示例的Python字典update()方法

    python 示例 字典update()方法 (Dictionary update() Method) update() method is used to update the dictionary ...

  5. python 示例_带有示例的Python字典popitem()方法

    python 示例 字典popitem()方法 (Dictionary popitem() Method) popitem() method is used to remove random/last ...

  6. python 示例_带有示例的Python File close()方法

    python 示例 文件close()方法 (File close() Method) close() method is an inbuilt method in Python, it is use ...

  7. python 示例_带有示例的Python列表remove()方法

    python 示例 列出remove()方法 (List remove() Method) remove() method is used to remove the first occurrence ...

  8. python 示例_带有示例的Python File read()方法

    python 示例 文件read()方法 (File read() Method) read() method is an inbuilt method in Python, it is used t ...

  9. python 示例_带有示例的Python列表copy()方法

    python 示例 列出copy()方法 (List copy() Method) copy() method is used to copy a list, the method is called ...

最新文章

  1. NHibernate之Generator主键生成方式
  2. [Swift通天遁地]七、数据与安全-(19)使用Swift实现原生的SHA1加密
  3. 无需predetermine一条路
  4. 用双向链表实现一个栈
  5. 如何使用html和css,如何使用html和css制作这个div?
  6. SwiftUI之深入解析如何处理特定的数据和如何在视图中适配数据模型对象
  7. oracle rownum 学习
  8. linux shell 试题,linux-shell 练习题
  9. pythonread读取怎么是乱码_python中如何读写文件不乱码
  10. cf修改游戏客户端是什么意思_cf游戏客户端是什么
  11. 力扣-205 同构字符串
  12. 筛选索引--filter indexs
  13. 获取两个数组的差 php,php-获取2个数组之间的差
  14. Flex builder3相关
  15. 什么是商业智能(BI)?
  16. Win7通过CMD命令开启无线热点
  17. 微信开发工具调试公众号
  18. 安装NET.FRAMEWORK报错:error 25015安装法度集 C:\Windows\Microsoft .NET\Framework\v2.0.50727\xxx.dl...
  19. [在线挑战]【i春秋】渗透测试入门 —— 渗透测试笔记 --转
  20. 非必要千万不要改C盘用户名!!!

热门文章

  1. 计算机在网站设计中的应用,网页设计中平面设计的应用及其作用
  2. linux mkdir 系统调用,Linux Rootkit 系列四:对于系统调用挂钩方法的补充
  3. java 解析ppt动画_上映17天,姜子牙口碑一路狂跌,但这份PPT让它又火了!
  4. oracle 01035,oracle常用命令(一)
  5. mfc对话框ok没效果_摄影色调效果(冷色调与暧色调)
  6. 37镇魔曲网页版服务器状态,37《镇魔曲网页版》官网正式上线
  7. 结构体嵌套结构体c语言,结构体的相互嵌套
  8. python读取二进制数据转整形,在python中读取二进制数据(替换C代码)
  9. linux时间与日期函数,Linux时间日期函数
  10. java怎么新建模块_spring boot添加新模块的方法教程