Colab 上的 Python 3.7 - 如何从特定目录导入火炬?

问题描述 投票:0回答:1

我正在尝试让 python 和一些模块与我一直在关注的机器学习项目兼容。它们在 Colab 上运行,模块安装在 Googe Drive 上。

我在正确设置所有其他模块(torch_geometric 和 torch_sparse 等)方面没有遇到太多问题。但是我的手电筒有问题。

这是我到目前为止所得到的:

安装 Python 3.7 并检查它是否正常工作

!sudo apt-get update -y
!sudo apt-get install python3.7
!sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1
!sudo update-alternatives --config python3
!python --version

安装我的谷歌驱动器

import os, sys
from google.colab import drive
drive.mount('/content/gdrive')
nb_path = '/content/gdrive/My\ Drive/packages'
sys.path.insert(0, nb_path)  # or append(nb_path)

这是我在 Google 驱动器中保存模块的位置:torch、torch_geometric 等

sys.path.append('/content/gdrive/My Drive/packages')
sys.path

以下模块按预期导入 - 稀疏、聚类和分散也是如此

import pkg_resources
pkg_resources.find_distributions("/content/gdrive/My Drive/packages/torch_geometric==2.0.4")
import torch_geometric
torch_geometric. __version__

这输出“2.0.4”,验证它正确导入

接下来,仔细检查是否没有导入任何版本的 torch。这样我就可以排除这是问题的原因。这将返回“NameError: name 'torch' is not defined”——正如预期的那样。

torch. __version__

然后我希望选择以下两行,然后导入我想要的 torch 版本,它位于 '/content/gdrive/My Drive/packages' 中,具有与 torch_geometric、sparse 等相同的目录结构,它们都可以工作。相反,它返回错误消息,如下所示

pkg_resources.require("torch==1.11+cu115")
import torch

VersionConflict: (torch 1.13.1+cu116 (/usr/local/lib/python3.8/dist-packages), Requirement.parse('torch==1.11+cu115'))

我在某个地方犯了一个明显的错误吗?

python python-3.x google-colaboratory torch python-module
1个回答
0
投票

看起来错误是由系统上已安装的 torch 版本(版本 1.13.1+cu116)与您尝试从 Google Drive 安装的 torch 版本(版本 1.11)之间的版本冲突引起的+cu115).

当你运行pkg_resources.require("torch==1.11+cu115")时,它会尝试安装指定版本的torch,但它与已经安装的现有版本冲突。这就是您看到 VersionConflict 错误的原因。

要解决此问题,您可能需要考虑先卸载现有版本的 Torch,然后再从 Google Drive 安装所需的版本。

您可以使用以下命令执行此操作:

!pip uninstall torch -y

这将卸载当前版本的手电筒。然后你可以尝试从你的谷歌驱动器安装你需要的版本:

!pip install /content/gdrive/My\ Drive/packages/torch-1.11+cu115-cp37-cp37m-linux_x86_64.whl

确保将文件路径替换为 Google Drive 上 torch wheel 文件的实际路径。

或者,您可以尝试指定要在代码中使用的 torch 版本,而无需显式安装它。您可以通过在代码开头添加以下行来完成此操作,然后再导入任何依赖于 torch 的模块:

!pip install torch==1.11+cu115 -f https://download.pytorch.org/whl/cu115/torch_stable.html
import sys
sys.path.append('/content/gdrive/My Drive/packages')

这将安装正确版本的 torch,并将包含其他模块的目录添加到系统路径中。请注意,如果其他依赖项需要不同版本的 torch

,此方法可能无效

希望我的回答有帮助!! 祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.