以下内容大部分来自b站up主“我是土堆”,只是一个粗浅总结,所以是小儒专用
1、神经网络基本骨架Containers——nn.Module
官方链接:nn.Model
nn.Module是对所有神经网络提供一个基本的类。
创建一个自己的Model类,继承nn.Model类。
import torch
from torch import nn
class XiaoRu(nn.Module):
def __init__(self):
super(XiaoRu, self).__init__() # 继承父类的初始化
def forward(self,input):
output = input +1
return output
xiaoguo = XiaoRu()
x = torch.tensor(1.0) # 创建一个值为 1.0 的tensor张量
output = xiaoguo(x) #使用pytorch的时候,不需要手动调用forward函数,只要在实例化一个对象中传入对应的参数就可以自动调用 forward 函数。
使用debug的步骤:
先在想分析的代码前面打上一个红点点
然后点击ladybug的按钮,pycharm下方进入到调试界面
然后按单步执行我的代码,一步一步分析代码运行
2、卷积原理
torch.nn官方链接:链接
torch.nn 和 torch.nn.function 的区别:
torch.nn 相当于 torch.nn.function 的封装,用起来更加简便一些。
torch.nn.function 里面有一些底层的卷积的内容,便于学习。
通道数channel含义的理解:good
import torch
import torch.nn.functional as F
# 创建一个张量input,其中括号里面中括号最开始有几个就是几维
input = torch.tensor([[1, 2, 0, 3, 1],
[0, 1, 2, 3, 1],
[1, 2, 1, 0, 0],
[5, 2, 3, 1, 1],
[2, 1, 0, 1, 1]])
print(input.shape) # torch.Size([5, 5]),但是conv2d要求输入数据是4维:(\text{minibatch一个batch中样本的数量} , \text{in\_channels通道数,取决于样本的通道,比如RGB图像的通道数是3} , iH , iW)
input = torch.reshape(input,(1,1,5,5))
#创建一个卷积核张量
kernel = torch.tensor([[1, 2, 1],
[0, 1, 0],
[2, 1, 0]])
print(kernel.shape)
kernel = torch.reshape(kernel,(1,1,3,3))
output = F.conv2d(input, kernel, stride=1) # stride:步幅
print(output)
① 步幅:卷积核经过输入特征图的采样间隔。设置步幅的目的:希望减小输入参数的数目,减少计算量。
② 填充:在输入特征图的每一边添加一定数目的行列。设置填充的目的:希望每个输入方块都能作为卷积窗口的中心,或使得输出的特征图的长、宽 = 输入的特征图的长、宽。
③ 一个尺寸 a * a 的特征图,经过 b * b 的卷积层,步幅(stride)= c,填充(padding)= d,若d等于0,也就是不填充,输出的特征图的尺寸 =(a-b)/ c+1;若d不等于0,也就是填充,输出的特征图的尺寸 =(a+2d-b)/ c+1。
参考连接:里面有动图
待补充:王木头的视频内容学习总结+一维卷积的思考
3、神经网络-卷积层
主要讲解nn.Conv2d
各种函数
1、torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
import torch.nn as nn
# 输入2维Tensor
input = torch.rand(4,3) # 随机生成输入的Tensor,这里input是二维变量,shape(4,3)
linearNet = nn.Linear(3,5) #(in_features,out_features)
# in_feaature = 3 是输入变量的最后一维的通道数,表示输入3个样本,每个样本是(4,)的向量
# out_feature = 5 是输出变量的最后一维的通道数,表示输出5个样本,每个样本的形状和输入样本相同
output = linearNet(input)
print(output.size())
print(linearNet.weight) # 查看初始权重,(out_features,in_features)
print(linearNet.bias) # 查看初始偏置项 (N,out_features)