Pytorch中的NN模塊并實(shí)現(xiàn)第一個神經(jīng)網(wǎng)絡(luò)模型
在PyTorch建立模型,主要是NN模塊。
nn.Linear
nn.Linear是創(chuàng)建一個線性層。這里需要將輸入和輸出維度作為參數(shù)傳遞。
- linear = nn.Linear(10, 2)
 - example_input = torch.randn(3, 10)
 - example_output = linear(example_input)
 - example_output
 
上面代碼linear接受nx10的輸入并返回nx2的輸出。
- print(example_input)
 - print(example_output)
 - tensor([[ 1.1122, -0.1381, 0.5547, -0.3326, -0.5676, 0.2810, -0.5521, -0.8729,
 - -0.6627, 0.8729],
 - [ 1.9134, 0.2397, -0.8340, 1.1532, -1.6725, 0.6171, -0.0357, -1.6848,
 - -0.8454, 0.3876],
 - [-0.0786, -0.1541, -0.8385, -0.1587, -0.0121, 1.4457, -0.0132, 1.5653,
 - -1.6954, -0.9350]])
 - # 輸出如下
 - tensor([[-0.1249, -0.8002],
 - [-1.0945, -0.2297],
 - [-0.3558, 0.8439]], grad_fn=<AddmmBackward>)
 
nn.Relu
nn.Relu對線性的給定輸出執(zhí)行 relu 激活函數(shù)操作。
- relu = nn.ReLU()
 - relu_output = relu(example_output)
 - relu_output
 - # 輸出如下
 - tensor([[0.0000, 0.0000],
 - [0.0000, 0.0000],
 - [0.0000, 0.8439]], grad_fn=<ReluBackward0>)
 
nn.BatchNorm1d
nn.BatchNorm1d是一種標(biāo)準(zhǔn)化技術(shù),用于在不同批次的輸入中保持一致的均值和標(biāo)準(zhǔn)偏差。
- batchnorm = nn.BatchNorm1d(2)
 - batchnorm_output = batchnorm(relu_output)
 - batchnorm_output
 - # 輸出如下
 - tensor([[ 0.0000, -0.7071],
 - [ 0.0000, -0.7071],
 - [ 0.0000, 1.4142]], grad_fn=<NativeBatchNormBackward>)
 
nn.Sequential
nn.Sequential一次性創(chuàng)建一系列操作。和tensorflow中的Sequential完全一樣。
- mlp_layer = nn.Sequential(
 - nn.Linear(5, 2),
 - nn.BatchNorm1d(2),
 - nn.ReLU()
 - )
 - test_example = torch.randn(5,5) + 1
 - print("input: ")
 - print(test_example)
 - print("output: ")
 - print(mlp_layer(test_example))
 - # 輸出如下
 - input:
 - tensor([[ 1.4617, 1.2446, 1.4919, 1.5978, -0.3410],
 - [-0.2819, 0.5567, 1.0113, 1.8053, -0.0833],
 - [ 0.2830, 1.0857, 1.2258, 2.6602, 0.1339],
 - [ 0.8682, 0.9344, 1.3715, 0.0279, 1.8011],
 - [ 0.6172, 1.1414, 0.6030, 0.3876, 1.3653]])
 - output:
 - tensor([[0.0000, 0.0000],
 - [0.0000, 1.3722],
 - [0.0000, 0.8861],
 - [1.0895, 0.0000],
 - [1.3047, 0.0000]], grad_fn=<ReluBackward0>)
 
在上面的模型中缺少了優(yōu)化器,我們無法得到對應(yīng)損失。
- import torch.optim as optim
 - adam_opt = optim.Adam(mlp_layer.parameters(), lr=1e-1)
 - # 這里lr表示學(xué)習(xí)率,1e-1表示0.1
 - train_example = torch.randn(100,5) + 1
 - adam_opt.zero_grad()
 - # 我們將使用1減去平均值,作為簡單損失函數(shù)
 - cur_loss = torch.abs(1 - mlp_layer(train_example)).mean()
 - cur_loss.backward()
 - # 更新參數(shù)
 - adam_opt.step()
 - print(cur_loss.data)
 - # 輸出如下
 - tensor(0.7467)
 
雖然上面只是用了一個epoch,訓(xùn)練線性模型得到loss為0.7467,上面就是NN模型建立model的整個流程,
第一個神經(jīng)網(wǎng)絡(luò)模型
下面實(shí)現(xiàn)第一個分類神經(jīng)網(wǎng)絡(luò),其中一個隱藏層用于開發(fā)單個輸出單元。
首先,使用以下命令導(dǎo)入 PyTorch 庫 -
- import torch
 - import torch.nn as nn
 
定義所有層和批量大小以開始執(zhí)行神經(jīng)網(wǎng)絡(luò),如下所示 -
- n_in, n_h, n_out, batch_size = 10, 5, 1, 10
 
由于神經(jīng)網(wǎng)絡(luò)包括輸入數(shù)據(jù)的組合以獲得相應(yīng)的輸出數(shù)據(jù),我們將遵循以下相同的程序 -
- x = torch.randn(batch_size, n_in)
 - y = torch.tensor([[1.0], [0.0], [0.0],
 - [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]])
 
創(chuàng)建順序模型。使用下面代碼,創(chuàng)建一個順序模型 -
- model = nn.Sequential(nn.Linear(n_in, n_h),
 - nn.ReLU(),
 - nn.Linear(n_h, n_out),
 - nn.Sigmoid())
 
借助梯度下降優(yōu)化器構(gòu)建損失函數(shù),如下所示 -
- # 構(gòu)造損失函數(shù)
 - criterion = torch.nn.MSELoss()
 - # 構(gòu)造優(yōu)化器
 - optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)
 
使用給定代碼行的迭代循環(huán)實(shí)現(xiàn)梯度下降模型 -
- # 梯度下降
 - for epoch in range(50):
 - # 正向傳遞:通過將x傳遞給模型來計(jì)算預(yù)測的y
 - y_pred = model(x)
 - # 計(jì)算loss
 - loss = criterion(y_pred, y)
 - # 梯度清0
 - optimizer.zero_grad()
 - # 反向傳播,求解梯度
 - loss.backward()
 - # 更新模型參數(shù)
 - optimizer.step()
 - if epoch % 10 == 0:
 - print('epoch: ', epoch,' loss: ', loss.item())
 
輸出如下
- epoch: 0 loss: 0.2508794665336609
 - epoch: 10 loss: 0.24847669899463654
 - epoch: 20 loss: 0.24615907669067383
 - epoch: 30 loss: 0.24392127990722656
 - epoch: 40 loss: 0.24175791442394257
 
【編輯推薦】
















 
 
 














 
 
 
 