深度学习笔记_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, ))
相关推荐
李帅朋6 小时前
微分基本定义笔记
人工智能·笔记·深度学习·神经网络
ai小陈7 小时前
LoRA微调显存怎么估?32GB GPU训练配置与常见问题排查
人工智能·深度学习·机器学习·ai·gpu算力
2601_962297487 小时前
AI 自动编码将上线,谷歌 Colab 推出 Github Copilot 竞品
深度学习·代码生成·githubcopilot·ai编码·谷歌colab
SuperHeroWu78 小时前
【HarmonyOS AI】 通用文字识别详解
人工智能·pytorch·深度学习·通用文字识别
xian_wwq9 小时前
【学习笔记】深度认知系列-第16讲-提示词工程
人工智能·笔记·学习
youm200310 小时前
认识Redis
redis·笔记·学习
deepdata_cn10 小时前
元学习、迁移学习、小样本学习的区别
深度学习·迁移学习
亮工硬件10 小时前
1-11 STM32内部FLASH(数据掉电保存)
笔记·stm32·单片机·嵌入式硬件·学习
千里码aicood11 小时前
Flask-基于图神经网络的谣言检测研究
人工智能·神经网络·flask
知识分享小能手12 小时前
深度学习学习教程,从入门到精通,深度模型中的优化 — 完整知识点与代码案例(8)
人工智能·深度学习·学习