这里的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即正向传播。