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

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

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

不同的正则化技术: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 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 rstrip函数_【C++实现python字符串函数库】strip、lstrip、rstrip方法

    [C++实现python字符串函数库]strip.lstrip.rstrip方法 这三个方法用于删除字符串首尾处指定的字符,默认删除空白符(包括'\n', '\r', '\t', ' '). s.st ...

  2. python创建线程_多种方法实现 python 线程池

    最近在做一个爬虫相关的项目,单线程的整站爬虫,耗时真的不是一般的巨大,运行一次也是心累,,,所以,要想实现整站爬虫,多线程是不可避免的,那么python多线程又应该怎样实现呢?这里主要要几个问题(关于 ...

  3. python filter函数_第九篇:Python中lambda、filter和map函数

    修修心养养性 世无常贵,事无常师,靠人不如靠己. 大纲 函数类型定义及特性 lambda函数定义及使用 filter函数定义及使用 map函数定义及使用 引入函数类型概念 函数类型定义:python中 ...

  4. python退出函数_【转】python 退出程序的方式

    python程序退出方式[sys.exit() os._exit() os.kill() os.popen(...)] 知乎说明 1. sys.exit() 执行该语句会直接退出程序,这也是经常使用的 ...

  5. python cut函数_一天学会Python Web框架(七)工具函数

    一.字符串操作包 string_helper.py是字符串操作包,主要对字符串进行检查.过滤和截取等处理. #!/usr/bin/evn python # coding=utf-8 import re ...

  6. python done函数_【转】Python内置函数(47)——open

    英文文档: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, ope ...

  7. python hist函数_虎哥的python小技巧放送之绘制统计图(2)

    先放出第一期让大家回顾一下上次的内容 虎哥的python小技巧放送之绘制统计图(1) 第一期主要给大家讲了一些图形设置的东西.这一次开始正式带大家画图~ 折线图:折线图可以通过matplotlib中的 ...

  8. python 排名函数_分数排名(Python),成绩,排序,python

    查找和排序 题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理. 示例: jack 70 peter 96 Tom 70 smith 67 从 ...

  9. python grid函数_(转)Python Tkinter Grid布局管理器详解

    Grid(网格)布局管理器会将控件放置到一个二维的表格里.主控件被分割成一系列的行和列,表格中的每个单元(cell)都可以放置一个控件. 什么时候使用Grid管理器 grid管理器是Tkinter里面 ...

最新文章

  1. 便利的开发工具 CppUnit 快速使用指南
  2. 断点续传了解一下啊?
  3. arduino水温度传感器数字显示_【雕爷学编程】Arduino动手做(5)---热敏温度传感器模块...
  4. php cache缓存 购物车,Yii2使用Redis缓存购物车等数据
  5. 089-袁佳鹏-实验报告1
  6. 服务中启动oracle服务,Linux下如何自动启动Oracle服务
  7. MySQL(四)索引的使用
  8. consul运维入门
  9. SQL语句实现行转列
  10. 串口控制led闪烁课程设计_排除led显示屏故障的方法及步骤
  11. 数据库系统原理教程-作业
  12. Windows2008之文件服务器资源管理器
  13. OC实现带弹跳动画按钮的界面控制器view
  14. 佳能G系列领军相机G1X
  15. 对接GA/T1400协议注册流程简易demo【Java版】
  16. Vue 项目断网时跳转到网络错误页面
  17. sql server 自定义背景、字体及显示行数
  18. 联想小新13pro锐龙版网卡_联想小新Pro13 锐龙版简测
  19. 三星D828刷机教程,完全经典版(附图)
  20. pdf怎么转换成jpg图片效果好

热门文章

  1. mssql行转列,列转行
  2. Malformed markup: Attribute “prop“ appears more than once in element
  3. WIN7系统搜索服务器文件慢,Win7旗舰版系统访问共享文件夹速度特别慢的应对方法...
  4. 利用原生Ajax技术实现WEB项目信息交互
  5. 党务管理信息系统,让组织人员架构管理更便利,操作更流畅
  6. IP有效载荷压缩协议(IPComp)
  7. 基于中值滤波与小波变换的图像去噪声实现
  8. 宝塔面板如何设置SSL访问HTTPS
  9. 【日常送书】非IT专业也能读得懂,这可能是最轻松的机器学习入门书
  10. Centos7 系列:磁盘挂载和磁盘扩容(新加硬盘方式)