# 5 个PyTorch 中的处理张量的基本函数

“为什么不使用 NumPy 库呢？”

• `torch.tensor()`
• `torch.sum()`
• `torch.index_select()`
• `torch.stack()`
• `torch.mm()`

``````# Import torch and other required modules
import torch``````

## torch.tensor()

``````# Helper function
def describe(x):
print("Type: {}".format(x.type()))
print("Shape/size: {}".format(x.shape))
print("Values: \n{}".format(x)``````

PyTorch 允许我们使用 torch 包以多种不同的方式创建张量。 创建张量的一种方法是通过指定其维度来初始化一个随机张量

``describe(torch.Tensor(2, 3))``

``````x = torch.Tensor([[1, 2, 3],[4, 5, 6]])
describe(x)``````

``````import numpy as np
npy = np.random.rand(2, 3)
describe(torch.from_numpy(npy))``````

``````torch.tensor([[1, 2], [3, 4, 5]])

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
in
1 # Example 3 - breaking (to illustrate when it breaks)
----> 2 torch.tensor([[1, 2], [3, 4, 5]])

ValueError: expected sequence of length 2 at dim 1 (got 3)``````

torch.tensor() 构成了任何 PyTorch 项目的核心，从字面上看，因为它就是张量。

## torch.sum()

``describe(torch.sum(x, dim=0,keepdims=True))``

``````torch.sum(npy,dim=1,keepdims=True)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
in ()
1 # Example 3 - breaking (to illustrate when it breaks)
----> 2 torch.sum(npy,dim=1,keepdims=True)

TypeError: sum() received an invalid combination of arguments - got (numpy.ndarray, keepdims=bool, dim=int), but expected one of:
* (Tensor input, *, torch.dtype dtype)
didn't match because some of the keywords were incorrect: keepdims, dim
* (Tensor input, tuple of ints dim, bool keepdim, *, torch.dtype dtype, Tensor out)
* (Tensor input, tuple of names dim, bool keepdim, *, torch.dtype dtype, Tensor out)``````

## torch.index_select()

``````indices = torch.LongTensor([0, 2])
describe(torch.index_select(x, dim=1, index=indices))``````

rows_of_original_tensor x length_of_indices_tensor。

``````indices = torch.LongTensor([0, 0])
describe(torch.index_select(x, dim=0, index=indices))``````

``````indices = torch.FloatTensor([0, 2])
describe(torch.index_select(x, dim=1, index=indices))``````

## torch.stack()

``describe(torch.stack([x, x, x],dim = 0))``

``describe(torch.stack([x, x, x],dim = 1))``

``````y = torch.tensor([3,3])
describe(torch.stack([x, y, x],dim = 1))

--------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
in ()
1 # Example 3 - breaking (to illustrate when it breaks)
2 y = torch.tensor([3,3])
----> 3 describe(torch.stack([x, y, x],dim = 1))

RuntimeError: stack expects each tensor to be equal size, but got [2, 3] at entry 0 and [2] at entry 1``````

## torch.mm()

``````mat1 =torch.randn(3,2)
describe(torch.mm(x, mat1))``````

``````mat1 = np.random.randn(3,2)
mat1 = torch.from_numpy(mat1).to(torch.float32)
describe(torch.mm(x, mat1))``````

``````mat1 =torch.randn(2,3)
describe(torch.mm(x, mat1))

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
in ()
1 # Example 3 - breaking (to illustrate when it breaks)
2 mat1 =torch.randn(2,3)
----> 3 describe(torch.mm(x, mat1))

RuntimeError: mat1 and mat2 shapes cannot be multiplied (2x3 and 2x3)``````