利用torch.nn.module建立简单神经网络框架

这里的nn表示neural network的意思。自己的神经网络均是nn.Module的子类,即搭建的神经网络用类的方式实现,以下是代码:

# torch.nn表示torch提供的神经网络框架,nn表示neural network
# Module 为所有神经网络的一个基本类,当搭建自己的网络时需要引用

# 以下搭建一个简单的神经网络
import torch
import numpy as np
import torch.nn as nn


class My_nn(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        return x + 1


if __name__ == '__main__':
    my = My_nn()  # 实例化神经网络

    # 两种方法正向传播,一种是用my.forward()调用
    # 输入是tensor数组
    input_x = torch.tensor([[1, 2, 3], [4, 5, 6]])
    out_x = my.forward(input_x)
    print(out_x)
    print(type(out_x))  # <class 'torch.Tensor'>

    # 输入是numpy数组
    input_x = np.array([[1, 2, 3], [4, 5, 6]])
    out_x = my.forward(input_x)
    print(out_x)
    print(type(out_x))  # <class 'numpy.ndarray'>

    # 另外一种正向传播方法是直接给实例化的类输入参数,如my(input_x):
    input_x = torch.tensor([[1, 2, 3], [4, 5, 6]])
    out_x = my(input_x)
    print(out_x)
    print(type(out_x))  # <class 'torch.Tensor'>

注意,目前的神经网络框架只定义了forward即正向传播。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值