PyTorch基础概念：张量用法详解

矩阵或张量

1. 创建PyTorch张量数组
2. 创建一个全张量和随机数的张量
3. 从numpy数组创建Tensor

将PyTorch张量创建为数组

``````import torch
arr = [[3, 4], [8, 5]]
pyTensor = torch.Tensor(arr)
print(pyTensor)``````

``tensor ([[3., 4.], [8., 5.]])``

用随机数和全部创建一个张量

``````import torch
ones_t = torch.ones((2, 2))
torch.manual_seed(0)  //to have same values for random generation
rand_t = torch.rand((2, 2))
print(ones_t)
print(rand_t)``````

``````Tensor ([[1., 1.], [1., 1.]])
tensor ([[0.4963, 0.7682], [0.0885, 0.1320]])``````

从numpy数组创建张量

``````import torch
import numpy as np1
numpy_arr = np1.ones((2, 2))
pyTensor = torch.from_numpy(numpy_arr)
np1_arr_from_Tensor = pyTensor.numpy()
print(np1_arr_from_Tensor)``````

``[[1. 1.] [1. 1.]]``

张量运算

1)调整张量

``````import torch
pyt_Tensor = torch.ones((2, 2))
print(pyt_Tensor.size())        # shows the size of this Tensor
pyt_Tensor = pyt_Tensor.view(4) # resizing 2x2 Tensor to 4x1
print(pyt_Tensor)``````

``````torch.Size ([2, 2])
tensor ([1., 1., 1., 1.])``````

2)数学运算

``````import numpy as np
import torch
Tensor_a = torch.ones((2, 2))
Tensor_b = torch.ones((2, 2))
result=Tensor_a+Tensor_b
print(result)
print(result1)
print(Tensor_a)``````

``````tensor ([[2., 2.], [2., 2.]])
tensor ([[2., 2.], [2., 2.]])``````

3)均值和标准差

``````import torch
pyTensor = torch.Tensor([1, 2, 3, 4, 5])
mean = pyt_Tensor.mean(dim=0)        //if multiple rows then dim = 1
std_dev = pyTensor.std(dim=0)       // if multiple rows then dim = 1
print(mean)
print(std_dev)``````

``````tensor (3.)
tensor (1.5811)``````

变量和梯度

``````import numpy as np
import torch
pyt_var = Variable(torch.ones((2, 2)), requires_grad = True)``````

例子

``````import numpy as np
import torch
// let's consider the following equation
// y = 5(x + 1)^2
x = Variable (torch.ones(1), requires_grad = True)
y = 5 * (x + 1) ** 2        //implementing the equation.
# differentiating the above mentioned equation
// => 5(x + 1)^2 = 10(x + 1) = 10(2) = 20``````

``tensor([20.])``