list、numpy、tensor(pytorch)常用操作

格式转换

t = torch.from_numpy(n) # numpy 2 tensor
t = torch.Tensor(l)     # list 2 tensor
n = t.numpy()           # tensor 2 numpy
n = numpy.array(l)      # list 2 numpy
l = t.numpy().tolist()  # tensor 2 list
l = n.tolist()          # numpy 2 list
num = t.item()            # tensor 2 num

数据类型转换

t.int() # tensor
t.to(torch.int64) # tensor
a = n.astype(np.int32) # array
l = [int(i) for i in l] # list
l = list(map(int, l)) # list

维度变换

增加维度

t = t.unsqueeze(0) # 新增第零维
t = t.repeat(1, 2, 3) # 第0维维度*1,第1维维度*2,第3维维度*3
n = n[:, :, np.newaxis] # 新增最后一维

维度调整

t = t.permute(2, 0, 1)  # 多维调整
t = t.transpose(0, 1)  # 二维交换
n = n.transpose(2, 0, 1)  # 多维调整
n = n.swapaxes(0, 1)  # 二维交换

创建多个空的子list

正确写法:

l = [[] for i in range(4)]

而不能用:

l = [[], ]*4
# 这种debug看起来和上面的一样,但不能用,就很奇怪
l[0].append(0)
# 结果是:[[0], [0], [0], [0]]

tensor与各种图像格式的相互转化

提取list中某些index的元素

input_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
extract_ids = [0, 1, 5]
get_labels = lambda t: input_list[t]
vlabels = np.vectorize(get_labels)
labels = vlabels(extract_ids)
# labels = array(['a', 'b', 'f'], dtype='

新建tensor指定值

new_tensor = torch.full((1, 2), val)
new_tensor = torch.zeros((1, 2))
new_tensor = torch.zeros_like(old_tensor)
new_tensor = torch.ones((1, 2))
new_tensor = torch.ones_like(old_tensor)

拼接

new_list = list1 + list2  # list
new_array = np.concatenate([array1, array2], 0)  # numpy array
new_tensor = torch.cat((tensor1, tensor2), 0)  # 在指定维度上拼接
new_tensor = torch.stack((tensor1, tensor2))  # 新增维度拼接

list换行写入txt

转载自:PYTHON 写入list并换行的方法

f.writelines(lists) 是不换行的写入,可用以下方法在写入时换行。

# 方法一:
for line in lists:
f.write(line+'\n')

# 方法二:
lists=[line+"\n" for line in lists]
f.writelines(lists)

# 方法三:
f.write('\n'.join(lists))

你可能感兴趣的:(pytorch,numpy,python)