【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)
相关推荐
无限的鲜花4 小时前
反射(原创推荐)
java·开发语言
hhzz5 小时前
基于监控视频的水位尺自动识别技术方案与实现
python·opencv·yolo·图像识别·cv
yongche_shi5 小时前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
一路向北he5 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
weixin_408099676 小时前
OCR批量识别图片方案:从手动处理到自动化API系统(Python/Java/PHP实战)
图像处理·python·ocr·文字识别·api调用·批量识别·石榴智能
AI行业学习6 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++
大圣编程7 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
云烟成雨TD7 小时前
LangFlow 1.x 系列【5】可视化编辑页面功能说明
人工智能·python·agent
upgrador7 小时前
基础知识:C++ STL构造函数的左闭右开惯例及其实现原理
开发语言·c++
yoothey8 小时前
报废审批流规则引擎设计——责任链模式完整实现
linux·开发语言·bash