在Ubuntu 16.04系統上安裝PyTorch

1 安裝

1.1 環境

軟硬件環境很重要:

  • 操作系統:Ubuntu 16.04
  • x86-64處理器,無GPU

1.2 安裝

最權威的安裝方式,當然是按照官網提供的教程。

在這裏插入圖片描述

說明:

  • PyTorch版本:穩定版和預覽版本(未經全面測試和支持)
  • 操作系統:Linux,Mac,Windows
  • 包:Conda,Pip,LibTorch,Source,建議使用Conda
  • 編程語言:Python2.7, Python3.5, Python3.6, Python3.7, C++
  • CUDA:9.2,10.1,無CUDA(即無GPU)
  • 運行的命令

雖然在Linux上默認安裝了Python 3.x,但默認情況下未安裝pip。安裝pip3

sudo apt-get install python3-pip

根據我的軟硬件環境,運行以下命令安裝PyTorch:

sudo pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html

注意:一定要添加sudo命令,否則會出現以下錯誤,然後需要再運行一次,很浪費時間。

ERROR: Could not install packages due to an EnvironmentError: [Errno 13] 權限不夠:

‘/usr/local/lib/python3.5/dist-packages/numpy-1.17.4.dist-info’
Consider using the --user option or check the permissions.

安裝完成後,會輸出以下信息:

Installing collected packages: torch, pillow, torchvision
Successfully installed pillow-6.2.1 torch-1.3.1+cpu torchvision-0.4.2+cpu

1.3 可能遇到的問題

下載numpy時,網速很慢,只有幾十KB,而且容易出現網絡超時錯誤。

下載numpy

Collecting numpy (from torch==1.3.1+cpu)
Downloading https://files.pythonhosted.org/packages/ab/e9/2561dbfbc05146bffa02167e09b9902e273decb2dc4cd5c43314ede20312/numpy-1.17.4-cp35-cp35m-manylinux1_x86_64.whl (19.8MB)

出現網絡超時錯誤:

raise ReadTimeoutError(self._pool, None, ‘Read timed out.’)
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host=‘files.pythonhosted.org’, port=443): Read timed out.

這時,可以嘗試添加--timeout=1000,即:

sudo pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html --timeout=1000

其實,這屬於pip超時問題,可以使用pypi鏡像加快下載速度。

sudo pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy

可以明顯看出,下載速度很快:

Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting numpy
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/ab/e9/2561dbfbc05146bffa02167e09b9902e273decb2dc4cd5c43314ede20312/numpy-1.17.4-cp35-cp35m-manylinux1_x86_64.whl (19.8MB)
|████████████████████████████████| 19.8MB 20.9MB/s

Installing collected packages: numpy
Successfully installed numpy-1.17.4

2 驗證是否安裝成功

爲了確保正確安裝了PyTorch,我們可以通過運行示例PyTorch代碼來驗證安裝。在這裏,我們將構造一個隨機初始化的張量。

from __future__ import print_function
import torch
x = torch.rand(5, 3)
print(x)

輸出應類似於以下內容:

tensor([[0.3380, 0.3845, 0.3217],
        [0.8337, 0.9050, 0.2650],
        [0.2979, 0.7141, 0.9069],
        [0.1449, 0.1132, 0.1375],
        [0.4675, 0.3947, 0.1426]])

此外,要檢查PyTorch是否啓用了GPU驅動程序和CUDA並可以訪問它,請運行以下命令:

import torch
torch.cuda.is_available()

查看PyTorc版本:

print(torch.__version__)

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章