cs231n assignment2 q5 PyTorch on CIFAR-10

文章目录

  • 嫌啰嗦直接看源码
  • Q5 :PyTorch on CIFAR-10
    • three_layer_convnet
      • 题面
      • 解析
      • 代码
      • 输出
    • Training a ConvNet
      • 题面
      • 解析
      • 代码
      • 输出
    • ThreeLayerConvNet
      • 题面
      • 解析
      • 代码
      • 输出
    • Train a Three-Layer ConvNet
      • 题面
      • 解析
      • 代码
      • 输出
    • Sequential API: Three-Layer ConvNet
      • 题面
      • 解析
      • 代码
      • 输出
    • CIFAR-10 open-ended challenge
      • 题面
      • 解析
      • 代码
      • 输出

嫌啰嗦直接看源码

Q5 :PyTorch on CIFAR-10

three_layer_convnet

题面

在这里插入图片描述
在这里插入图片描述
让我们使用Pytorch来实现一个三层神经网络

解析

看下pytorch是怎么用的,原理我们其实都清楚了,自己去查下文档就好了

具体的可以看上一个cell上面给出的文档地址

For convolutions: http://pytorch.org/docs/stable/nn.html#torch.nn.functional.conv2d; pay attention to the shapes of convolutional filters!

代码

def three_layer_convnet(x, params):
    """
    Performs the forward pass of a three-layer convolutional network with the
    architecture defined above.

    Inputs:
    - x: A PyTorch Tensor of shape (N, 3, H, W) giving a minibatch of images
    - params: A list of PyTorch Tensors giving the weights and biases for the
      network; should contain the following:
      - conv_w1: PyTorch Tensor of shape (channel_1, 3, KH1, KW1) giving weights
        for the first convolutional layer
      - conv_b1: PyTorch Tensor of shape (channel_1,) giving biases for the first
        convolutional layer
      - conv_w2: PyTorch Tensor of shape (channel_2, channel_1, KH2, KW2) giving
        weights for the second convolutional layer
      - conv_b2: PyTorch Tensor of shape (channel_2,) giving biases for the second
        convolutional layer
      - fc_w: PyTorch Tensor giving weights for the fully-connected layer. Can you
        figure out what the shape should be?
      - fc_b: PyTorch Tensor giving biases for the fully-connected layer. Can you
        figure out what the shape should be?
    
    Returns:
    - scores: PyTorch Tensor of shape (N, C) giving classification scores for x
    """
    conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b = params
    scores = None
    ################################################################################
    # TODO: Implement the forward pass for the three-layer ConvNet.                #
    ################################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    x = F.conv2d(x, conv_w1, bias=conv_b1, padding=2)
    x = F.relu(x)
    x = F.conv2d(x, conv_w2, bias=conv_b2, padding=1)
    x = F.relu(x)
    x = flatten(x)
    scores = x.mm(fc_w) + fc_b

    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    ################################################################################
    #                                 END OF YOUR CODE                             #
    ################################################################################
    return scores

输出

在这里插入图片描述
在这里插入图片描述
注意这里需要注意有没有使用Gpu版本的pytorch,我就是在这里发现我的pytorch没有cuda

Training a ConvNet

题面

在这里插入图片描述
在这里插入图片描述

解析

按照题面意思来就好了

代码

learning_rate = 3e-3

channel_1 = 32
channel_2 = 16

conv_w1 = None
conv_b1 = None
conv_w2 = None
conv_b2 = None
fc_w = None
fc_b = None

################################################################################
# TODO: Initialize the parameters of a three-layer ConvNet.                    #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

conv_w1 = random_weight((channel_1, 3, 5, 5))
conv_b1 = zero_weight(channel_1)
conv_w2 = random_weight((channel_2, channel_1, 3, 3))
conv_b2 = zero_weight(channel_2)
fc_w = random_weight((channel_2 * 32 * 32, 10))
fc_b = zero_weight(10)

# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
#                                 END OF YOUR CODE                             #
################################################################################

params = [conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b]
train_part2(three_layer_convnet, params, learning_rate)

输出

在这里插入图片描述

ThreeLayerConvNet

题面

在这里插入图片描述

解析

就是让我们熟悉一下几个api

代码

class ThreeLayerConvNet(nn.Module):
    def __init__(self, in_channel, channel_1, channel_2, num_classes):
        super().__init__()
        ########################################################################
        # TODO: Set up the layers you need for a three-layer ConvNet with the  #
        # architecture defined above.                                          #
        ########################################################################
        # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

        self.conv1 = nn.Conv2d(in_channel, channel_1, kernel_size=5, padding=2)
        self.conv2 = nn.Conv2d(channel_1, channel_2, kernel_size=3, padding=1)
        self.fc3 = nn.Linear(channel_2 * 32 * 32, num_classes)
        nn.init.kaiming_normal_(self.conv1.weight)
        nn.init.kaiming_normal_(self.conv2.weight)
        nn.init.kaiming_normal_(self.fc3.weight)

        # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
        ########################################################################
        #                          END OF YOUR CODE                            #
        ########################################################################

    def forward(self, x):
        scores = None
        ########################################################################
        # TODO: Implement the forward function for a 3-layer ConvNet. you      #
        # should use the layers you defined in __init__ and specify the        #
        # connectivity of those layers in forward()                            #
        ########################################################################
        # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        scores = self.fc3(flatten(x))

        # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
        ########################################################################
        #                             END OF YOUR CODE                         #
        ########################################################################
        return scores

输出

在这里插入图片描述
在这里插入图片描述

Train a Three-Layer ConvNet

题面

在这里插入图片描述

解析

就仿照上面的两层全连接改写就好了

关于optim ,我试过sgd 和 adam,但是我发现还是sgd效果对于这个样本好一点。。。。

代码

learning_rate = 3e-3
channel_1 = 32
channel_2 = 16

model = None
optimizer = None
################################################################################
# TODO: Instantiate your ThreeLayerConvNet model and a corresponding optimizer #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

model = ThreeLayerConvNet(in_channel=3, channel_1=channel_1, channel_2=channel_2, num_classes=10)
optimizer = optim.SGD(model.parameters(), lr=learning_rate)

# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
#                                 END OF YOUR CODE                             #
################################################################################

train_part34(model, optimizer)

输出

在这里插入图片描述

Sequential API: Three-Layer ConvNet

题面

在这里插入图片描述

解析

也是仿照上面写就好了

代码

channel_1 = 32
channel_2 = 16
learning_rate = 1e-2

model = None
optimizer = None

################################################################################
# TODO: Rewrite the 2-layer ConvNet with bias from Part III with the           #
# Sequential API.                                                              #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

model = nn.Sequential(
    nn.Conv2d(in_channels=3, out_channels=channel_1, kernel_size=5, padding=2),
    nn.ReLU(),
    nn.Conv2d(in_channels=channel_1, out_channels=channel_2, kernel_size=3, padding=1),
    nn.ReLU(),
    Flatten(),
    nn.Linear(channel_2 * 32 * 32, 10)
)
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, nesterov=True)

# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
#                                 END OF YOUR CODE                             #
################################################################################

train_part34(model, optimizer)

输出

在这里插入图片描述

CIFAR-10 open-ended challenge

题面

在这里插入图片描述
在这里插入图片描述
就是让我们自己尝试搭建一种网络结构使其准确率大于70%

解析

自己试吧

代码

################################################################################
# TODO:                                                                        #         
# Experiment with any architectures, optimizers, and hyperparameters.          #
# Achieve AT LEAST 70% accuracy on the *validation set* within 10 epochs.      #
#                                                                              #
# Note that you can use the check_accuracy function to evaluate on either      #
# the test set or the validation set, by passing either loader_test or         #
# loader_val as the second argument to check_accuracy. You should not touch    #
# the test set until you have finished your architecture and  hyperparameter   #
# tuning, and only run the test set once at the end to report a final value.   #
################################################################################
model = None
optimizer = None

# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

model = nn.Sequential(
    nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1),
    nn.ReLU(),
    nn.MaxPool2d(kernel_size=2, stride=2),
    nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
    nn.ReLU(),
    nn.MaxPool2d(kernel_size=2, stride=2),
    nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
    nn.ReLU(),
    nn.MaxPool2d(kernel_size=2, stride=2),
    Flatten(),
    nn.Linear(128 * 4 * 4, 1024),
)
optimizer = optim.Adam(model.parameters(), lr=1e-3)

# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
#                                 END OF YOUR CODE                             #
################################################################################

# You should get at least 70% accuracy.
# You may modify the number of epochs to any number below 15.
train_part34(model, optimizer, epochs=10)

输出

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/73332.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【MongoDB】解决ProxmoxVE下CentOS7虚拟机安装MongoDB6后启动失败的问题

目录 安装步骤: 2.1 配置yum源 2.2 安装MongoDB 2.3 启 动MongoDB ProxmoxVE上新装的CentOS7.4虚拟机,安装MongoDB6。 安装步骤: 2.1 配置yum源 # 创建mongodb yum源(https://www.mongodb.com/docs/manual/tutorial/insta…

27岁了学plc还来得及吗?

如果你是学电气或者自控,完全没问题,PLC其实只是你的理解力的问题,真正底层的,都帮你打包了,你直接用就是。问题只是:你要能透彻理解 如果你从一个完全陌生的行业转过来,完全没必要。如果本身就…

[数据分析与可视化] Python绘制数据地图5-MovingPandas绘图实例

MovingPandas是一个基于Python和GeoPandas的开源地理时空数据处理库,用于处理移动物体的轨迹数据。关于MovingPandas的使用见文章:MovingPandas入门指北,本文主要介绍三个MovingPandas的绘图实例。 MovingPandas官方仓库地址为:mo…

自定义批量修改图像位深度

什么是图像位深度??? 图像位深度(Bit Depth)是指图像中每个像素所占的比特数,它决定了图像能够表示的颜色数量和亮度层级。 简单来说: 位深度越高,每个像素所能表示的颜色数和亮度等级越多。位深度越低,每个像素所能表示的颜色数和亮度等级…

容器安全的常见风险与防护实践

运行在云平台上的容器产品,因为具备一个完整的可移植应用程序环境,能够帮助用户轻松地完成对应用程序的开关控制,提升应用程序的敏捷性,同时节约企业的IT建设成本。在巨大优势作用下,容器产品的采用率在2021年达到了新…

恒运资本:算力股爆发,地产股全线下挫,海外机构调研股出炉

60股近期获海外组织调研,医疗龙头最受组织重视。 今日早盘三大指数全线低开,延续调整走势,上证指数跌1.01%,深证成指跌1.35%,创业板指跌1.6%。AI概念股逆市走强,算力、数据要素等方向领涨,朗威股…

通达信接口调用过程需要借助什么?

通达信接口是一种用于获取、传输和处理股票市场相关数据的软件接口,以提供了一种连接股票市场数据源和数据使用者之间的通道,允许开发者通过编程方式获取股票行情数据、交易数据和相关信息等。如果调用通达信接口,需要借助以下几个方面的工具…

竞赛项目 深度学习的动物识别

文章目录 0 前言1 背景2 算法原理2.1 动物识别方法概况2.2 常用的网络模型2.2.1 B-CNN2.2.2 SSD 3 SSD动物目标检测流程4 实现效果5 部分相关代码5.1 数据预处理5.2 构建卷积神经网络5.3 tensorflow计算图可视化5.4 网络模型训练5.5 对猫狗图像进行2分类 6 最后 0 前言 &#…

【Linux】网络层、数据链路层、DNS、ICMP协议、NAT技术

​🌠 作者:阿亮joy. 🎆专栏:《学会Linux》 🎇 座右铭:每个优秀的人都有一段沉默的时光,那段时光是付出了很多努力却得不到结果的日子,我们把它叫做扎根 目录 👉网络层&a…

SQL | 检索数据

1-检索数据 1.1-检索单个列 SELECT prod_name FROM Products; 上述SELECT语句从Products表中检索一个名为prod_name的列。 所要查找的列在select后面,from关键字指出从那个表查询数据。 输出如下: prod_name8 inch teddy bear12 inch teddy bear18…

【Unity3D】Shader Graph节点

1 前言 Shader Graph 16.0.3 中有 208 个 Node(节点),本文梳理了 Shader Graph 中大部分 Node 的释义,官方介绍详见→Node-Library。 Shader Graph 通过图像的形式表达了顶点变换和片元着色流程,其背后都是一些列的数学…

ubuntu 安装 python

ubuntu 安装 python 初环境与设备查询是否安装安装python 本篇文章将介绍ubuntu 安装 python 初 希望能写一些简单的教程和案例分享给需要的人 环境与设备 系统:ubuntu 查询是否安装 因为系统也许会自带一个python,所以验证一下,如果自…

FPGA应用学习笔记----CORDIC 算法和小结

加减移位操作来运算三角函数,开根号,求对数 圆周旋转模式

【Uni-App】uview 开发多端应用,密码显示隐藏功能不生效问题

出现的问题: 使用uview组件u-input框密码绑定时会出现右侧密码显隐图标不显示的问题 思路: 1.看了下uview源码,发现这有一段注释,我们需要把源码修改一下,问题出在这里 这行代码修改为 :password"password || …

ChatGPT: 提升程序员开发效率的秘密武器!

引言 在现代软件开发中,时间和效率显得尤为重要。程序员们需要在尽可能短的时间内编写高质量的代码,并使之处于状态良好的维护周期。为满足这些需求,人工智能技术逐渐成为软件开发的一项核心能力。ChatGPT作为自然语言生成模型中的佼佼者&am…

K8S MetalLB LoadBalancer

1. 简介 kubernetes集群没有L4负载均衡,对外暴漏服务时,只能使用nodePort的方式,比较麻烦,必须要记住不同的端口号。 LoadBalancer:使用云提供商的负载均衡器向外部暴露服务,外部负载均衡器可以将流量路由…

面部表情识别(Pytorch):人脸检测模型+面部表情识别分类模型

目录 0 相关资料1 基于人脸检测面部表情分类识别方法2 项目安装2.1 平台与镜像2.2 项目下载2.3 模型下载2.4 上传待测试图片2.5 项目安装 3 demo测试 0 相关资料 面部表情识别2:Pytorch实现表情识别(含表情识别数据集和训练代码):https://blog.csdn.net…

Java:正则表达式书写规则及相关案例:检验QQ号码,校验手机号码,邮箱格式,当前时间

正则表达式 目标:体验一下使用正则表达式来校验数据格式的合法性。需求:校验QQ号码是否正确,要求全部是数字,长度是(6-20)之间,不能以0开头 首先用自己编写的程序判断QQ号码是否正确 public static void main(String[] args) {Sy…

camera hal|如何学习一个新平台

全网最具价值的Android Camera开发学习系列资料~ 作者:8年Android Camera开发,从Camera app一直做到Hal和驱动~ 欢迎订阅,相信能扩展你的知识面,提升个人能力~ 我自己目前从事的是android camera hal 的工作,工作上接触到的芯片平台要么是高通的,要么是mtk的。 其实…

shell脚本循环语句

shell脚本循环语句 一.echo命令二.查看当前系统的时间--date命令三.循环语句for四.while循环语句结构五.while循环语句结构(迭代)六.continue和break 一.echo命令 echo -n 表示不换行输出 echo -e输出转义符,将转义后的内容输出到屏幕上 常…
最新文章