由于架构和各种各样的错误,花了我五六个小时,终于在M1上安装好了Tensorflow!!!
一、python
首先电脑上需要一个python,版本需要在3.8以上。在终端中输入python可以查看版本
由于苹果不支持x86架构的anaconda,我们需要下载ARM版的miniforge3,用法和anaconda是一样的。在此处下载ARM版的Miniforge3
下载完成后,使用终端进入下载目录,运行命令:
[En]
After the download is completed, use the terminal to enter the download directory and run the command:
bash Miniforge3-MacOSX-arm64.sh
这样miniforge3就安装好了。可以在zshrc中查看环境变量,输入一下命令:
vim ~/.zshrc
您可以在配置文件中看到一个段落
[En]
You can see a paragraph in the configuration file
输入冒号”:”,再输入q!退出。
三、在虚拟环境中安装ML Compute版的TensorFlow
我们需要在下载一个environment.yml文件。
下载完成后我们需要记住这个yml文件的路径,然后在终端中输入以下命令创建虚拟环境,我暂且将虚拟环境命名为tf:
conda env create --file=PATH_TO_ENVIRONMENT.YML --name=tf
用你的yml文件的路径替换里面的大写字母。小tips:直接将文件拖入终端即可显示文件路径。
然后激活我们刚刚在终端中创建的虚拟环境:
[En]
Then activate the virtual environment we just created in the terminal:
conda activate tf
然后开始安装依赖项并输入:
[En]
Then start installing the dependencies and enter:
pip install --upgrade --force --no-dependencies https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl
然后就开始安装了。
未报告错误,表示安装成功!
[En]
Did not report an error, indicating that the installation was successful!
四、测试Tensorflow代码
用VS Code测试,进入项目目录,编辑如下代码:
import tensorflow as tf
import time
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
start = time.time()
model.fit(x_train, y_train, epochs=5)
end = time.time()
model.evaluate(x_test, y_test)
print(end - start)
记得在让python解释器在tf环境中
然后运行
五、一些问题
我在安装过程中使用过别的方法,曾遇到两个问题,一个是xxx .whl is not a supported wheel on this platform.还有一个是用别的方法安装好了tensorflow后提示 zsh:illeagal instruction
如果你也遇到了和我一样的问题,我个人理解是miniforge3的原因,我之前是用brew安装的miniforge3,后来我用brew把它卸载了,用的是github上面的安装包安装的miniforge3之后,再进行下面步骤,就安装上了。我在谷歌上看了很久,也有很多人遇到这样得到问题,不知道他们是不是因为这个原因。
Original: https://blog.csdn.net/hsywatchingu/article/details/118055508
Author: hsywatchingu
Title: 在M1的Mac上安装Tensorflow(避坑版)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/513972/
转载文章受原作者版权保护。转载请注明原作者出处!