"zsh: illegal hardware instruction python" 在 macbook pro M1 上安装 Tensorflow 时

"zsh: illegal hardware instruction python" when installing Tensorflow on macbook pro M1

我正在尝试让 tensorflow 在我的 MacBook pro M1 上运行。但是,我在尝试导入时不断收到以下错误:zsh: illegal hardware instruction python

我已经通过这个link下载并安装了tensorflow。

这些是我的安装步骤:

我正在使用 Python 3.8.2.

我看过一些教程,其中这个确切的方法确实有效,所以我不知道这里的问题是什么。

Python3 在 M1 中附带 2 个架构。

$ file $(which python3)
# If you installed python through Homebrew or Anaconda, deactivate your conda env, then run this line instead:
# $ file $(which /usr/bin/python3)
/usr/bin/python3: Mach-O universal binary with 2 architectures: [x86_64:Mach-O 64-bit executable x86_64] [arm64e:Mach-O 64-bit executable arm64e]
/usr/bin/python3 (for architecture x86_64): Mach-O 64-bit executable x86_64
/usr/bin/python3 (for architecture arm64e): Mach-O 64-bit executable arm64e

在这里,指定使用哪一个非常重要。您可以通过安装这样的脚本来做到这一点:

arch -arm64 bash install_venv.sh my_tf_env

如果您有多个 python 安装,请使用:

arch -arm64 bash install_venv.sh --python=/usr/bin/python3 my_tf_env

您可以将 my_tf_env 替换为您选择的任何其他 name/path。

我遇到了同样的问题

这是因为M1芯片。现在有一个预发布版本,可以为 macOS 11.0+ 提供硬件加速的 TensorFlow 和 TensorFlow Addons。通过 Apple 的 ML Compute 框架,M1 Mac 和基于 Intel 的 Mac 支持本机硬件加速。

您需要安装支持M1芯片的TensorFlow 简单地拉这个 tensorflow macos repository 和 运行 ./scripts/download_and_install.sh

在尝试了一堆无济于事的解决方案后,这对我有用。

步骤 1 使用 pyenv 安装 python 版本 3.8.5 并将其设置为默认 python 版本。本教程(https://realpython.com/intro-to-pyenv/)对 正确配置 pyenv。

步骤 1.1 如果您遇到问题,请使用此 post(https://github.com/pyenv/pyenv/issues/1446) 运行在 zsh 中使用 pyenv。

步骤 1.2 一旦你有了 python 版本 3.8.5 运行ning,你可以通过 运行ning python -V 检查它应该输出:

Python 3.8.5

步骤 2 通过 pip install virtualenv

安装 virtualenv

步骤 2.1 通过 运行ning virtualenv ENV

创建虚拟环境

步骤 2.2 通过 运行ning source ENV/bin/activate

激活该虚拟环境

步骤 3 安装位于 public google 驱动器 link https://drive.google.com/drive/folders/1oSipZLnoeQB0Awz8U68KYeCPsULy_dQ7

的名为 tensorflow-2.4.1-py3-none-any.whl 的 tensorflow wheel

步骤 3.1 假设您只是简单地安装了下载轮运行 pip install ~/Downloads/tensorflow-2.4.1-py3-none-any.whl 在您激活的虚拟环境中

第 4 步键入 python,这将在您的终端中显示 >>>,然后键入

>>> import tensorflow
>>>

如果没有“zsh illegal hardware instruction”错误,你就可以开始了。

注意:如果你使用的是anaconda,上面的方法也可以。您可以跳过虚拟环境步骤(假设您有一个通过 Conda 激活的虚拟环境),直接进入上面提到的 pip install(第 3 步及之后的步骤)。