짜증내지 마. - 파이터치 학습 노트[1]

4734 단어

1. Numpy VS Torch

# 
np_data = torch_data.numpy()
torch_data = torch.from_numpy(np_data)
#abs
data = [1, 2, -2, -1] #array
tensor = torch.FloatTensor(data) #32bit  
np.abs(data); torch.abs(tensor);
# 
data.dot(data) # numpy data data=np.array(data)
torch.mm(tensor, tensor)

2. Variable

# 
from torch.autograd import Variable
# 
variable = Varible(tensor, requires_grad=True)
variable.data #type tensor

3. Activation Function 인센티브 함수


그림 그리기
# 
import torch.nn.function as F
import matplotlib.pyplot as plt
#fake data
x = torch.linspace(-5, 5, 200)
x = Variable(x)
x_np = x.data.numpy() ***
#activation
y_relu = F.relu(x).data.numpy() ***

plt.plot(x_np, y_relu, c='red', label='relu')

4. Regression 컴백

#  
plt.ion()
plt.show()

#for if 
  plt.cla()
  plt.scatter(x.data.numpy(), y.data.numpy())
  plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
  plt.text(0.5, 0, 'Loss=%.4f' % loss.data, fontdict={'size':20, 'color': 'red'})
  plt.pause(0.1)
  
#for 
plt.ioff()
plt.show()

#net regression !

5. Classification 분류

#       
n_data = torch.ones(100, 2) # shape(100, 2)
x0 = torch.normal(2*n_data, 1)
y0 = torch.zeros(100)
x1 = torch.normal(-2*n_data, 1)
y1 = torch.ones(100)
x = torch.cat((x0, x1), 0).type(torch.FloatTensor)
y = torch.cat((y0, y1)).type(torch.LongTensor) #label  integer 

x, y = Variable(x), Variable(y)

plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn')
plt.show()

#  hiddenlayer10   
net = Net(2, 10, 2)

# 
loss_func = torch.nn.CrossEntropyLoss()

#for   out   prediction
out = net(x) # out 
loss = loss_func(out, y) # 

prediction = torch.max(F.softmax(out), 1)[1] #   softmax  
accuracy = sum(pre_y == target_y) / 200 # 

6. 빠른 구축법

net = torch.nn.Sequential(
    torch.nn.Linear(2, 10),
    torch.nn.ReLU(),
    torch.nn.Linear(10, 2)
)

7. 추출 저장


두 가지 방식으로 전체 신경 네트워크를 추출합니다. 전체 네트워크를 추출하거나 파라미터만 추출합니다.
save에 저장하고 restore에서 추출하고 마지막으로 표시합니다.
def save():
  # #
  # #
  # 
  torch.save(net1, 'net.pkl') # 
  torch.save(net1.state_dict(), 'net_params.pkl') # 

# 
def restore_net():
  net2 = torch.load('net.pkl')
  prediction = net2(x)
  
# 
def restore_params():
  net3 = ... #net3 = net1
  net3.load_state_dict(torch.load('net_params.pkl'))
  prediction = net3(x)
  
# 
save()
restore_net()
restore_params()

8. 배치 데이터 트레이닝

# 
import torch.utils.data as Data
#  batchsize
BATCH_SIZE = 5
#  torch Dataset
torch_dataset = Data.TensorDataset(x, y) #(1)
loader = Data.DataLoader(...)
#for 
for step, (batch_x, batch_y) in enumerate(loader):
# loader 
if __name__ == '__main__': # 
  #(1)

9. Optimizer 최적화기

# 
net_SGD         = Net()
net_Momentum    = Net()
net_RMSprop     = Net()
net_Adam        = Net()
nets = [net_SGD, net_Momentum, net_RMSprop, net_Adam]

# , loss_func 
opt_SGD         = torch.optim.SGD(net_SGD.parameters(), lr=LR)
opt_Momentum    = torch.optim.SGD(net_Momentum.parameters(), lr=LR, momentum=0.8)
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))
optimizers = [opt_SGD, opt_Momentum, opt_RMSprop, opt_Adam]

loss_func = torch.nn.MSELoss()
losses_his = [[], [], [], []]   #   training   loss

# , 
for epoch in range(EPOCH):
    print('Epoch: ', epoch)
    for step, (b_x, b_y) in enumerate(loader):
        for net, opt, l_his in zip(nets, optimizers, losses_his): # 
            output = net(b_x)              # get output for every net
            loss = loss_func(output, b_y)  # compute loss for every net
            opt.zero_grad()                # clear gradients for next train
            loss.backward()                # backpropagation, compute gradients
            opt.step()                     # apply gradients
            l_his.append(loss.data.numpy())     # loss recoder
            
# 
labels = ['SGD', 'Momentum', 'RMSprop', 'Adam']
for i, l_his in enumerate(losses_his):
    plt.plot(l_his, label=labels[i])
plt.legend(loc='best')
plt.xlabel('Steps')
plt.ylabel('Loss')
plt.ylim((0, 0.2))
plt.show()

좋은 웹페이지 즐겨찾기