【python】神经网络

构建神经网络的典型流程

  1. 定义一个拥有可学习参数的神经网络

  2. 遍历训练数据集

  3. 处理输入数据使其流经神经网络

  4. 计算损失值

  5. 将网络参数的梯度进行反向传播

  6. 以一定的规则更新网络的权重

卷积神经网络(pytorch自己写的,建议用第三方包)

导包

from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F

建立神经网络类

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 定义第一层卷积神经网络,输入通道为3,输出通道为6,卷积核大小为5*5
        self.conv1 = nn.Conv2d(3, 6, 5)
        # 定义第二层卷积神经网络,输入通道为6,输出通道为16,卷积核大小为5*5
        self.conv2 = nn.Conv2d(6, 16, 5)
        # 定义全连接层
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 在池化层窗口下进行池化操作
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # 除去批处理维度的其他所有维度
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

使用

net=Net()
param=list(net.parameters())
print(len(param))
print(param[0].size())
input=torch.randn(1,3,32,32)
out=net(input)
print(out)
相关推荐
金灰3 分钟前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5
浊酒南街4 分钟前
吴恩达深度学习笔记:卷积神经网络(Foundations of Convolutional Neural Networks)2.7-2.8
人工智能·深度学习·神经网络
爱上语文7 分钟前
Java LeetCode每日一题
java·开发语言·leetcode
qq_273900237 分钟前
解析TMalign文本文件中的转换矩阵
python·生物信息学
Манго нектар34 分钟前
JavaScript for循环语句
开发语言·前端·javascript
程序猿小D42 分钟前
第二百六十九节 JPA教程 - JPA查询OrderBy两个属性示例
java·开发语言·数据库·windows·jpa
阿华的代码王国1 小时前
【JavaEE】——文件IO的应用
开发语言·python
satan–01 小时前
R语言的下载、安装及环境配置(Rstudio&VSCode)
开发语言·windows·vscode·r语言
电饭叔1 小时前
《python语言程序设计》2018版第8章19题几何Rectangle2D类(下)-头疼的几何和数学
开发语言·python
Eternal-Student1 小时前
everyday_question dq20240731
开发语言·arm开发·php