深度学习笔记_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, ))
相关推荐
Uncommon.10 小时前
使用pandas处理csv并转为张量
pytorch·python·深度学习·pandas
Chen—LSN10 小时前
C语言——数据在内存中的存储
c语言·开发语言·经验分享·笔记
柳叶方舟10 小时前
Nature Medicine IF=50.0 | 公众医疗助手LLM可靠性存隐忧:真人交互表现未优于对照组,现有评估基准失效
论文阅读·人工智能·深度学习·交互·健康医疗
手写码匠11 小时前
华为云Flexus+DeepSeek征文|Dify 多 Agent 评测实战:用 DeepSeek-R1 当裁判,打造多智能体系统的自动化质量保障体系
人工智能·深度学习·算法·aigc
汽车仪器仪表相关领域11 小时前
SIRIUS R1DB/R2DB便携式一体化数据采集系统
大数据·人工智能·功能测试·深度学习·压力测试
头发够用的程序员12 小时前
Nsight Systems 零基础入门:Trace采集与基础操作
人工智能·深度学习·神经网络·计算机视觉·边缘计算·分析工具
bitbrowser20 小时前
giffgaff突然停用?先分清闲置停用和长期境外断开
笔记
九硕智慧建筑一体化厂家21 小时前
数字化管控落地,直流照明构筑安全照明体系
运维·人工智能·笔记·安全·智慧城市
AI云海21 小时前
天幕红尘笔记
笔记