shape 和 size
pytorch
本文字数:242 字 | 阅读时长 ≈ 1 min

shape 和 size

pytorch
本文字数:242 字 | 阅读时长 ≈ 1 min

1. shape && size

shapesize 是在 numpy 中使用的属性/方法

shapesize 在 tensor 中也可以使用,均返回矩阵的形状

import torch
import numpy as np

tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
array = np.array([[1, 2, 3], [4, 5, 6]])

# size和shape作为tensor的方法和属性
print("tensor.size():       ", tensor.size())
print("tensor.shape:        ", tensor.shape)
'''
tensor.size():        torch.Size([2, 3])
tensor.shape:         torch.Size([2, 3])
'''


# size和shape作为array的属性
print("array.size:          ", array.size)
print("array.shape:         ", array.shape)
'''
array.size:           6
array.shape:          (2, 3)
'''


# size和shape作为array的方法
print("np.size(array):      ", np.size(array))
print("np.size(array, 0):   ", np.size(array, 0))
print("np.size(array, 1):   ", np.size(array, 1))
print("np.shape(array):     ", np.shape(array))
'''
np.size(array):       6
np.size(array, 0):    2
np.size(array, 1):    3
np.shape(array):      (2, 3)
'''


# torch_data = torch.from_numpy(np_data)
# tensor2array = torch_data.numpy()

2. numpy && tensor 互转

2.1 numpy–>tensor

tensor = torch.from_numpy(array)

2.2 tensor–>numpy

array = tensor.numpy()

4月 06, 2025
3月 10, 2025
12月 31, 2024