深度学习笔记_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, ))
相关推荐
shandianchengzi26 分钟前
【小白向】错位排列|图文解释公考常见题目错位排列的递推式Dn=(n-1)(Dn-2+Dn-1)推导方式
笔记·算法·公考·递推·排列·考公
Yeats_Liao28 分钟前
评估体系构建:基于自动化指标与人工打分的双重验证
运维·人工智能·深度学习·算法·机器学习·自动化
浅念-36 分钟前
C语言编译与链接全流程:从源码到可执行程序的幕后之旅
c语言·开发语言·数据结构·经验分享·笔记·学习·算法
A尘埃1 小时前
电子厂PCB板焊点缺陷检测(卷积神经网络CNN)
人工智能·神经网络·cnn
Tadas-Gao1 小时前
缸中之脑:大模型架构的智能幻象与演进困局
人工智能·深度学习·机器学习·架构·大模型·llm
The森1 小时前
Linux IO 模型纵深解析 01:从 Unix 传统到 Linux 内核的 IO 第一性原理
linux·服务器·c语言·经验分享·笔记·unix
tq10861 小时前
Skills 的问题与解决方案
笔记
三水不滴1 小时前
有 HTTP 了为什么还要有 RPC?
经验分享·笔记·网络协议·计算机网络·http·rpc
2301_818730561 小时前
transformer(上)
人工智能·深度学习·transformer
木枷1 小时前
Online Process Reward Learning for Agentic Reinforcement Learning
人工智能·深度学习·机器学习