*args和**kwargs
model.name_parameters()
model.name_parameters中包含该模型的所有参数,以及其是否参与梯度运算。
model = DarkNet([1, 2, 8, 8, 4])
for name, param in model.named_parameters():
print(name,param.requires_grad)
param.requires_grad = False
输出结果为:
conv1.weight True
bn1.weight True
bn1.bias True
layer1.ds_conv.weight True
layer1.ds_bn.weight True
layer1.ds_bn.bias True
layer1.residual_0.conv1.weight True
layer1.residual_0.bn1.weight True
layer1.residual_0.bn1.bias True
layer1.residual_0.conv2.weight True
····
代码参考:原文链接
torch中的clone()和detach()
clone()和detach()都是对Tensor进行的复制操作。二者的不同之处在于复制Tensor后,新的Tensor是否与原Tensor共享内存以及是否仍需要计算梯度。
下图清晰的展现了二者的区别:
Reference & Experiments
//(地板除)
在python中使用双斜杠出发,代表抹去小数部分,只保留证书部分。
如:
5 // 2 = 2 (5 ÷ 2 = 2.5)
5 // 3 = 1 (5 ÷ 3 = 1.6666666666666667)
expand_as()
将Tensor扩展为其他Tensor的大小。
x = torch.rand(1,2,3,1)
y = torch.rand(1,2,1,1)
print(x)
print(y)
y = torch.expand_as(x)
print(y)
输出:
tensor([[[[0.6562, 0.2285, 0.5095],
[0.7477, 0.4172, 0.4819],
[0.4797, 0.6547, 0.7803]],
[[0.0496, 0.7345, 0.8254],
[0.9246, 0.5301, 0.0871],
[0.9279, 0.9954, 0.7164]]]])
tensor([[[[0.8026],
[0.2089],
[0.8383]],
[[0.6787],
[0.2688],
[0.5040]]]])
tensor([[[[0.8026, 0.8026, 0.8026],
[0.2089, 0.2089, 0.2089],
[0.8383, 0.8383, 0.8383]],
[[0.6787, 0.6787, 0.6787],
[0.2688, 0.2688, 0.2688],
[0.5040, 0.5040, 0.5040]]]])
Linux中后台运行python代码
参考博客: Nohup
字典的items()函数
将字典返回可以遍历的元组。
示例用法:
dict = {'en':'hello','zh':'你好'}
for key,value in dict.items():
print(key,value)
输出结果为:
en hello
zh 你好