python 近期用到的基础知识汇总(四)

1.python中 return 的用法:return 语句就是讲结果返回到调用的地方,并把程序的控制权一起返回 程序运行到所遇到的第一个return即返回(退出def块),不会再运行第二个return。

代码实测搞清楚:

def test_return(x):
    for i in range(3):
        print(1)
        if x > 0:
            return x

test_return(-1)

1
1
1


def test_return(x):
    for i in range(3):
        print(1)
        if x > 0:
            return x

test_return(1)

1

可以看出return后直接退出def块,要实现循坏要将其替代掉

2.pytorch中nn.ReLU(inplace=True)含义

在例如nn.LeakyReLU(inplace=True)中的inplace字段是什么意思呢?有什么用?

inplace=True的意思是进行原地操作,例如x=x+5,对x就是一个原地操作,y=x+5,x=y,完成了与x=x+5同样的功能但是不是原地操作,上面LeakyReLU中的inplace=True的含义是一样的,是对于Conv2d这样的上层网络传递下来的tensor直接进行修改,好处就是可以节省运算内存,不用多储存变量y

3.np.rot90()矩阵旋转90°或90°的倍数。默认逆时针旋转。

Examples
--------
>>> m = np.array([[1,2],[3,4]], int)
>>> m
array([[1, 2],
       [3, 4]])
>>> np.rot90(m)
array([[2, 4],
       [1, 3]])
>>> np.rot90(m, 2)
array([[4, 3],
       [2, 1]])

上面的参数2代表转2次90,如果想要顺时针2次90可用-2替代。

当上面的升级到3d时候

>>> m = np.arange(8).reshape((2,2,2))
>>> np.rot90(m, 1, (1,2))
array([[[1, 3],
        [0, 2]],
       [[5, 7],
        [4, 6]]])

前面的1参数已经介绍过了,这里主要介绍下后面的(1,2)这里代表第二维度和第三维的组成的面来旋转。参数前后顺序可以用

rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1))
rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))

(1,0)与(0,1)在当两个k为相反数的时候相等。

3d旋转实例如下:

import numpy as np
m = np.arange(8).reshape((2,2,2))
print('before',m[:,:,0])
p=np.rot90(m, 1, (0,1))
print('after',p[:,:,0])

before [[0 2]
 [4 6]]
after [[2 6]
 [0 4]]

还要特别注意

flip : Reverse the order of elements in an array along the given axis.反向沿给定轴反转数组中元素的顺序(跟前面的[:,::-1,:]翻转第二维度是等效的)
fliplr : Flip an array horizontally.水平翻转阵列
flipud : Flip an array vertically.垂直翻转数组
m1=np.copy(m)
mp=m[::-1,:,:]
print('compare',mp[:,:,0])
m1p=np.flip(m1,0)
print('compare1',m1p[:,:,0])
compare [[4 6]
 [0 2]]
compare1 [[4 6]
 [0 2]]

4.set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

例子:

import random

h = set()
while (len(h) < 10):
    h.add(random.randint(10, 100))

print(h)

{99, 36, 37, 70, 72, 73, 44, 28, 13, 60}

5.isinstance()判断某个对象是否属于某个类

如assert isinstance(output_size, (int, tuple))

判断output_size是int或tuple.都不是assert报错.

6.torch.mul() 和 torch.mm() 的区别.torch.mul(a, b)是矩阵a和b对应位相乘,a和b的维度必须相等,torch.mm(a, b)是矩阵a和b矩阵相乘.要求衔接维度相同.

import torch

a = torch.rand(3, 2)
b = torch.rand(3, 2)
c = torch.rand(2, 3)

print(torch.mul(a, b))  # 返回 3*2 的tensor,要求a,b各维度大小相同
print(torch.mm(a, c))   # 返回 3*3 的tensor,要求a,c的衔接维度相同(a的第二维度和c的第一维度)

猜你喜欢

转载自blog.csdn.net/qq_36401512/article/details/88714627