PyTorch实现AlexNet示例

yipeiwu_com5年前Python基础

PyTorch: https://github.com/shanglianlm0525/PyTorch-Networks

import torch
import torch.nn as nn
import torchvision

class AlexNet(nn.Module):
  def __init__(self,num_classes=1000):
    super(AlexNet,self).__init__()
    self.feature_extraction = nn.Sequential(
      nn.Conv2d(in_channels=3,out_channels=96,kernel_size=11,stride=4,padding=2,bias=False),
      nn.ReLU(inplace=True),
      nn.MaxPool2d(kernel_size=3,stride=2,padding=0),
      nn.Conv2d(in_channels=96,out_channels=192,kernel_size=5,stride=1,padding=2,bias=False),
      nn.ReLU(inplace=True),
      nn.MaxPool2d(kernel_size=3,stride=2,padding=0),
      nn.Conv2d(in_channels=192,out_channels=384,kernel_size=3,stride=1,padding=1,bias=False),
      nn.ReLU(inplace=True),
      nn.Conv2d(in_channels=384,out_channels=256,kernel_size=3,stride=1,padding=1,bias=False),
      nn.ReLU(inplace=True),
      nn.Conv2d(in_channels=256,out_channels=256,kernel_size=3,stride=1,padding=1,bias=False),
      nn.ReLU(inplace=True),
      nn.MaxPool2d(kernel_size=3, stride=2, padding=0),
    )
    self.classifier = nn.Sequential(
      nn.Dropout(p=0.5),
      nn.Linear(in_features=256*6*6,out_features=4096),
      nn.ReLU(inplace=True),
      nn.Dropout(p=0.5),
      nn.Linear(in_features=4096, out_features=4096),
      nn.ReLU(inplace=True),
      nn.Linear(in_features=4096, out_features=num_classes),
    )
  def forward(self,x):
    x = self.feature_extraction(x)
    x = x.view(x.size(0),256*6*6)
    x = self.classifier(x)
    return x


if __name__ =='__main__':
  # model = torchvision.models.AlexNet()
  model = AlexNet()
  print(model)

  input = torch.randn(8,3,224,224)
  out = model(input)
  print(out.shape)

以上这篇PyTorch实现AlexNet示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

对python 多线程中的守护线程与join的用法详解

多线程:在同一个时间做多件事 守护线程:如果在程序中将子线程设置为守护线程,则该子线程会在主线程结束时自动退出,设置方式为thread.setDaemon(True),要在thread....

python机器学习库常用汇总

汇总整理一套Python网页爬虫,文本处理,科学计算,机器学习和数据挖掘的兵器谱。 1. Python网页爬虫工具集 一个真实的项目,一定是从获取数据开始的。无论文本处理,机器学习和数据...

Python多继承原理与用法示例

Python多继承原理与用法示例

本文实例讲述了Python多继承原理与用法。分享给大家供大家参考,具体如下: python中使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承,也叫菱形继承问题)等 MRO MR...

Python异常处理操作实例详解

本文实例讲述了Python异常处理操作。分享给大家供大家参考,具体如下: 一、异常处理的引入 >>>whileTrue: try: x = int(input("P...

python中join()方法介绍

描述 Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。 语法 join()方法语法: str . join ( sequence ) 参数 sequ...