国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

pytorch構(gòu)建網(wǎng)絡(luò)模型的4種方法

2020-02-22 23:39:49
字體:
供稿:網(wǎng)友

利用pytorch來構(gòu)建網(wǎng)絡(luò)模型有很多種方法,以下簡單列出其中的四種。

假設(shè)構(gòu)建一個(gè)網(wǎng)絡(luò)模型如下:

卷積層--》Relu層--》池化層--》全連接層--》Relu層--》全連接層

首先導(dǎo)入幾種方法用到的包:

import torchimport torch.nn.functional as Ffrom collections import OrderedDict

第一種方法

# Method 1 -----------------------------------------class Net1(torch.nn.Module):  def __init__(self):    super(Net1, self).__init__()    self.conv1 = torch.nn.Conv2d(3, 32, 3, 1, 1)    self.dense1 = torch.nn.Linear(32 * 3 * 3, 128)    self.dense2 = torch.nn.Linear(128, 10)  def forward(self, x):    x = F.max_pool2d(F.relu(self.conv(x)), 2)    x = x.view(x.size(0), -1)    x = F.relu(self.dense1(x))    x = self.dense2(x)    return xprint("Method 1:")model1 = Net1()print(model1)

這種方法比較常用,早期的教程通常就是使用這種方法。

第二種方法

# Method 2 ------------------------------------------class Net2(torch.nn.Module):  def __init__(self):    super(Net2, self).__init__()    self.conv = torch.nn.Sequential(      torch.nn.Conv2d(3, 32, 3, 1, 1),      torch.nn.ReLU(),      torch.nn.MaxPool2d(2))    self.dense = torch.nn.Sequential(      torch.nn.Linear(32 * 3 * 3, 128),      torch.nn.ReLU(),      torch.nn.Linear(128, 10)    )  def forward(self, x):    conv_out = self.conv1(x)    res = conv_out.view(conv_out.size(0), -1)    out = self.dense(res)    return outprint("Method 2:")model2 = Net2()print(model2)

這種方法利用torch.nn.Sequential()容器進(jìn)行快速搭建,模型的各層被順序添加到容器中。缺點(diǎn)是每層的編號是默認(rèn)的阿拉伯?dāng)?shù)字,不易區(qū)分。

第三種方法:

# Method 3 -------------------------------class Net3(torch.nn.Module):  def __init__(self):    super(Net3, self).__init__()    self.conv=torch.nn.Sequential()    self.conv.add_module("conv1",torch.nn.Conv2d(3, 32, 3, 1, 1))    self.conv.add_module("relu1",torch.nn.ReLU())    self.conv.add_module("pool1",torch.nn.MaxPool2d(2))    self.dense = torch.nn.Sequential()    self.dense.add_module("dense1",torch.nn.Linear(32 * 3 * 3, 128))    self.dense.add_module("relu2",torch.nn.ReLU())    self.dense.add_module("dense2",torch.nn.Linear(128, 10))  def forward(self, x):    conv_out = self.conv1(x)    res = conv_out.view(conv_out.size(0), -1)    out = self.dense(res)    return outprint("Method 3:")model3 = Net3()print(model3)

這種方法是對第二種方法的改進(jìn):通過add_module()添加每一層,并且為每一層增加了一個(gè)單獨(dú)的名字。 

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 广州市| 普格县| 革吉县| 锦屏县| 淮北市| 长岛县| 肇庆市| 富锦市| 高安市| 长海县| 中阳县| 广河县| 比如县| 贵州省| 浦北县| 绍兴市| 手游| 宾阳县| 长沙县| 乌拉特中旗| 襄樊市| 名山县| 丰台区| 沙河市| 巴林右旗| 小金县| 平南县| 中牟县| 临颍县| 隆子县| 雷山县| 禹城市| 霸州市| 巴塘县| 托克逊县| 托里县| 桑植县| 乌鲁木齐市| 芦山县| 崇左市| 晋江市|