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 ...
随机推荐
- web可拖动控件js
先下载:http://code.jquery.com/ui/1.10.3/jquery-ui.js $('.i-i-yuan').draggable({ containment: '#app'//可通 ...
- php7.2 下安装swoole扩展
git clone git@github.com:swoole/swoole-src.git phpize ./configure make && make test make ins ...
- python字符串的学习计划
python字符串有14小节内容, 计划7天学完吧(不知道能完成不) 今天依然是在禅道上写用例的一天 禅道上的用例,编写的时候比较方便 修改维护的时候,有点小麻烦(没有在Excel表中容易修改) D5 ...
- 【ABAP系列】SAP ABAP 控制ALV单元格编辑后获取新的数值
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP ABAP 控制ALV单元 ...
- codeforces 1186C Vus the Cossack and Strings
题目链接:https://codeforc.es/contest/1186/problem/C 题目大意:xxxxx(自认为讲不清.for instance) 例如:a="01100010& ...
- Windows.etc\hosts文件
ZC:就是将 后面的项 重定位到 前面的项 1.目录:"C:\Windows\System32\drivers\etc" 文件:"C:\Windows\System32\ ...
- net 架构师-数据库-sql server-001-SQL Server中的对象
1.1 数据库的构成 1.2 数据库对象概述 1.2.1 数据库对象 RDBMS 关系数据库管理系统 对象:数据库.索引.事务日志.CLR程序集.表 .报表.文件组.全文目录.图表.用户自定义数据类型 ...
- Nginx 3.使用配置
转 https://www.cnblogs.com/wcwnina/p/9946747.html 本文只针对Nginx在不加载第三方模块的情况能处理哪些事情,由于第三方模块太多所以也介绍不完,当然本文 ...
- nginx下载安装和虚拟机的配置
一. Nginx下载安装 1.Nginx下载:nginx-1.13.0.tar.gz,下载到:/usr/local/software/ wget http://nginx.org/download/n ...
- pureftp安装
1.下载 #cd /usr/local/src #wget http://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.36.t ...