AlexNet网络搭建(pytorch版)

VGG网络模型详解以及代码实现 VGG网络模型详解以及代码实现一、背景1. VGG原理二、VGG网络模型详解及代码实现1. VGG网络模型详解2. 代码实现三、参考资料: 一、背景 VGGNet是在2014年由Karen Simonyan和Andrew Zisserman提出的,网络模型包括VGG-11、VGG-13、VGG-16以及VGG-19,其中VGG-16和VGG-19在分类和定位任务上效果最好,因此作者在2014年ImageNet Challenge上获得分类第二和定位第一的网络。 论文地址:VERY DEEP CONVOLUT 阅读详情

1.网络结构

 2.网络搭建

import torch.nn as nn
import torch

class AlexNet(nn.Module):
    def __init__(self, num_classes=1000, init_weights=False):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 48, kernel_size=11, stride=4, padding=2),  # input[3, 224, 224]  output[48, 55, 55]
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),                  # output[48, 27, 27]
            nn.Conv2d(48, 128, kernel_size=5, padding=2),           # output[128, 27, 27]
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),                  # output[128, 13, 13]
            nn.Conv2d(128, 192, kernel_size=3, padding=1),          # output[192, 13, 13]
            nn.ReLU(inplace=True),
            nn.Conv2d(192, 192, kernel_size=3, padding=1),          # output[192, 13, 13]
            nn.ReLU(inplace=True),
            nn.Conv2d(192, 128, kernel_size=3, padding=1),          # output[128, 13, 13]
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),                  # output[128, 6, 6]
        )
        self.classifier = nn.Sequential(
            nn.Dropout(p=0.5),
            nn.Linear(128 * 6 * 6, 2048),
            nn.ReLU(inplace=True),
            nn.Dropout(p=0.5),
            nn.Linear(2048, 2048),
            nn.ReLU(inplace=True),
            nn.Linear(2048, num_classes),
        )
        if init_weights:
            self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        x = torch.flatten(x, start_dim=1)
        x = self.classifier(x)
        return x
    
    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m,nn.Conv2d):
                nn.init.kaiming_normal_(m.weight,mode='fan_out',nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias,0)
                elif isinstance(m,nn.Linear):
                    nn.init.normal_(m.weight,0,0.01)
                    nn.init.constant_(m.bias,0)

3.网络训练

import os
import sys
import json
from sympy import im
import torch
import torch.nn as nn
from torchvision import transforms,datasets,utils
import matplotlib.pyplot as plt
import numpy as np
import torch.optim as optim
from tqdm import tqdm
from model import AlexNet

def main():
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print("using {} device.".format(device))

    data_transform = {
        "train":transforms.Compose([
            transforms.RandomResizedCrop(224),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))
        ]),
        "val":transforms.Compose([
            transforms.Resize((224,224)),# cannot(224),must(224,224)
            transforms.ToTensor(),
            transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))
        ])
    }

    image_path = './flower_data'
    train_dataset = datasets.ImageFolder(root=os.path.join(image_path,"train"),transform=data_transform["train"])
    train_num = len(train_dataset)
    # {'daisy':0, 'dandelion':1, 'roses':2, 'sunflower':3, 'tulips':4}
    flower_list = train_dataset.class_to_idx
    cla_dict = dict((val,key) for key, val in flower_list.items())
    # write dict into json file
    json_str = json.dumps(cla_dict,indent=4)
    with open('class_indices.json','w') as json_file:
        json_file.write(json_str)
    
    batch_size = 32
    nw = min([os.cpu_count(),batch_size if batch_size>1 else 0,8])# number of workers
    print("Using {} dataloader workers every process".format(nw))
    train_loader = torch.utils.data.DataLoader(
        train_dataset,
        batch_size=batch_size,
        shuffle=True,
        num_workers=nw
    )

    validate_dataset = datasets.ImageFolder(
        root=os.path.join(image_path,"val"),
        transform=data_transform["val"]
    )
    val_num=len(validate_dataset)
    validate_loader = torch.utils.data.DataLoader(
        validate_dataset,
        batch_size=4,
        shuffle=False,
        num_workers=nw
    )
    print("using {} images for training,{} images for validation.".format(train_num,val_num))
    
    
    # test_data_iter = iter(validate_loader)
    # test_image, test_label = test_data_iter.next()
    
    # def imshow(img):
    #     img = img / 2 + 0.5  # unnormalize
    #     npimg = img.numpy()
    #     plt.imshow(np.transpose(npimg, (1, 2, 0)))
    #     plt.show()
    
    # print(' '.join('%5s' % cla_dict[test_label[j].item()] for j in range(4)))
    # imshow(utils.make_grid(test_image))

    net = AlexNet(num_classes=5,init_weights=True)
    net.to(device)
    loss_function = nn.CrossEntropyLoss()
    optimizer = optim.Adam(net.parameters(),lr=0.0002)

    epochs = 10
    save_path = './Alexnet.pth'
    best_acc=0.0
    train_steps = len(train_loader)
    for epoch in range(epochs):
        # train
        net.train()
        running_loss = 0.0
        train_bar = tqdm(train_loader,file=sys.stdout)
        for step,data in enumerate(train_bar):
            images,labels = data
            optimizer.zero_grad()
            outputs = net(images.to(device))
            loss = loss_function(outputs,labels.to(device))
            loss.backward()
            optimizer.step()

            # print statistics
            running_loss += loss.item()
            train_bar.desc = "train epoch[{}/{}] loss:{:.3f}".format(epoch+1,epochs,loss)
        
        # validate
        net.eval()
        acc = 0.0  #accumulate accurate number / epoch
        with torch.no_grad():
            val_bar = tqdm(validate_loader,file=sys.stdout)
            for val_data in val_bar:
                val_images,val_labels = val_data
                outputs = net(val_images.to(device))
                predict_y = torch.max(outputs,dim=1)[1]
                acc+=torch.eq(predict_y,val_labels.to(device)).sum().item()

        val_accurate = acc/val_num
        print("[epoch %d] train_loss:%.3f val_accuracy:%.3f"%(epoch+1,running_loss/train_steps,val_accurate))

        if val_accurate > best_acc:
            best_acc = val_accurate
            torch.save(net.state_dict(),save_path)
    print("Finished Training!!!")


if __name__ == '__main__':
    main()
   

4.网络检验

import os
import json
import torch
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
from model import AlexNet

def main():
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    data_transform = transforms.Compose([
        transforms.Resize((224,224)),
        transforms.ToTensor(),
        transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))
    ])

    # load image
    img_path = "./tulip.jpg"
    assert os.path.exists(img_path),"file:'{}' does not exist.".format(img_path)
    img = Image.open(img_path)

    plt.imshow(img)
    # [N,C,H,W]
    img = data_transform(img)
    # expand batch dimension
    img = torch.unsqueeze(img,dim=0)

    # read class_indict
    json_path = './class_indices.json'
    assert os.path.exists(json_path),"file:'{}' does not exist.".format(json_path)

    with open(json_path,"r") as f:
        class_indict = json.load(f)

    # create model
    model = AlexNet(num_classes=5).to(device)

    # load model weights
    weights_path = './Alexnet.pth'
    assert os.path.exists(weights_path),"file:'{}' does not exist.".format(weights_path)
    model.load_state_dict(torch.load(weights_path))

    model.eval()
    with torch.no_grad():
        # pridict class
        output = torch.squeeze(model(img.to(device))).cpu()
        predict = torch.softmax(output,dim=0)
        predict_cla = torch.argmax(predict).numpy()
    
    print_res = "class:{} prob:{:.3f}".format(class_indict[str(predict_cla)],predict[predict_cla].numpy())
    plt.title(print_res)
    for i in range(len(predict)):
        print("class:{:10} prob:{:.3}".format(class_indict[str(i)],predict[predict_cla].numpy()))
    plt.show()

if __name__ == '__main__':
    main()

pytorch十三:pytorch搭建AlexNet网络 2012年Imagenet比赛冠军的model——Alexnet (以第一作者alex命名) 模型结构见下图,别看只有寥寥八层(不算input层),但是它有60M以上的参数总量,事实上在参数量上比后面的网络都大。 由于当时的显卡容量问题,AlexNet 的60M个参数无法全部放在一张显卡上操作,所以采用了两张显卡分开操作的形式,其中在C3,R1,R2,R3层上出现交互,所谓的交互就是通道的... 阅读详情

相关推荐

【深度学习】经典网络之AlexNet:使用PyTorch搭建AlexNet详细教程

本文主要内容: 1. AlexNet网络架构 2. 搭建AlexNet网络模型(model) 3. 数据集的下载与处理(5类花卉数据集) 4. 训练模型(train) 5. 预测模型(predict) 6. 附录 附录1:model_AlexNet.py 带详细注释源码 附录2:train_AlexNet.py 带详细注释源码 附录3:predict_AlexNet.py 带详细注释源码 1. AlexNet网络架构 在原论文中,AlexNet的网络结构是这样的:

拾年之璐 1661

经典网络架构学习-VGG

本篇博文将介绍一下在ImageNet 2014 年斩获目标定位竞赛的第一名,图像分类竞赛的第二名的网络结构VGG。VGG 是 Visual Geometry Group 的缩写,是这个网络创建者的队名,作者来自牛津大学.VGG论文《Very Deep Convolutional Networks for Large-Scale Image Recognition》作为一篇会议论文在2015年的ICLR大会上发表Visual Geometry Group实验室链接:https://www.robots.ox.

一璐有你的专栏 4779

YOLOv11 网络结构详解:一文看懂 Backbone、Head、C3k2、SPPF 和 Detect 检测头

在使用 YOLOv11 进行目标检测时,我们经常会接触到或这样的模型配置文件。backbone和head分别是什么意思?ConvC3k2SPPFC2PSA这些模块分别起什么作用?P3/8、P4/16、P5/32 代表什么?为什么最后 Detect 要同时接收 3 个不同尺度的特征图?YOLOv11n、YOLOv11s、YOLOv11m、YOLOv11l、YOLOv11x 的区别在哪里?

learnerYC的博客 1816

VGG19结构图

自己整理的VGG19层结构图

susansmile1014的博客 4万+

基于Java的高校学生信息管理系统的设计与实现(论文+源码)

可以对本系统的数据进行良好的封装,Java可以对不想被访问的数据进行良好的隐藏,具备平台无关性,可移植,更加可靠与安全,具备多线程支持,进行网络交互更容易。它支持本系统的B/S模式。开发效益方面,本系统一旦开发成功并且面向社会,就会让大多数的学生教师体会到便利办公的乐趣,随之促进提高本系统的使用率和经济利润,所以在经济方面,对于零成本开发且高利润的学生管理系统是可行的。学生可以在学生端进行选课,查看自己的成绩,教师可以在教师端查看所任课程的选课情况,对学生成绩进行录入,对所任的课程进行结课等操作。

2402_82389843的博客 1094

新建菜单Office被替换为腾讯文档 - 解决方案

右键新建菜单中的Office被替换为腾讯文档。原因是安装了腾讯文档软件,此软件安装时会自动将新建菜单中的Office替换为腾讯文档,下文介绍解决方案。

NSJim的博客 2933

AlexNet网络结构详解(含各层维度大小计算过程)与PyTorch实现

AlexNet网络结构详解(含各层维度大小计算过程)1、AlexNet之前的思考2、AlexNet网络结构3、AlexNet网络结构的主要贡献     在上文中详细介绍了第一个神经网络LeNet,但是在其提出20年的时间里并没有引起学者和各研究机构的重视,随机机器学习的兴起,LeNet网络基本被遗忘了。而真正打破机器学习和传统特征提取方法限制的深度神经网络就是本文要讲述的AlexNet。 1、AlexNet之前的思考     在AlexNet网络问世之前,大量的学者在进行图像分类、分割、识别等工作时,主要是

gz7seven 12万+

LabVIEW状态机实战:用STM32+DHT11搭建温湿度监测系统(附完整VI源码)

本文详细介绍了如何利用LabVIEW状态机模式与STM32微控制器、DHT11温湿度传感器构建温湿度监测系统。通过硬件选型、状态机设计、LabVIEW程序实现及系统优化等环节,提供了一套完整的解决方案,并附有VI源码,助力开发者快速实现嵌入式温湿度监测应用。

weixin_42549723的博客 524

VGGNet 阅读理解 - Very Deep Convolutional Networks for Large-Scale Image Recognition

论文理解 - VGGNet - Very Deep Convolutional Networks for Large-Scale Image Recognition [VGG-Paper] [原文地址 - Very deep convolutional networks for large-scale image recognition] 一篇对 VGGNet 理解比较详细的博客,很长...

长风破浪会有时,直挂云帆济沧海 5万+

字节跳动高频111道核心前端面试题解析,web开发增强

但是本人觉得看书也很必要,可以节省很多时间,常见的javascript的书,例如:javascript的高级程序设计,是每位前端工程师必不可少的一本书,边看边用,了解js的一些基本知识,基本上很全面了,如果有时间可以读一些,js性能相关的书籍,以及设计者模式,在实践中都会用的到。内容包括html,css,JavaScript,ES6,计算机网络,浏览器,工程化,模块化,Node.js,框架,数据结构,性能优化,项目等等。自定义指令(v-check、v-focus)的方法有哪些?v-model是什么?

2401_84094620的博客 1200

【ANSYS APDL】提取结构刚度矩阵完整过程--附Python代码实现

ANSYS的结构刚度矩阵提取中一些操作技巧

m0_61038364的博客 1万+

超详细,搭建网络代码解析,使用PyTorch手动搭建AlexNet网络进行图像分类实践

尽量自己编写一次代码,这样会对深度学习的网络框架有更深理解。操作系统:Ubuntu 18.04 / Windows 10编程语言:Python 3.7+深度学习框架:PyTorch 1.6+编译器:IDE(如PyCharm)或Jupyter Notebook计算机硬件配置:NVIDIA GPU(如CUDA兼容的显卡)推荐,但CPU也可运行相关库:torchvision, numpy, matplotlib等需要对网络先有个基础认识,如果你知道,可以直接跳过去看代码部分。

wzm15939943783的博客 2383

扣子Coze触发器使用指南:实现工作流定时执行的完整教程

Coze平台触发器功能详解:定时触发器配置指南 摘要:Coze平台的触发器是实现自动化任务的核心组件,其中定时触发器能够按预设时间自动执行工作流。本指南介绍了定时触发器的配置方法,包括每日、每周、每月及Cron表达式等多种时间设置方式,以及如何关联工作流执行具体任务。文章还提供了健身提醒等实用案例,并涵盖了触发器调试、发布及常见问题解决方案。通过合理配置定时触发器,用户可以轻松实现各类自动化任务,如定时发送消息、数据采集等,大幅提升工作效率。

互联网架构师笔记 1927

pytorch搭建AlexNet网络实现花分类

使用Dropout的方式在网络正向传播过程中随机失活一部分神经元,以减少过拟合。

冲冲冲的博客 3348

码农新宠大对决:GitHub Copilot、通义灵码和CodeLlama谁主沉浮?

本文对三款主流AI编程工具GitHub Copilot、通义灵码和CodeLlama进行了全面对比分析。GitHub Copilot在多语言支持和代码质量上表现突出;通义灵码在中文理解和阿里云生态集成方面优势明显;CodeLlama则以开源可定制见长。文章从代码生成、理解能力、多语言支持、使用体验等维度展开评测,并结合实际案例说明不同开发者群体的适用选择。建议新手可优先考虑通义灵码,经验开发者适合GitHub Copilot,而有定制需求的企业团队则可选择CodeLlama。随着AI技术发展,这些工具将持续

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 675

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

使用pytorch搭建AlexNet网络模型

使用pytorch搭建AlexNet网络模型

sxn0121的博客 1423

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Pytorch搭建AlexNet网络进行【自制】数据集识别

本讲目标:   介绍Pytorch搭建AlexNet网络的流程。参考 Pytorch搭建ALexNet网络1.AlexNet网络介绍2.Pytorch框架搭建AlexNet2.1搭建模型 model.py2.2搭建训练过程 train.py2.3搭建预测过程 predict.py 1.AlexNet网络介绍   AlexNet网络诞生于2012年,当年ImageNet竞赛的冠军,Top5错误率为16.4%   借鉴点:使用了Relu激活函数,提升训练速度;使用了Dropout, 防止过拟合。使用了图像增强,

AI Chen的博客 722

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

pytorch搭建卷积神经网络(alexnet、vgg16、resnet50)以及训练

文末有代码和数据集链接!!!! (注:文章中所有path指文件的路径) 因毕业设计需要,接触卷积神经网络。由于pytorch方便使用,所以最后使用pytorch来完成卷积神经网络训练。 接触到的网络有Alexnet、vgg16、resnet50,毕业答辩完后,一直在训练Alexnet。 1.卷积神经网络搭建 pytorch中有torchvision.models,里面有许多已搭建好的...

PC1022的博客 2万+

【pytorch学习笔记】pytorch搭建AlexNet网络+FashionMnist数据集

目录 AlexNet网络介绍 pytorch搭建网络 AlexNet网络介绍 AlexNet由⼋层组成:五个卷积层、两个全连接隐藏层和⼀个全连接输出层。其次,AlexNet使⽤ReLU而不是sigmoid作为其激活函数。 在AlexNet的第⼀层,卷积窗口的形状是 11×11,,需要⼀个更⼤的卷积窗口来捕获⽬标。 AlexNet将sigmoid激活函数改为更简单的ReLU激活函数。⼀⽅⾯,ReLU激活函数的计算更简单,它 不需要如sigmoid激活函数那般复杂的求幂运算。另⼀⽅⾯,

是安澜啊 1116

深度学习第二禅:pytorch搭建AlexNet网络

pytorch搭建AlexNet网络并使用话分类数据集进行训练

weixin_44230855的博客 792

pytorch Alexnet 网络模型搭建

Alexnet 网络模型 网络亮点 首次使用GPU进行网络加速训练(是cpu的20-50倍速度) 使用Relu激活函数,而不是传统的sigmoid激活函数及Tanh激活函数 使用LRN局部相应归一化 在全连接层的前两层使用了Dropout随机失活神经元操作,以减少过拟合 pytorch 模型实现 import torch.nn as nn import torch #卷积核的数量仅仅用到论文中的一半 class AlexNet(nn.Module): def __init__(self, n

1738

基于pytorch搭建AlexNet神经网络用于花类识别_alxnett实现102花卉

最近打算出一个基于pytorch搭建各种经典神经网络的系列。对神经网络有一定的了解,当然了,本节针对AlexNet,那么你应对其有较深入的了解,不明白的请看我之前关于此部分的介绍,详情戳此图标☞☞☞对pytorch有一定的了解,同样的,不了解的请移步至我之前的文章,详情戳此图标☞☞☞。

2401_84978490的博客 1229

PyTorch搭建AlexNet网络模型

PyTorch搭建AlexNet网络模型详解代码!

2301_78820199的博客 1230

基于pytorch搭建AlexNet神经网络用于花类识别

🍊作者简介:秃头小苏,致力于用最通俗的语言描述问题 🍊往期回顾:卡尔曼滤波系列1——卡尔曼滤波    张氏标定法原理详解 🍊近期目标:拥有5000粉丝 🍊支持小苏:点赞👍🏼、收藏⭐、留言📩 文章目录基于pytorch搭建AlexNet神经网络用于花类识别写在前面完整网络模型训练步骤1、准备数据集2、加载数据集3、搭建神经网络✨✨✨4、创建网络模型5、设置损失函数、优化器等参数6、开始训练网络✨✨✨7、开始测试网络✨✨✨8、保存模型9、模型训练结果使用训练模型进行物体识别✨✨✨...

秃头小苏的博客 6382

使用pytorch搭建自己的网络之AlexNet

一、introduction 回顾近几年来卷积神经网络的发展历史,我们必须要提到AlexNet卷积神经网络。这是Alex在2012年提出来的神经网络模型,赢得了当年的图像识别大赛冠军,首次证明了通过网络学习到的特征可以超越手工设计的特征,同时也奠定了CNN在处理图像分类任务上的地位。 二、网络结构 网上比较流行的网络结构如上图所示,由于当年计算能力的不足,AlexNet网络在训练时使用了两块GPU同时进行训练;随着现在硬件能力的提升,我们使用一块普通的GPU已经能够很快速地训练该网络。 具体代码如下: i

qq_40356092的博客 1261

Pytorch搭建AlexNet网络

AlexNet详解

weixin_44436319的博客 1086
上一篇: LeNet网络模型的搭建与训练
下一篇: VGG网络模型
Caoyy686868
博客等级 码龄8年 5742粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Caoyy686868

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值