一、nn.Conv2d
函数:
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)
代码:
import torch
import torch.nn as nn
x = torch.randn(10, 6, 32, 32) # batch, channel , height , width
print(x.shape)
conv1 = nn.Conv2d(6, 6, 3)# in_channel, out_channel ,kennel_size,stride
conv2 = nn.Conv2d(6, 16, 3)# in_channel, out_channel ,kennel_size,stride
y1 = conv1(x)
y2 = conv2(x)
print(y1.shape)
print(y2.shape)
out:
总结:
例x = torch.randn(10, 6, 32, 32)中的数据分别对应了batch:10 channel:6 height:32 width:32
进行卷积计算的x的channel必须要和nn.Conv2d的in_channel对应,从而进行一个计算。
#卷积公式计算:h/w = (h/w - kennel_size + 2*padding) / stride + 1
参考链接:https://blog.csdn.net/qq_26369907/article/details/88366147
https://blog.csdn.net/PolarisRisingWar/article/details/116069338
二、nn.Linear
函数:
torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
代码:
import torch
x = torch.rand(128,20)
#torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
m = torch.nn.Linear(20,30)
output = m(x)
print(m.weight.shape)
print(m.bias.shape)
print(output.shape)
out:
总结:
x = torch.rand(128,20)中的数据的分别对应为batch:128,feature:20
简单点来说:x有128组数据,一组数据有20个样本
nn.Linear函数的作用是对传入数据应用线性变换及: y = xA^T + by=xAT+b
简单点来说:m是用来把拥有20个特征值的样本输入转变为拥有30个特征值的输出
ps:1.weight为(30,20)的原因是因为计算前要进行一个转至(T)
2.bias为随机数据,与out_feature对应
参考链接:https://pytorch.org/docs/master/generated/torch.nn.Linear.html#torch.nn.Linear
https://blog.csdn.net/qq_42079689/article/details/102873766
三、 torch.flatten
函数:
torch.flatten(input, start_dim=0, end_dim=- 1)
代码:
import torch
input = torch.randn(2, 2,3)
print(input.shape)
x = torch.flatten(input,1)
print(x.shape)
out:
总结:
torch.flatten(t, start_dim=0, end_dim=-1) 的实现原理如下。假设类型为 torch.tensor 的张量 t 的形状如下所示:(2,2,3),则 torch.flatten(t, 1)(ps:1为start_dim).shape 的结果为 (2, 6)。将索引为 start_dim 和 end_dim 之间(包括该位置)的数量相乘,其余位置不变。因为默认 start_dim=0,end_dim=-1,所以 torch.flatten(t) 返回只有一维的数据。
参考链接:https://blog.csdn.net/liangjiu2009/article/details/106219458
新账号文章链接:https://blog.csdn.net/Mr_Suda/article/details/119522560?spm=1001.2014.3001.5501