文章目录
前言
前面编写了一篇文章,描述在Ubuntu20.04.2系统采用python3.10.6安装tensorflow的过程,当时根据前辈的文章选择在虚拟环境中安装,这样的好处就是不会对工作环境产生影响。本文安装pytorch采用直接在python中安装,主要考虑后期主要用pytorch框架来工作。但是为了学习RK3588的RKNN-Toolkit2需要tensorflow/torch/torchvision/opencv-python/onnx这些依赖,我在虚拟环境中pytorch再安装一遍。
一、pytorch安装
首先进入pytorch官方网页:https://pytorch.org/。根据自身系统、打包方式、语言和硬件情况,官网会生成下载的命令。
将红框内的命令输入bash。
pi@NanoPi-R6S:/opt$ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
#整个过程安装还算顺利,出现1个warning:
WARNING: The scripts convert-caffe2-to-onnx, convert-onnx-to-caffe2 and torchrun are installed in '/home/pi/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
#安装结果:
Successfully installed torch-1.13.1 torchaudio-2.0.0 torchvision-0.1.6 typing-extensions-4.4.0
二、pytorch安装检验
进入python命令行,验证pytorch是否可以导入:
pi@NanoPi-R6S:/opt$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> print(torch.__version__)
1.13.1
同时测试下tensorflow,由于它是安装在虚拟环境,因此引入时报错
>>> import tensorflow as tf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tensorflow'
三、在虚拟环境中安装pytorch
3.1 安装Python虚拟环境
sudo apt install python3-venv python3-dev
3.2创建文件夹存储虚拟环境
pi@NanoPi-R6S:/opt$ mkdir torch_envrionment
pi@NanoPi-R6S:/opt$ cd torch_envrionment/
pi@NanoPi-R6S:/opt/torch_envrionment$
3.3在文件夹创建虚拟环境
python3 -m venv torch_env
source torch_env/bin/activate
#其结果:
(torch_env) pi@NanoPi-R6S:/opt/torch_envrionment$
3.4 检验下虚拟环境中是否有pytorch
(torch_env) pi@NanoPi-R6S:/opt/torch_envrionment$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'torch'
在虚拟环境中没有pytorch
3.5 安装pytorch
(torch_env) pi@NanoPi-R6S:/opt/torch_envrionment$ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
#安装过程使用cache中数据,比第一次安装速度快,而且没有warning
Successfully installed torch-1.13.1 torchaudio-2.0.0 torchvision-0.1.6 typing-extensions-4.4.0
3.6 重新检验下pythorch引用
(torch_env) pi@NanoPi-R6S:/opt/torch_envrionment$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> print(torch.__version__)
1.13.1
#安装成功
3.7 退出python命令行
exit()
3.8 退出虚拟环境命令
deactivate
(torch_env) pi@NanoPi-R6S:/opt/torch_envrionment$ deactivate
pi@NanoPi-R6S:/opt/torch_envrionment$
总结
1、根据pytorch官网的环境选择生成的命令安装,比较靠谱;
2、如果只是学习,可以在虚拟环境中安装各种依赖,比如tensorflow,pytorch等,不需要可以删除。
本文详细介绍了如何在Ubuntu 20.04.2系统上,使用Python 3.10.6直接安装PyTorch的步骤,包括从PyTorch官网获取安装命令、验证安装成功、以及在虚拟环境中安装和检查PyTorch的过程。

1万+

被折叠的 条评论
为什么被折叠?



