从零实现深度神经网络的正向传播

该博客介绍了如何使用PyTorch构建一个具有两隐藏层的神经网络,输入500个样本的20个特征,进行3类分类任务。模型结构包括13个神经元的第一层,ReLU激活,8个神经元的第二层,Sigmoid激活,以及最后的输出层。代码展示了模型定义、随机种子设置、数据生成以及模型前向传播的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

500个数据,20个特征,标签为3分类,

网络架构:第一层13个神经元,第二层8个,第三层输出

第一层激活函数relu,第二层 。

import torch
import torch.nn as nn
from torch.nn import functional as F

torch.random.manual_seed(22)
x = torch.rand((500,20),dtype=torch.float32)
y = torch.randint(low=0,high=3,size=(500,1),dtype=torch.float32)

class Model(nn.Module):
    def __init__(self,in_features=10,out_features=2):
        """
        :param in_features: input feature count
        :param out_features: output feature count
        """
        super(Model, self).__init__()# copy init in nn.Module,
        self.linear1 = nn.Linear(in_features,13)
        self.linear2 = nn.Linear(13,8)
        self.output = nn.Linear(8,out_features)
    def forward(self,x):
        """
        nn forward propagat
        Run each layer and add activation function
        :param x:
        :return:
        """
        z1 = self.linear1(x)
        relu1 = torch.relu(z1)
        z2 = self.linear2(relu1)
        sigma1 = torch.sigmoid(z2)
        out = self.output(sigma1)
        softmax1 = F.softmax(out,dim=1)
        return softmax1

if __name__ == '__main__':
    # instantiation nn
    torch.random.manual_seed(22)
    net = Model(in_features=x.shape[1],out_features=len(y.unique()))
    print(net.forward(x))
    print(net.linear1.weight.shape)
    print(net.linear2.weight.shape)
    print(net.output.weight.shape)



关于super,Model是nn.Module的子类,会继承其父类的方法(init之外的方法),但是无法继承父类的init之内的属性,所以这里要用super。

nn.apply() # 对神经网络中的所有层,init中的所有对象都执行相同的操作

nn.parameters() # 神经网络生成的所有参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

happydog007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值