【Python】Numpy torch Tensor

Numpy

新建维度

arr = np.array((1,2,3,4,5,6))
print(arr.shape)  # (6,)
arr1 = arr[np.newaxis, :] # == np.expand_dims(arr, axis=0) 
print(arr1.shape) # (1, 6)
arr2 = arr[:, np.newaxis] # == np.expand_dims(arr, axis=1)
print(arr2.shape) # (6, 1)
arr3 = arr2.reshape(2,-1)
print(arr3.shape) # (2, 3)
arr4 = arr3[:, np.newaxis,:]
print(arr4.shape) # (2, 1, 3)
arr5 = np.expand_dims(arr4, axis=0)
print(arr5.shape) # (1, 2, 1, 3)

a=np.array([[1,2,3],[4,5,6]])
b=np.array([[11,21,31],[7,8,9]])
a = a[:,:,np.newaxis]
b = b[:,:,np.newaxis]
np.concatenate((a,b),axis=2)
array([[[ 1, 11],
        [ 2, 21],
        [ 3, 31]],
       [[ 4,  7],
        [ 5,  8],
        [ 6,  9]]])

a = np.array(([1,2,3],[3, 4, 5]))
a.ndim		# 返回其有几个维度

torch

src = torch.from_numpy(src)		# 将numpy变为tensor
print(src.ndimension())		# 3
print(src.size())		# torch.Size([6000, 8192, 3])	# 此处为图片
x.unsqueeze(0) # 在0位置加一维 即最外面加一维

x = torch.randn(2, 3, 5) 
x.size() 	# torch.Size([2, 3, 5]) 
x.permute(2, 0, 1).size() 	# torch.Size([5, 2, 3])
x.contiguous() # 把tensor变成在内存中连续分布的形式。
# torch.view等方法操作需要连续的Tensor 因此更换了维度的张量一般需要contiguous一下

clone
bboxes.new_tensor([1,2,3])	生成一个tensor,内容是1,2,3 类型和属性与bboxes一致





使用einops库

from einops import rearrange, reduce, repeat
# 按给出的模式重组张量
output_tensor = rearrange(input_tensor, 't b c -> b c t')
# 结合重组(rearrange)和reduction操作
output_tensor = reduce(input_tensor, 'b c (h h2) (w w2) -> b h w c', 'mean', h2=2, w2=2)
# 沿着某一维复制
output_tensor = repeat(input_tensor, 'h w -> h w c', c=3)

你可能感兴趣的:(Python,深度学习,numpy,python)