深度学习笔记_1、定义神经网络

1、 使用了PyTorch的nn.Module类来定义神经网络模型;使用nn.Linear来创建全连接层。(CPU)

复制代码
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary

# 定义神经网络模型
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(in_features=250, out_features=100, bias=True)  # 输入层到隐藏层1,具有250个输入特征和100个神经元
        self.fc2 = nn.Linear(100, 50)  # 隐藏层2,具有100到50个神经元
        self.fc3 = nn.Linear(50, 25)   # 隐藏层3,具有50到25个神经元
        self.fc4 = nn.Linear(25, 10)   # 隐藏层4,具有25到10个神经元
        self.fc5 = nn.Linear(10, 2)    # 输出层,具有10到2个神经元,用于二分类任务

    # 前向传播函数
    def forward(self, x):
        x = x.view(-1, 250)  # 将输入数据展平成一维张量
        x = F.relu(self.fc1(x))  # 使用ReLU激活函数传递到隐藏层1
        x = F.relu(self.fc2(x))  # 使用ReLU激活函数传递到隐藏层2
        x = F.relu(self.fc3(x))  # 使用ReLU激活函数传递到隐藏层3
        x = F.relu(self.fc4(x))  # 使用ReLU激活函数传递到隐藏层4
        x = self.fc5(x)         # 输出层,没有显式激活函数
        return x

if __name__ == '__main__':
    print(Net())
    model = Net()
    summary(model, (250,))  # 打印模型摘要信息,输入大小为(250,)

2、GPU版本

python 复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(784, 100).to(device='cuda:0')
        self.fc2 = nn.Linear(100, 50).to(device='cuda:0')
        self.fc3 = nn.Linear(50, 25).to(device='cuda:0')
        self.fc4 = nn.Linear(25, 10).to(device='cuda:0')

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.relu(self.fc3(x))
        x = F.relu(self.fc4(x))
        return x

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model = Net().to(device)
input_data = torch.randn(784, 100).to(device)

summary(model, (784, ))
相关推荐
CoovallyAIHub18 小时前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub18 小时前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub18 小时前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉
CoovallyAIHub18 小时前
强化学习凭什么比监督学习更聪明?RL的“聪明”并非来自算法,而是因为它学会了“挑食”
深度学习·算法·计算机视觉
CoovallyAIHub18 小时前
YOLO-IOD深度解析:打破实时增量目标检测的三重知识冲突
深度学习·算法·计算机视觉
用户1474853079741 天前
AI-动手深度学习环境搭建-d2l
深度学习
OpenBayes贝式计算2 天前
解决视频模型痛点,TurboDiffusion 高效视频扩散生成系统;Google Streetview 涵盖多个国家的街景图像数据集
人工智能·深度学习·机器学习
OpenBayes贝式计算2 天前
OCR教程汇总丨DeepSeek/百度飞桨/华中科大等开源创新技术,实现OCR高精度、本地化部署
人工智能·深度学习·机器学习
在人间耕耘2 天前
HarmonyOS Vision Kit 视觉AI实战:把官方 Demo 改造成一套能长期复用的组件库
人工智能·深度学习·harmonyos
西岸行者2 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习