欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > PyTorch环境配置常见报错的解决办法

PyTorch环境配置常见报错的解决办法

2025/2/5 11:55:16 来源:https://blog.csdn.net/lpx666168/article/details/145099500  浏览:    关键词:PyTorch环境配置常见报错的解决办法

目标

小白在最基础的环境配置里一般都会出现许多问题。
这里把一些常见的问题分享出来。希望可以节省大家一些时间。

最终目标是可以在cmd虚拟环境里进入jupyter notebook,new的时候有对应的环境,并且可以跑通所有的import code。

第一步: 在anaconda中创建一个专门的虚拟环境

conda create -n py37_torch131 python=3.7

第二步:激活环境

# 激活环境
source activate py37_torch131## 如果source报错,改用conda 
conda activate py37_torch131# 退出环境的指令
deactivate

以上两步一般都不会出现什么问题。

第三步:在虚拟环境下安装pytorch1.3.1及各种依赖库

原始安装代码:

# 安装pytorch1.3.1
conda install pytorch=1.3.1 torchvision cudatoolkit=10.0# 安装其他依赖库
pip install jupyter tqdm opencv-python matplotlib pandas

这一步可能会遇到非常多的安装的问题。

安装的时候可能会遇到:
① channel找不到的,报错为 The following packages are not available from current channels;
②也可能文件比较大,或者下载速度非常慢。

此外,conda的安装目前不支持断点续传,一旦卡住了或者超时,就需要重头再来。

这里提供一种针对各种安装问题的通用解决方案: 尽量都通过清华源的镜像下载安装。相比速度很快。

# 先添加清华的channelsconda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/conda config --set show_channel_urls yes# 安装pytorch
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
# conda install pytorch torchvision cudatoolkit=10.0 # 不指定版本的话,默认下载最新的,这样的话再baseline里可能会遇到需要将target类型转为long的报错提示conda install pytorch=1.3.1 torchvision cudatoolkit=10.0# 安装其他依赖包
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jupyter tqdm opencv-python matplotlib pandas

如果要安装其他包,可以先网上搜索下清华镜像是否有,一般都会有的。然后尽量通过清华镜像资源下载。

第四步:启动notebook

jupyter-notebook
jupyter notebook
# 以上两种方式都可以启动notebook

本来要开始愉快的代码之旅了,结果发现在notebook里new的时候,并没有我们刚刚创建的那个虚拟环境。

原因是缺少nb_conda插件,以及没有导入虚拟环境。

# 安装nb_conda插件
conda install nb_conda
conda install ipykernel# 导入虚拟环境
python -m ipykernel install --user --name py37_torch131 --display-name "py37_cv"# 最后启动jupyter notebook
jupyter notebook

总结

要敲的指令按顺序如下:

conda create -n py37_torch131 python=3.7 
conda activate py37_torch131conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yesconda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
conda install pytorch=1.3.1 torchvision cudatoolkit=10.0pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jupyter tqdm opencv-python matplotlib pandasconda install nb_conda
conda install ipykernelpython -m ipykernel install --user --name py37_torch131 --display-name "py37_cv"
jupyter notebook

在notebook里new file的时候记得选择 py37_cv那个环境。

最终效果如下:

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com