一、shape && size
shape
和size
是在numpy中使用的属性/方法
- shape:返回矩阵的形状
- size:返回矩阵内元素的个数
shape
和size
在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()
二、numpy && tensor互转
1. numpy—>tensor
tensor = torch.from_numpy(array)
2. tensor—>numpy
array = tensor.numpy()