📅  最后修改于: 2023-12-03 15:34:33.150000             🧑  作者: Mango
PyTorch is an open source machine learning framework that was developed by Facebook's AI Research team. It is based on Torch, which is a scientific computing framework.
PyTorch provides two main features:
To install PyTorch, you need to have Python installed on your system. You can install PyTorch using pip
by running the following command:
pip install torch
You can also install PyTorch using Anaconda by running the following command:
conda install pytorch torchvision -c pytorch
Let's start by importing PyTorch and creating a simple tensor:
import torch
x = torch.tensor([[1, 2], [3, 4]])
print(x)
Output:
tensor([[1, 2],
[3, 4]])
We can also create tensors of a specific size and type:
# Create a tensor of size 3x3 with random values
x = torch.rand(3, 3)
print(x)
# Create a tensor of size 2x2 with zeros
x = torch.zeros(2, 2)
print(x)
# Create a tensor of size 2x2 with ones
x = torch.ones(2, 2)
print(x)
# Create a tensor of size 2x2 with a specific value (5)
x = torch.full((2, 2), 5)
print(x)
# Create a tensor of size 2x2 with values from a normal distribution (mean=0, std=1)
x = torch.randn(2, 2)
print(x)
Output:
tensor([[0.6176, 0.5149, 0.9247],
[0.2104, 0.3562, 0.1681],
[0.2510, 0.1128, 0.6265]])
tensor([[0., 0.],
[0., 0.]])
tensor([[1., 1.],
[1., 1.]])
tensor([[5, 5],
[5, 5]])
tensor([[-1.0983, -0.3215],
[ 1.2306, -0.6546]])
PyTorch provides a module called autograd
, which allows for automatic differentiation of tensors. This means that it can compute the gradient of any function with respect to its inputs.
Let's create a tensor and compute its gradient:
import torch
x = torch.tensor([2.0], requires_grad=True)
y = x**2 + 3*x + 1
y.backward()
print(x.grad)
Output:
tensor([7.])
In this example, x
is a tensor with a value of 2. We set requires_grad=True
to enable gradient computation for x
. We then create a new tensor y
, which is a function of x
. In this case, y
is a polynomial function. Finally, we call the backward
method on y
to compute its gradient with respect to x
. We can then use x.grad
to get the gradient of y
with respect to x
.
In this tutorial, we introduced PyTorch and its main features. We demonstrated how to install PyTorch and how to create and manipulate tensors. We also showed how to use automatic differentiation to compute the gradient of a function with respect to its inputs. PyTorch is a powerful tool for building and training deep neural networks, and we hope that this tutorial has helped you get started with PyTorch!