官术网_书友最值得收藏!

Installing and using PyTorch 1.x

Like most Python packages, PyTorch is very simple to install. There are two main ways of doing so. The first is to simply install it using pip in the command line. Simply type the following command:

pip install torch torchvision

While this installation method is quick, it is recommended to install using Anaconda instead, as this includes all the required dependencies and binaries for PyTorch to run. Furthermore, Anaconda will be required later to enable training models on a GPU using CUDA. PyTorch can be installed through Anaconda by entering the following in the command line:

conda install torch torchvision -c pytorch

To check that PyTorch is working correctly, we can open a Jupyter Notebook and run a few simple commands:

  1. To define a Tensor in PyTorch, we can do the following:

    import torch

    x = torch.tensor([1.,2.])

    print(x)

    This results in the following output:

    Figure 2.1 – Tensor output

    Figure 2.1 – Tensor output

    This shows that tensors within PyTorch are saved as their own data type (not dissimilar to how arrays are saved within NumPy).

  2. We can perform basic operations such as multiplication using standard Python operators:

    x = torch.tensor([1., 2.])

    y = torch.tensor([3., 4.])

    print(x * y)

    This results in the following output:

    Figure 2.2 – Tensor multiplication output

  3. We can also select inpidual elements from a tensor, as follows:

    x = torch.tensor([[1., 2.],[5., 3.],[0., 4.]])

    print(x[0][1])

    This results in the following output:

Figure 2.3 – Tensor selection output

However, note that unlike a NumPy array, selecting an inpidual element from a tensor object returns another tensor. In order to return an inpidual value from a tensor, you can use the .item() function:

print(x[0][1].item())

This results in the following output:

Figure 2.4 – Output of the .item() function

Tensors

Before we continue, it is important that you are fully aware of the properties of a tensor. Tensors have a property known as an order, which essentially determines the dimensionality of a tensor. An order one tensor is a tensor with a single dimension, which is equivalent to a vector or list of numbers. An order 2 tensor is a tensor with two dimensions, equivalent to a matrix, whereas a tensor of order 3 consists of three dimensions. There is no limit to the maximum order a tensor can have within PyTorch:

Figure 2.5 – Tensor matrix

You can check the size of any tensor by typing the following:

x.shape

This results in the following output:

Figure 2.6 – Tensor shape output

This shows that this is a 3x2 tensor (order 2).

主站蜘蛛池模板: 琼中| 寿光市| 鲁山县| 岚皋县| 武强县| 黑龙江省| 台州市| 游戏| 吉林省| 新宾| 老河口市| 凌源市| 奉化市| 宜宾县| 仙桃市| 望奎县| 丽江市| 抚顺市| 祁连县| 潜山县| 天柱县| 鱼台县| 新密市| 嘉禾县| 金湖县| 上林县| 遂川县| 陇南市| 勐海县| 孝昌县| 汝阳县| 栾城县| 伊吾县| 井研县| 涟水县| 吴旗县| 光泽县| 正蓝旗| 益阳市| 盐津县| 台中市|