深度学习笔记_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, ))
相关推荐
TheSumSt5 小时前
Python丨课程笔记Part3:语法进阶部分(控制结构与基础数据结构)
数据结构·笔记·python
赋创小助手5 小时前
融合与跃迁:NVIDIA、Groq 与下一代 AI 推理架构的博弈与机遇
服务器·人工智能·深度学习·神经网络·语言模型·自然语言处理·架构
白日做梦Q5 小时前
深度学习模型评估指标深度解析:不止于准确率的科研量化方法
人工智能·深度学习
IT19956 小时前
Qt笔记-使用SSH2进行远程连接linux服务器并上传文件
linux·服务器·笔记
哥布林学者7 小时前
吴恩达深度学习课程四:计算机视觉 第四周:卷积网络应用 (二) 图像风格转换
深度学习·ai
BOF_dcb7 小时前
【无标题】
pytorch·深度学习·机器学习
利刃大大7 小时前
【2025年度创作总结】从笔记到实践,从思考到生活融合
笔记·生活
航Hang*8 小时前
Photoshop 图形与图像处理技术——第1章:数字图像基本知识
图像处理·笔记·ui·photoshop
Secede.8 小时前
Windows + WSL2 + Docker + CudaToolkit:深度学习环境配置
windows·深度学习·docker
iconball9 小时前
个人用云计算学习笔记 --37 Zabbix
运维·笔记·学习·云计算·zabbix