PyTorch 教程-PyTorch基础
现在,逐一理解所有这些概念,以深入了解PyTorch。
矩阵或张量
上面的矩阵表示具有三行和两列的2D张量。
使用数组创建PyTorch张量
创建包含全部为1和随机数的张量
从NumPy数组创建张量
让我们看看如何创建张量
👉点击领取:最全Python资料合集
创建一个PyTorch张量作为数组
在这种情况下,您首先必须定义数组,然后将该数组作为参数传递给torch的Tensor方法。
import torcharr = [[3, 4], [8, 5]]pyTensor = torch.Tensor(arr)print(pyTensor)
tensor ([[3., 4.],[8., 5.]])
创建具有随机数和全部为1的张量
要创建一个具有随机数的张量,您必须使用rand()方法,要创建一个全部为1的张量,您必须使用torch的ones()。为了生成随机数,torch的rand之外还将使用带有0参数的manual_seed方法。
import torchones_t = torch.ones((2, 2))torch.manual_seed(0) //to have same values for random generationrand_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数组创建张量
要从NumPy数组创建张量,我们必须创建一个NumPy数组。一旦创建了NumPy数组,我们必须将其作为参数传递给from_numpy()。此方法将NumPy数组转换为张量。
import torchimport numpy as np1numpy_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) 改变张量的大小
我们可以使用张量的size属性来调整张量的大小。我们使用Tensor.view()来调整张量的大小。调整张量的大小意味着将2x2维张量转换为4x1或4x4维张量转换为16x1等。要打印张量的大小,我们使用Tensor.size()方法。
import torchpyt_Tensor = torch.ones((2, 2))print(pyt_Tensor.size()) # shows the size of this Tensorpyt_Tensor = pyt_Tensor.view(4) # resizing 2x2 Tensor to 4x1print(pyt_Tensor)
torch.Size ([2, 2])tensor ([1., 1., 1., 1.])
2) 数学运算
让我们看一个数学运算如何执行的示例:
import numpy as npimport torchTensor_a = torch.ones((2, 2))Tensor_b = torch.ones((2, 2))result=Tensor_a+Tensor_bresult1 = torch.add(Tensor_a, Tensor_b) //another way of addidtionTensor_a.add_(Tensor_b) // In-place additionprint(result)print(result1)print(Tensor_a)
tensor ([[2., 2.], [2., 2.]])tensor ([[2., 2.], [2., 2.]])
3) 均值和标准差
我们可以计算张量的标准差,无论是一维还是多维。在我们的数学计算中,我们首先要计算均值,然后在给定的数据上应用以下公式。
让我们看一个计算的示例。
import torchpyTensor = torch.Tensor([1, 2, 3, 4, 5])mean = pyt_Tensor.mean(dim=0) //if multiple rows then dim = 1std_dev = pyTensor.std(dim=0) // if multiple rows then dim = 1print(mean)print(std_dev)
输出:
tensor (3.)tensor (1.5811)
变量和梯度
通过.data属性,您可以访问原始张量,而此变量的梯度累积到.grad中。
下面是用于管理变量的Python代码。
import numpy as npimport torchfrom torch.autograd import Variablepyt_var = Variable(torch.ones((2, 2)), requires_grad = True)
上述代码的行为与张量相同,因此我们可以以相同的方式应用所有操作。
示例
import numpy as npimport torchfrom torch.autograd import Variable// let's consider the following equation// y = 5(x + 1)^2x = Variable (torch.ones(1), requires_grad = True)y = 5 * (x + 1) ** 2 //implementing the equation.y.backward() // calculate gradientprint(x.grad) // get the gradient of variable x# differentiating the above mentioned equation// => 5(x + 1)^2 = 10(x + 1) = 10(2) = 20
输出:
tensor([20.])
热门推荐