pytorch入門學習(三) 神經網路

2021-08-28 13:42:12 字數 1510 閱讀 4780

神經網路可以使用torch.nn包構建.

autograd實現了反向傳播功能, 但是直接用來寫深度學習的**在很多情況下還是稍顯複雜,torch.nn是專門為神經網路設計的模組化介面.nn構建於autograd之上, 可用來定義和執行神經網路.nn.modulenn中最重要的類, 可把它看成是乙個網路的封裝, 包含網路各層定義以及forward方法, 呼叫forward(input)方法, 可返回前向傳播的結果.

乙個典型的神經網路訓練過程如下:

讓我們來定義乙個網路:

import torch

from torch.autograd import variable

import torch.nn as nn

import torch.nn.functional as f

class net(nn.module):

def __init__(self):

super(net, self).__init__()

# 卷積層 '1'表示輸入為單通道, '6'表示輸出通道數, '5'表示卷積核為5*5

# 核心

self.conv1 = nn.conv2d(1, 6, 5)

self.conv2 = nn.conv2d(6, 16, 5)

# 仿射層/全連線層: y = wx + b

self.fc1 = nn.linear(16 * 5 * 5, 120)

self.fc2 = nn.linear(120, 84)

self.fc3 = nn.linear(84, 10)

def forward(self, x):

#在由多個輸入平面組成的輸入訊號上應用2d最大池化.

# (2, 2) 代表的是池化操作的步幅

x = f.max_pool2d(f.relu(self.conv1(x)), (2, 2))

# 如果大小是正方形, 則只能指定乙個數字

x = f.max_pool2d(f.relu(self.conv2(x)), 2)

x = x.view(-1, self.num_flat_features(x))

x = f.relu(self.fc1(x))

x = f.relu(self.fc2(x))

x = self.fc3(x)

return x

def num_flat_features(self, x):

size = x.size()[1:] # 除批量維度外的所有維度

num_features = 1

for s in size:

num_features *= s

return num_features

net = net()

print(net)

如何入門Pytorch之三 如何優化神經網路

在上一節中,我們介紹了如何使用pytorch來搭建乙個經典的分類神經網路。在本節中,我們將介紹從資料集到模型各個部分的調整,從而可以有乙個完整的解決思路。1 資料集部分 1.1 資料集劃分 當然,還有一些需要考慮的問題 資料表徵,時間敏感性和資料冗餘。在資料表徵中,隨機打亂 shuffle 是乙個不...

pytorch搭建神經網路入門

autograd自動求導 pytorch 是乙個基於python的科學計算包,用於代替numpy,可以利用gpu的效能進行計算 作為乙個深度學習平台。張量 tensor 類似於numpy中的ndarray,但還可以在gpu上使用,實現加速計算的效果。建立張量的幾種方式 建立乙個沒有初始化的矩陣張量 ...

PyTorch入門(三)PyTorch常用操作

def bilinear kernel in channels,out channels,kernel size return a bilinear kernel tensor tensor in channels,out channels,kernel size,kernel size 返回雙線性...