- tensor, numpy array, list之间切换
ndarray = np.array(list) # list 转 numpy数组
list = ndarray.tolist() # numpy 转 list
tensor=torch.Tensor(list) # list 转 torch.Tensor
list = tensor.numpy().tolist() # torch.Tensor 转 list 先转numpy,后转list
ndarray = tensor.cpu().numpy() # torch.Tensor 转 numpy *gpu上的tensor不能直接转为numpy
tensor = torch.from_numpy(ndarray) # numpy 转 torch.Tensor
-
关于Pytorch几种定义网络的方法
- pytorch模型的加载方式
碎片篇——Pytorch模型 .pt, .pth, .pkl的区别及模型不同保存加载方式的区别_姜一诚的博客-优快云博客
- 使用torchvision.models
"""
如果你需要用预训练模型,设置pretrained=True
如果你不需要用预训练模型,设置pretrained=False,默认是False,你可以不写
"""
class VGG16GAP(nn.Module):
def __init__(self):
super(VGG16GAP, self).__init__()
self.backbone = torchvision.models.vgg16_bn()
self.backbone.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096,4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096,200)
)
- 库函数方法总结
index_select:pytorch中index_select()的用法_g_blink的博客-优快云博客,按条件筛选
argsort:Python3:numpy模块中的argsort()函数_WordZzzz-优快云博客,返回从小到大的索引值。
distance.cdist:求距离2——distance.cdist()方法,返回距离值_祝鹏辉-优快云博客,求各种距离。
input():Python3.x 中 input() 函数,默认接收到的是 str 类型。Python2.x 中 input() 相等于 eval(raw_input(prompt)) ,输入纯数字,返回纯数字,输入加引号的字符串,返回字符串。raw_input() 将所有输入作为字符串看待,返回字符串类型。input([prompt])或raw_input([prompt]),其中[prompt]为可选的提示信息。
map(function, iterable, ...):其主要作用,就是对迭代对象中每一个元素,利用function函数做一次运算,然后然后将返回结果为了一个新的可迭代对象。https://www.runoob.com/python/python-func-map.html
- 对list逆序遍历。
lists = [0, 1, 2, 3, 4, 5]
# 输出 5, 4, 3, 2, 1, 0,或者直接lists.reverse(),但会直接对lists操作。
for i in range(5, -1, -1):
print(lists[i]) # 或lists[::-1]
- Python获取每一位的数字,并返回到列表。Python获取每一位的数字,并返回到列表_bangquanou9433的博客-优快云博客
def num2str(value):
return list(map(int, str(value)))#map()中的function为int(),迭代对象为str。
- Python两个字典键同则值相加的几种方法
>>> A = {'a': 1, 'b': 2, 'c': 3}
>>> B = {'b': 4, 'c': 6, 'd': 8}
>>> for key,value in B.items(): # 字典的items()返回可遍历的元组的数组
... if key in A:
... A[key] += value # 在A中修改
... else:
... A[key] = value
>>> dict(sorted(A.items(), key=lambda d:d[1])) # lambda函数功能是取value值,sorted按此排序
{'a': 1, 'b': 6, 'd': 8, 'c': 9}
- 去尾法保留两位小数:python 保留两位小数方法 - 静静别跑 - 博客园
a = 12.345
str(a).split('.')[0] + '.' + str(a).split('.')[1][:2]
'12.34'
- 在一个字符串中查找所有指定字串的位置:
def find_all(all_str, sub_str):
'''查找所有子串位置'''
index_list = []
index = s.find(sub_str)
sub_len = len(sub_str)
while index != -1:
index_list.append(index) # 记录当前找到的位置
index = all_str.find(sub_str, index + sub_len) # 改变查找范围,查找下一个
if len(index_list) > 0:
return index_list
else:
return -1
# str.find(str, beg=0, end=len(string))方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1
- [[0]*n]*m 和[[0 for _ in range(n)] for _ in range(m)]
两个表面上结果一致,但[[0]*n]*m这种方式是直接将[0]*n复制了m遍,是=号复制(注意不是浅拷贝,=与浅拷贝的list id是不同的),若[0]*n发生了更改,则m个都发生更改。python创建数组[[0]*n]*m与[[0 for _ in range(n)] for _ in range(m)]的区别_别说话写代码的博客-优快云博客
- 找到d中非零元素的索引
#d = [1,2,3,0,0,4],找到d中非零元素的索引
for i,e in enumerate(d):
if e!=0:
print(i)
- torch.cat和torch.stack的区别:
torch.cat不会产生新的维度,只是相应维度的数值上增加,torch.stack上会增加一个维度。两个二维stack后输出三维torch.cat与torch.stack的区别_沐风大大的博客-优快云博客
注意:stack()函数在dim=-1时,是将单个元素进行stack,效果就是将多个数组中的每一个元素进行拼接。
torch.stack()的使用_张先生-您好的博客-优快云博客
- torch中的常见函数
torch中tensor.max()/min() 函数在指定维度dim后返回的是两个数据,一个是最大最小值,一个是最大最小值的索引。
torch/numpy中的数组索引是支持列表或由range生成的可迭代对象的
torch.as_tensor(boxes),将boxes从numpy转换为tensor,与torch.from_numpy()一致,和数组共享内存,使用数组创建新的tensor可以使用torch.tensor()。Pytorch张量的主要方法之间的区别(Tensor、tensor、from_numpy、as_tensor)_乐亦亦乐的博客-优快云博客_torch.as_tensor
type_as()将转换后的tensor再次转换为指定类型的tensor(比如FloatTensor转换为IntTensor)
tensor.clone()不提供数据内存共享,但提供梯度追溯功能,而tensor.detach又“舍弃”了梯度回溯功能,虽然提供了共享内存,因此clone.detach()只做简单的数据复制,既不数据共享,也不梯度共享,从此两个张量无关联。Pytorch之clone(),detach(),new_tensor(),copy_()_一个小呀小可爱的博客-优快云博客
pytorch 两个不同纬度的Tensor相减是怎么实现的?
dim小的会复制到和dim大的一方相同,再相减.
pytorch 两个不同纬度的Tensor相减是怎么实现的?_页页读-优快云博客
numpy.nan_to_num
使用0代替数组x中的nan元素,使用有限的数字代替inf元素
求二维数组中每一列或者每一行的最大值,最小值
rowMax = list(map(max, grid))#行最大值
colMax = list(map(max, zip(*grid)))#列最大值
rowMax = list(map(min, grid))#行最小值
colMax = list(map(min, zip(*grid)))#列最小值