丢弃法——pytroch版
import torch
from torch import nn
from d2l import torch as d2l
def dropout_layer(x,dropout):
assert 0<= dropout <=1
if dropout ==1:
return torch.zeros_like(x)
if dropout == 0:
return x
# 取0-1上的均匀随机分布,>dropout则=1,否则=0
mask = (torch.rand(x.shape)>dropout).float()
print('开始')
print(x.shape)
print(torch.rand(x.shape))
print(torch.rand(x.shape)>dropout)
print(mask)
print(mask*x)
print(1.0-dropout)
return mask*x/(1.0-dropout)
# 测试dropout_layer函数
x = torch.arange(16,dtype=torch.float32).reshape((2,8))
print(x)
print(dropout_layer(x,0.))
print(dropout_layer(x,0.5))
print(dropout_layer(x,1.))
num_inputs,num_outputs,num_hiddens1,num_hidden2 = 784,10,256,256
dropout1,dropout2 = 0.2,0.5
class Net(nn.Module):
def __init__(self, num_inputs,num_outputs,num_hiddens1,num_hiddens2,is_training = True):
super(Net,self).__init__()
self.num_inputs = num_inputs
self.training = is_training
self.lin1 = nn.Linear(num_inputs,num_hiddens1)
self.lin2 = nn.Linear(num_hiddens1,num_hiddens2)
self.lin3 = nn.Linear(num_hiddens2,num_outputs)
self.relu = nn.ReLU()
def forward(self,x):
h1 = self.relu(self.lin1(x.reshape((-1,self.num_inputs))))
# 只有在训练模型时才使用dropout
if self.training == True:
# 在第一个全连接层之后添加一个dropout层
h1 = dropout_layer(h1,dropout1)
h2 = self.training == True
if self.training == True:
# 在第二个全连接层之后添加一个dropout层
h2 = dropout_layer(h2,dropout2)
out = self.lin3(h2)
return out
net = Net(num_inputs,num_outputs,num_hiddens1,num_hidden2)
num_epochs,lr,batch_size=10,0.5,256
loss = nn.CrossEntropyLoss(reduction='none')
train_iter,test_iter = d2l.load_data_fashion_mnist(batch_size)
trainer = torch.optim.SGD(net.parameters(),lr=lr)
d2l.train_ch3(net,train_iter,test_iter,loss,num_epochs,trainer)
作者:Jace Jin
github地址:https://github.com/buxianghua
原创文章版权归作者所有.
欢迎转载,转载时请在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
欢迎转载,转载时请在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.