Pytorch学习笔记——神经网络基本框架

发布于:2024-05-08 ⋅ 阅读:(27) ⋅ 点赞:(0)

一、神经网络是什么

神经网络在人工智能和深度学习的领域,一般称为人工神经网络,即ANN(Artificial Neural Network),是一种模仿人脑神经系统工作方式的计算模型。被广泛应用于人工智能、自动控制、机器人、统计学等领域的信息处理中。

二、如何搭建一个属于自己的神经网络

搭建一个神经网络,需要借用torch中的nn模块,也就是Neural Network(神经网络)模块

还是要遵循以下的步骤:导包——构造神经网络骨架(模型)——定义实体类(调用辅助类或函数)——调用输入数据进行训练——得出训练结果

1、导包

import torch
from torch import nn

2、搭建神经网络模型

class W(nn.Module):

    def __init__(self):
        super(W,self).__init__() 

    def forward(self,input):
        output = input + 1
        return output

这个自定义的W神经网络训练模型继承于nn的Module模块。Module模块用于搭建最基本的神经网络骨架,它是所有神经网络模块的基类。

里面需要重写两个函数,一个是构造函数init,一个是前向函数forward(区别于backword反向传播,后面会学习到),super()的作用是调用父类构造函数确保子函数正常运行,在forward中可以写相关的训练操作

可以参考Pytorch的官方文档,里面有对Module的详细介绍

Module — PyTorch 2.3 documentationicon-default.png?t=N7T8https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module

3、利用模型训练

创建神经网络模型实例对象,利用数据进行训练,得出训练结果并输出

注意:输入的类型为tensor张量

w = W()
x = torch.tensor(1.0)

输出的训练结果为tensor张量

tensor(2.)

三、完整代码展示

# -*- coding: utf-8 -*-
# @Author: hxm
import torch
from torch import nn

class W(nn.Module):

    def __init__(self):
        super(W, self).__init__()

    def forward(self,input):
        output = input + 1
        return output

w = W()
x = torch.tensor(1.0)
output = w(x)
print(output)


网站公告

今日签到

点亮在社区的每一天
去签到