PyTorch基本用法(九)——オプティマイザ
作者:Tyan博客:noahsnail.com|CSDN|簡書
本文は主にPyTorchのいくつかの使い方についてです.
https://www.youtube.com/user/MorvanZhou
本文は主にPyTorchのいくつかの使い方についてです.
import torch
import matplotlib.pyplot as plt
import torch.nn.functional as F
import torch.utils.data as Data
from torch.autograd import Variable
#
LR = 0.01
BATCH_SIZE = 32
EPOCH = 10
#
x = torch.unsqueeze(torch.linspace(-1, 1, 1000), dim = 1)
y = x.pow(2) + 0.1 * torch.normal(torch.zeros(x.size()))
#
plt.scatter(x.numpy(), y.numpy())
plt.show()
#
dataset = Data.TensorDataset(data_tensor = x, target_tensor = y)
#
loader = Data.DataLoader(dataset = dataset, batch_size = BATCH_SIZE, shuffle = True, num_workers = 2)
# pytorch
class Net(torch.nn.Module):
def __init__(self, n_features, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_features, n_hidden)
self.predict = torch.nn.Linear(n_hidden, n_output)
def forward(self, x):
x = F.relu(self.hidden(x))
y = self.predict(x)
return y
#
net_SGD = Net(1, 10, 1)
net_Momentum = Net(1, 10, 1)
net_RMSprop = Net(1, 10, 1)
net_Adam = Net(1, 10, 1)
#
opt_SGD = torch.optim.SGD(net_SGD.parameters(), lr = LR)
opt_Momentum = torch.optim.SGD(net_Momentum.parameters(), lr = LR, momentum = 0.9)
opt_RMSprop = torch.optim.RMSprop(net_RMSprop.parameters(), lr = LR, alpha = 0.9)
opt_Adam = torch.optim.Adam(net_Adam.parameters(), lr = LR, betas= (0.9, 0.99))
nets = [net_SGD, net_Momentum, net_RMSprop, net_Adam]
optimizers = [opt_SGD, opt_Momentum, opt_RMSprop, opt_Adam]
#
loss_func = torch.nn.MSELoss()
# loss
loss_SGD = []
loss_Momentum = []
loss_RMSprop =[]
loss_Adam = []
# loss
losses = [loss_SGD, loss_Momentum, loss_RMSprop, loss_Adam]
#
for epoch in xrange(EPOCH):
for step, (batch_x, batch_y) in enumerate(loader):
var_x = Variable(batch_x)
var_y = Variable(batch_y)
for net, optimizer, loss_history in zip(nets, optimizers, losses):
# x
prediction = net(var_x)
#
loss = loss_func(prediction, var_y)
#
optimizer.zero_grad()
#
loss.backward()
#
optimizer.step()
# loss
loss_history.append(loss.data[0])
#
labels = ['SGD', 'Momentum', 'RMSprop', 'Adam']
for i, loss_history in enumerate(losses):
plt.plot(loss_history, label = labels[i])
plt.legend(loc = 'best')
plt.xlabel('Steps')
plt.ylabel('Loss')
plt.ylim((0, 0.2))
plt.show()