shape和size

@TOC

一、shape && size

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

  • shape:返回矩阵的形状
  • size:返回矩阵内元素的个数

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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()

Error: Not Found