佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Pytorch實現(xiàn)全連接層的操作

Pytorch實現(xiàn)全連接層的操作

熱門標簽:企業(yè)做大做強 百度AI接口 呼叫中心市場需求 電話運營中心 客戶服務 硅谷的囚徒呼叫中心 語音系統(tǒng) Win7旗艦版

全連接神經網絡(FC)

全連接神經網絡是一種最基本的神經網絡結構,英文為Full Connection,所以一般簡稱FC。

FC的準則很簡單:神經網絡中除輸入層之外的每個節(jié)點都和上一層的所有節(jié)點有連接。

以上一次的MNIST為例

import torch
import torch.utils.data
from torch import optim
from torchvision import datasets
from torchvision.transforms import transforms
import torch.nn.functional as F
batch_size = 200
learning_rate = 0.001
epochs = 20
train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('mnistdata', train=True, download=False,
                   transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('mnistdata', train=False, download=False,
                   transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=batch_size, shuffle=True)
w1, b1 = torch.randn(200, 784, requires_grad=True), torch.zeros(200, requires_grad=True)
w2, b2 = torch.randn(200, 200, requires_grad=True), torch.zeros(200, requires_grad=True)
w3, b3 = torch.randn(10, 200, requires_grad=True), torch.zeros(10, requires_grad=True)
torch.nn.init.kaiming_normal_(w1)
torch.nn.init.kaiming_normal_(w2)
torch.nn.init.kaiming_normal_(w3)
def forward(x):
    x = x@w1.t() + b1
    x = F.relu(x)
    x = x@w2.t() + b2
    x = F.relu(x)
    x = x@w3.t() + b3
    x = F.relu(x)
    return x
optimizer = optim.Adam([w1, b1, w2, b2, w3, b3], lr=learning_rate)
criteon = torch.nn.CrossEntropyLoss()
for epoch in range(epochs):
    for batch_idx, (data, target) in enumerate(train_loader):
        data = data.view(-1, 28*28)
        logits = forward(data)
        loss = criteon(logits, target)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if batch_idx % 100 == 0:
            print('Train Epoch : {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx*len(data), len(train_loader.dataset),
                100.*batch_idx/len(train_loader), loss.item()
            ))
    test_loss = 0
    correct = 0
    for data, target in test_loader:
        data = data.view(-1, 28*28)
        logits = forward(data)
        test_loss += criteon(logits, target).item()
        pred = logits.data.max(1)[1]
        correct += pred.eq(target.data).sum()
    test_loss /= len(test_loader.dataset)
    print('\nTest set : Averge loss: {:.4f}, Accurancy: {}/{}({:.3f}%)'.format(
        test_loss, correct, len(test_loader.dataset),
        100.*correct/len(test_loader.dataset)
        ))

我們將每個w和b都進行了定義,并且自己寫了一個forward函數(shù)。如果我們采用了全連接層,那么整個代碼也會更加簡介明了。

首先,我們定義自己的網絡結構的類:

class MLP(nn.Module):
    def __init__(self):
        super(MLP, self).__init__()
        self.model = nn.Sequential(
            nn.Linear(784, 200),
            nn.LeakyReLU(inplace=True),
            nn.Linear(200, 200),
            nn.LeakyReLU(inplace=True),
            nn.Linear(200, 10),
            nn.LeakyReLU(inplace=True)
        )
    def forward(self, x):
        x = self.model(x)
        return x

它繼承于nn.Moudle,并且自己定義里整個網絡結構。

其中inplace的作用是直接復用存儲空間,減少新開辟存儲空間。

除此之外,它可以直接進行運算,不需要手動定義參數(shù)和寫出運算語句,更加簡便。

同時我們還可以發(fā)現(xiàn),它自動完成了初試化,不需要像之前一樣再手動寫一個初始化了。

區(qū)分nn.Relu和F.relu()

前者是一個類的接口,后者是一個函數(shù)式接口。

前者都是大寫的,并且調用的的時候需要先實例化才能使用,而后者是小寫的可以直接使用。

最重要的是后者的自由度更高,更適合做一些自己定義的操作。

完整代碼

import torch
import torch.utils.data
from torch import optim, nn
from torchvision import datasets
from torchvision.transforms import transforms
import torch.nn.functional as F
batch_size = 200
learning_rate = 0.001
epochs = 20
train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('mnistdata', train=True, download=False,
                   transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('mnistdata', train=False, download=False,
                   transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=batch_size, shuffle=True)
class MLP(nn.Module):
    def __init__(self):
        super(MLP, self).__init__()
        self.model = nn.Sequential(
            nn.Linear(784, 200),
            nn.LeakyReLU(inplace=True),
            nn.Linear(200, 200),
            nn.LeakyReLU(inplace=True),
            nn.Linear(200, 10),
            nn.LeakyReLU(inplace=True)
        )
    def forward(self, x):
        x = self.model(x)
        return x
device = torch.device('cuda:0')
net = MLP().to(device)
optimizer = optim.Adam(net.parameters(), lr=learning_rate)
criteon = nn.CrossEntropyLoss().to(device)
for epoch in range(epochs):
    for batch_idx, (data, target) in enumerate(train_loader):
        data = data.view(-1, 28*28)
        data, target = data.to(device), target.to(device)
        logits = net(data)
        loss = criteon(logits, target)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if batch_idx % 100 == 0:
            print('Train Epoch : {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx*len(data), len(train_loader.dataset),
                100.*batch_idx/len(train_loader), loss.item()
            ))
    test_loss = 0
    correct = 0
    for data, target in test_loader:
        data = data.view(-1, 28*28)
        data, target = data.to(device), target.to(device)
        logits = net(data)
        test_loss += criteon(logits, target).item()
        pred = logits.data.max(1)[1]
        correct += pred.eq(target.data).sum()
    test_loss /= len(test_loader.dataset)
    print('\nTest set : Averge loss: {:.4f}, Accurancy: {}/{}({:.3f}%)'.format(
        test_loss, correct, len(test_loader.dataset),
        100.*correct/len(test_loader.dataset)
        ))

補充:pytorch 實現(xiàn)一個隱層的全連接神經網絡

torch.nn 實現(xiàn) 模型的定義,網絡層的定義,損失函數(shù)的定義。

import torch
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
# Use the nn package to define our model as a sequence of layers. nn.Sequential
# is a Module which contains other Modules, and applies them in sequence to
# produce its output. Each Linear Module computes output from input using a
# linear function, and holds internal Tensors for its weight and bias.
model = torch.nn.Sequential(
    torch.nn.Linear(D_in, H),
    torch.nn.ReLU(),
    torch.nn.Linear(H, D_out),
)
# The nn package also contains definitions of popular loss functions; in this
# case we will use Mean Squared Error (MSE) as our loss function.
loss_fn = torch.nn.MSELoss(reduction='sum')
learning_rate = 1e-4
for t in range(500):
    # Forward pass: compute predicted y by passing x to the model. Module objects
    # override the __call__ operator so you can call them like functions. When
    # doing so you pass a Tensor of input data to the Module and it produces
    # a Tensor of output data.
    y_pred = model(x)
    # Compute and print loss. We pass Tensors containing the predicted and true
    # values of y, and the loss function returns a Tensor containing the
    # loss.
    loss = loss_fn(y_pred, y)
    print(t, loss.item())
    # Zero the gradients before running the backward pass.
    model.zero_grad()
    # Backward pass: compute gradient of the loss with respect to all the learnable
    # parameters of the model. Internally, the parameters of each Module are stored
    # in Tensors with requires_grad=True, so this call will compute gradients for
    # all learnable parameters in the model.
    loss.backward()
    # Update the weights using gradient descent. Each parameter is a Tensor, so
    # we can access its gradients like we did before.
    with torch.no_grad():
        for param in model.parameters():
            param -= learning_rate * param.grad

上面,我們使用parem= -= learning_rate* param.grad 手動更新參數(shù)。

使用torch.optim 自動優(yōu)化參數(shù)。optim這個package提供了各種不同的模型優(yōu)化方法,包括SGD+momentum, RMSProp, Adam等等。

optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for t in range(500):
    y_pred = model(x)
    loss = loss_fn(y_pred, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

您可能感興趣的文章:
  • pytorch_detach 切斷網絡反傳方式
  • pytorch 禁止/允許計算局部梯度的操作
  • 如何利用Pytorch計算三角函數(shù)
  • 聊聊PyTorch中eval和no_grad的關系
  • Pytorch實現(xiàn)圖像識別之數(shù)字識別(附詳細注釋)
  • pytorch 優(yōu)化器(optim)不同參數(shù)組,不同學習率設置的操作
  • PyTorch 如何將CIFAR100數(shù)據按類標歸類保存
  • PyTorch的Debug指南
  • Python深度學習之使用Pytorch搭建ShuffleNetv2
  • win10系統(tǒng)配置GPU版本Pytorch的詳細教程
  • 淺談pytorch中的nn.Sequential(*net[3: 5])是啥意思
  • pytorch visdom安裝開啟及使用方法
  • PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程)
  • pytorch中的nn.ZeroPad2d()零填充函數(shù)實例詳解
  • 使用pytorch實現(xiàn)線性回歸
  • pytorch實現(xiàn)線性回歸以及多元回歸
  • PyTorch學習之軟件準備與基本操作總結

標簽:海南 山西 濟南 長沙 喀什 崇左 安康 山西

巨人網絡通訊聲明:本文標題《Pytorch實現(xiàn)全連接層的操作》,本文關鍵詞  ;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    通城县| 大石桥市| 三都| 邢台市| 台安县| 嘉黎县| 巨鹿县| 沈丘县| 积石山| 望谟县| 丰台区| 德格县| 万山特区| 洪湖市| 息烽县| 灵台县| 越西县| 邯郸市| 应用必备| 红河县| 修水县| 雷波县| 石门县| 吴桥县| 苏尼特右旗| 麦盖提县| 吉安县| 慈溪市| 环江| 石渠县| 谷城县| 盘山县| 鹤岗市| 南昌县| 文昌市| 景德镇市| 宁阳县| 韶山市| 改则县| 子洲县| 安福县|