终于开始用torch写神经网络啦!
主要用到了python API中的torch.nn
- Container:骨架,对神经网络定义了一些结构,在结构中添加一些内容就可以实现我们的神经网络
后面都是需要往骨架当中填充的东西,比如卷积层、池化层、padding层balabala~
点开container看看
其中最常用的是Module
,我们再点开看看里面的案例:
我们继承了nn.module
这个父类(模板),而对于不满意的部分我们可以自己再进行修改,如果module是玩具赛车,这两个def定义的函数就可以看作是我们更换的马达
用一个例子来解释一下:
import torch
from torch import nn
class Model(nn.Module):
# 方法一:手敲
# def __init__(self):
# super(Model, self).__init__() # 继承父类的init
# 方法二:代码->重写方法->init
def __init__(self):
super().__init__()
# 假设神经网络:输出=输入+1
def forward(self, input):
output = input + 1
return output
# 拿模板创建神经网络
Model = Model()
x = torch.tensor(1.0)
# 这里可以直接调用,而不用Model.forward(x),是因为forward方法是__call__()方法的实现
output = Model(x)
print(output)
输出为
D:\Anaconda3\envs\pytorch\python.exe D:/研究生/代码尝试/nn_module.py
tensor(2.)
进程已结束,退出代码为 0
这样就实现了简单的module使用~