目录
6 使用torch.optim.lr_scheduler调整学习率
7 CrossEntropyLoss和LabelSmoothing详解
1 Pytorch中dim的理解
总结:
(1) dim表示维度,每一个dim的size看其下一个dim中有几个并列的括号对,例如:
x = torch.randn(2, 3, 3)
print(x)
print(x.size())
print(x.dim())
输出:
tensor([[[-1.6943, -2.1487, 1.2332],
[-0.2261, -0.1596, 1.5513],
[ 2.0383, -0.6982, -2.1481]],
[[ 0.4201, -2.7373, 0.2424],
[-1.1152, 1.3682, -1.8322],
[ 0.1957, -0.2920, 0.1845]]])
torch.Size([2, 3, 3])
3
这里,第一个dim的size是2,是因为第二个dim中有两个并列的括号对,即:
x = torch.randn(2, 3, 3)
print(x)
for i in x:
print(i)
print(i.size())
输出:
tensor([[[-1.4251, -0.8321, 1.0230],
[ 0.2008, 0.5929, -0.7696],
[-0.3721, -1.0837, -0.6642]],
[[-0.5337, 0.7808, 0.4419],
[-0.4683, 0.3847, 0.0747],
[ 1.0156, -0.4933, 1.5340]]])
tensor(
[
[-1.4251, -0.8321, 1.0230],
[ 0.2008, 0.5929, -0.7696],
[-0.3721, -1.0837, -0.6642]
]
)
torch.Size([3, 3])
tensor(
[
[-0.5337, 0.7808, 0.4419],
[-0.4683, 0.3847, 0.0747],
[ 1.0156, -0.4933, 1.5340]
]
)
torch.Size([3, 3])
(2)使用函数给定dim时,表示的是其他维度不变,对该维度进行操作,并去除该维度或使得该维度变化,例如:
import torch
x = torch.randn(2,3)
print(x)
y = torch.argmax(x, dim=0)
print(y)
print(y.size())
输出:
tensor(
[
[ 0.0251, -0.3640, 0.1965],
[ 0.6902, 0.9846, 0.2035]
]
)
tensor([1, 1, 1])
torch.Size([3])
去掉dim = 0,比较的就是 [ 0.0251, -0.3640, 0.1965]
和 [ 0.6902, 0.9846, 0.2035]
dim = (2, 3) -> (3)
2 Pytorch中的初始化函数
3 torch.cat()函数
注意:按照1中dim的规律,在cat()函数中设置哪个dim,对应的dim的size会变化(增加)
4 torch.empty()函数
总结: 返回填充有未初始化数据的张量。 张量的形状由可变的参数大小定义
5 Adam优化器详解
6 使用torch.optim.lr_scheduler调整学习率
注意:一般是调整优化器中的学习率
7 CrossEntropyLoss和LabelSmoothing详解
总结:
(1)调用CrossEntropyLoss(x, y),其中x为预测结果(直接的预测结果,不经过softmax层),y为实际的标签值(整数值,而非one-hot值)
(2)CrossEntropyLoss的快速计算方法:
其中,class为实际的标签值(整数值,而非one-hot值)
8 KL散度的两种调用方法和输入要求
总结:
(1)KL散度的定义、基本性质、应用以及常见分布KL散度的计算
注意:
1)上文的倒数第二段推导存在问题,因为在的分布下,,所以可以得到,故原先的推导变为:
2)一些结论:
当为标准正太分布时,结果简化为:
(2)torch.nn.KLDivLoss(x, y)和torch.nn.functional.kl_div(x, y)实现的计算为:
(3)在使用时,x为经过softmax和log后的预测结果,y是实际标签值的概率分布
(4)需要注意的是,一般只有LabelSmoothing之后才会将y由原来的整数标签值(或one-hot型标签值)转换成标签值的概率分布,即KL散度一般和LabelSmoothing一起使用