PyTorch实现AlexNet示例

yipeiwu_com6年前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闭包执行时值的传递方式实例分析

本文实例分析了Python闭包执行时值的传递方式。分享给大家供大家参考,具体如下: 代码中有问题和问题的解释。 #!/usr/bin/python #coding: utf-8 #...

图文详解Django使用Pycharm连接MySQL数据库

图文详解Django使用Pycharm连接MySQL数据库

在 Pycharm 的右上方找到 Database 点击 依次点击,选择 MySQL 数据库 点击 Download 下载驱动文件 下载完成后对数据库的相关信息进行填写 填写完成...

Python读取图片EXIF信息类库介绍和使用实例

首先要介绍的是 Python Imaging Library,使用方法如下: 复制代码 代码如下: from PIL import Image from PIL.ExifTags imp...

python实现下载文件的三种方法

Python开发中时长遇到要下载文件的情况,最常用的方法就是通过Http利用urllib或者urllib2模块。 当然你也可以利用ftplib从ftp站点下载文件。此外Python还提...

Django使用消息提示简单的弹出个对话框实例

Django使用消息提示简单的弹出个对话框实例

1、下面就来介绍一下如何简单的显示一个消息提示,好像js可以控制,不过这里用了django.contrib.messages这个库 2、首先呢,在项目的settings.py有默认配置...