Python Coding Skills

*args和**kwargs

*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共享内存以及是否仍需要计算梯度。
下图清晰的展现了二者的区别:
Differences
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 你好
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值