Task5.PyTorch实现L1,L2正则化以及Dropout
1.了解知道Dropout原理
深度学习网路中,参数多,可能出现过拟合及费时问题。为了解决这一问题,通过实验,在2012年,Hinton在其论文《Improving neural networks by preventing co-adaptation of feature detectors》中提出Dropout。证明了其能有效解决过拟合的能力。
dropout 是指在深度学习网络的训练过程中,按照一定的概率将一部分神经网络单元暂时从网络中丢弃,相当于从原始的网络中找到一个更瘦的网络示意图如下:
其实现是以某种概率分布使得一些神经元为0,一些为1.这样在有N个神经元的神经网络中,其参数搭配可能有2^N种。
具体介绍 见论文(我也不是很懂 实现得见)
适用情况:
1 Dropout主要用在数据量不够,容易过拟合,需要dropout。
L1及L2可以使得结构化风险最小
其中:
L1的参数具有稀疏性(具有更多的0或1)
L2的参数趋近于分散化 ,其参数值趋向于选择更简单(趋于0的参数),因此比较平滑
2.用代码实现正则化(L1、L2、Dropout)
L1范数
L1范数是参数矩阵W中元素的绝对值之和,L1范数相对于L0范数不同点在于,L0范数求解是NP问题,而L1范数是L0范数的最优凸近似,求解较为容易。L1常被称为LASSO.
regularization_loss = 0
for param in model.parameters():
regularization_loss += torch.sum(abs(param)) for epoch in range(EPOCHS):
y_pred = model(x_train)
classify_loss = criterion(y_pred, y_train.float().view(-1, 1))
loss = classify_loss + 0.001 * regularization_loss # 引入L1正则化项
L2范数
L2范数是参数矩阵W中元素的平方之和,这使得参数矩阵中的元素更稀疏,与前两个范数不同的是,它不会让参数变为0,而是使得参数大部分都接近于0。L1追求稀疏化,从而丢弃了一部分特征(参数为0),而L2范数只是使参数尽可能为0,保留了特征。L2被称为Rigde.
criterion = torch.nn.BCELoss() #定义损失函数
optimizer = torch.optim.SGD(model.parameters(),lr = 0.01, momentum=0, dampening=0,weight_decay=0) #weight_decay 表示使用L2正则化
3.Dropout的numpy实现
import numpy as np X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ]) y = np.array([[0,1,1,0]]).T alpha,hidden_dim,dropout_percent,do_dropout = (0.5,4,0.2,True) synapse_0 = 2*np.random.random((3,hidden_dim)) - 1 synapse_1 = 2*np.random.random((hidden_dim,1)) - 1 for j in xrange(60000): layer_1 = (1/(1+np.exp(-(np.dot(X,synapse_0))))) if(do_dropout): layer_1 *= np.random.binomial([np.ones((len(X),hidden_dim))],1-dropout_percent)[0] * (1.0/(1-dropout_percent)) layer_2 = 1/(1+np.exp(-(np.dot(layer_1,synapse_1)))) layer_2_delta = (layer_2 - y)*(layer_2*(1-layer_2)) layer_1_delta = layer_2_delta.dot(synapse_1.T) * (layer_1 * (1-layer_1)) synapse_1 -= (alpha * layer_1.T.dot(layer_2_delta)) synapse_0 -= (alpha * X.T.dot(layer_1_delta))
4.完整代码
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn.init as init
import math
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import numpy as np
import pandas as pd
%matplotlib inline # 导入数据
data = pd.read_csv(r'C:\Users\betty\Desktop\pytorch学习\data.txt')
x, y = data.ix[:,:8],data.ix[:,-1] #测试集为30%,训练集为80%
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0) x_train = Variable(torch.from_numpy(np.array(x_train)).float())
y_train = Variable(torch.from_numpy(np.array(y_train).reshape(-1, 1)).float()) x_test = Variable(torch.from_numpy(np.array(x_test)).float())
y_test= Variable(torch.from_numpy(np.array(y_test).reshape(-1,1)).float()) print(x_train.data.shape)
print(y_train.data.shape) print(x_test.data.shape)
print(y_test.data.shape) class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.l1 = torch.nn.Linear(8, 200)
self.l2 = torch.nn.Linear(200, 50)
self.l3 = torch.nn.Linear(50, 1) def forward(self, x):
out1 = F.relu(self.l1(x))
out2 = F.dropout(out1, p= 0.5)
out3 = F.relu(self.l2(out2))
out4 = F.dropout(out3, p=0.5)
y_pred = F.sigmoid(self.l3(out3))
return y_pred model = Model() criterion = torch.nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.1) Loss=[]
for epoch in range(2000):
y_pred = model(x_train)
loss = criterion(y_pred, y_train)
if epoch % 400 == 0:
print("epoch =", epoch, "loss", loss.item())
Loss.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step() # 模型评估
def label_flag(data):
for i in range(len(data)):
if(data[i]>0.5):
data[i] = 1.0
else:
data[i] = 0.0
return data y_pred = label_flag(y_pred)
print(classification_report(y_train.detach().numpy(), y_pred.detach().numpy())) # 测试
y_test_pred = model(x_test)
y_test_pred = label_flag(y_test_pred)
print(classification_report(y_test.detach().numpy(), y_test_pred.detach().numpy()))
数据集下载链接:链接:https://pan.baidu.com/s/1LrJktjVQ1OM9mYt_cuE-FQ
提取码:hatv
原文链接:https://blog.csdn.net/wehung/article/details/89283583
Task5.PyTorch实现L1,L2正则化以及Dropout的更多相关文章
- 防止过拟合:L1/L2正则化
正则化方法:防止过拟合,提高泛化能力 在训练数据不够多时,或者overtraining时,常常会导致overfitting(过拟合).其直观的表现如下图所示,随着训练过程的进行,模型复杂度增加,在tr ...
- ML-线性模型 泛化优化 之 L1 L2 正则化
认识 L1, L2 从效果上来看, 正则化通过, 对ML的算法的任意修改, 达到减少泛化错误, 但不减少训练误差的方式的统称 训练误差 这个就损失函数什么的, 很好理解. 泛化错误 假设 我们知道 预 ...
- 机器学习中L1,L2正则化项
搞过机器学习的同学都知道,L1正则就是绝对值的方式,而L2正则是平方和的形式.L1能产生稀疏的特征,这对大规模的机器学习灰常灰常重要.但是L1的求解过程,实在是太过蛋疼.所以即使L1能产生稀疏特征,不 ...
- L0,L1,L2正则化浅析
在机器学习的概念中,我们经常听到L0,L1,L2正则化,本文对这几种正则化做简单总结. 1.概念 L0正则化的值是模型参数中非零参数的个数. L1正则化表示各个参数绝对值之和. L2正则化标识各个参数 ...
- L1,L2正则化代码
# L1正则 import numpy as np from sklearn.linear_model import Lasso from sklearn.linear_model import SG ...
- L1和L2正则化(转载)
[深度学习]L1正则化和L2正则化 在机器学习中,我们非常关心模型的预测能力,即模型在新数据上的表现,而不希望过拟合现象的的发生,我们通常使用正则化(regularization)技术来防止过拟合情况 ...
- TensorFlow之DNN(三):神经网络的正则化方法(Dropout、L2正则化、早停和数据增强)
这一篇博客整理用TensorFlow实现神经网络正则化的内容. 深层神经网络往往具有数十万乃至数百万的参数,可以进行非常复杂的特征变换,具有强大的学习能力,因此容易在训练集上过拟合.缓解神经网络的过拟 ...
- 机器学习之正则化【L1 & L2】
前言 L1.L2在机器学习方向有两种含义:一是L1范数.L2范数的损失函数,二是L1.L2正则化 L1范数.L2范数损失函数 L1范数损失函数: L2范数损失函数: L1.L2分别对应损失函数中的绝对 ...
- 机器学习中的L1、L2正则化
目录 1. 什么是正则化?正则化有什么作用? 1.1 什么是正则化? 1.2 正则化有什么作用? 2. L1,L2正则化? 2.1 L1.L2范数 2.2 监督学习中的L1.L2正则化 3. L1.L ...
随机推荐
- 阶段3 1.Mybatis_06.使用Mybatis完成DAO层的开发_8 properties标签的使用及细节
properties 可以把数据库链接的配置放在上面的properties里面 #{占位符}的形式去引用上面的.下面的内容就是引用上面的内容的定义. 运行查询的方法测试一下 这样改造可以成功的运行程序 ...
- 阶段3 1.Mybatis_01.Mybatis课程介绍及环境搭建_06.mybatis的环境搭建
创建实体类,实现Serializable接口 属性名和数据库的字段名保持一致 Date字段需要导入包 生成gettter和setter,再生成一个ToString的方法 创建持久层Dao 创建接口 里 ...
- SAP屏幕事件的控制
1. INITALIZATION事件 该事件在屏幕未显示之前执行,对程序设置值及屏幕元素进行初始化赋值. REPORT Y001. PARAMETERS QUAL_DAY TYPE D DEFAUL ...
- 【EWM系列】SAP EWM凭证对象表概览
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[EWM系列]SAP EWM凭证对象表概览 ...
- 【QT开发】QT在windows下的exe应用程序如何在别人的电脑上直接运行
当你利用QT编译了一个可执行程序,需要将这个可执行程序拷贝到别人的电脑上运行,这个时候除了这个可执行程序外,还需要支持的库才可用运行.一般来说通过下面的方法可以实现. 首先,需要看你用的是什 ...
- 开篇——从程序员到IT经理
2002年~2005年我在广州的广东水力电力职业技术学院求学,主修网络工程.求学期间,我从事最多的就是玩游戏,当时就是玩MU和CS,所以有一门编程课叫C语言的“肥佬”(广东话)了,要补考,没办法,于是 ...
- 循环结构 :for
循环结构 :for 循环四要素: 1.初始化条件 2.循环条件 3.循环体 4.迭代条件 格式: for(初始化条件;循环条件;迭代条件){ 循环体; } 执行顺序 :1 -> 2 -> ...
- linux中断处理上下部分
一.linux中断处理为什么要分为上下部 1.1. 中断处理的上半部(top half,又叫顶半部)和处理的下半部(bottom half,又叫底半部) 1.1. linux中断处理不参与调度,故中断 ...
- 遍历文件夹下的csv,把数据读进一张表
import pandas as pd import os if __name__ == '__main__': Path = 'c:\checklog' dfs = [] for dir_path, ...
- Python环境配置:anaconda+pycharm一站式解决
https://www.cnblogs.com/yuxuefeng/p/9235431.html 不错的博文,码一下.