M1 MacBook air 配置tensorflow

M1 mackbook air 配置tensorflow环境

由于m1没有avx指令集,所以用pip的传统方法无法安装tensorflow库,好在Apple在GitHub给出了解决方案点击进入GitHub下载tar.gz压缩文件

1、准备工作

建议python版本为3.8,用miniforge管理包文件,并解压下载的tar.gz文件

2、创建虚拟环境

conda create --name tf24a1
conda activate tf24a1

在这个环境中安装一些包

conda install -y pandas matplotlib scikit-learn jupyterlab

3、打开压缩文件中的arm64文件夹

进入arm64这个文件夹

(tf24a1) zhaoziqing@zhaoziqingdeMacBook-Air arm64 % ls
grpcio-1.33.2-cp38-cp38-macosx_11_0_arm64.whl
h5py-2.10.0-cp38-cp38-macosx_11_0_arm64.whl
h5py-2.10.0-cp38-cp38-macosx_11_0_arm64.whl.backup
numpy-1.18.5-cp38-cp38-macosx_11_0_arm64.whl
tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl
tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl
pip install --upgrade --no-dependencies --force tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl

可以看到文件夹里的文件,接下来强制安装这些whl文件

pip install --upgrade --no-dependencies --force grpcio-1.33.2-cp38-cp38-macosx_11_0_arm64.whl
pip install --upgrade --no-dependencies --force h5py-2.10.0-cp38-cp38-macosx_11_0_arm64.whl
pip install --upgrade --no-dependencies --force numpy-1.18.5-cp38-cp38-macosx_11_0_arm64.whl
pip install --upgrade --no-dependencies --force tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl

在安装一些必要的库

pip install absl-py astunparse flatbuffers gast google_pasta keras_preprocessing opt_einsum protobuf tensorflow_estimator termcolor typing_extensions wrapt wheel tensorboard typeguard

OK!到这就全部装完;

Successfully installed tensorflow-macos-0.1a3

检查一下版本

>>> import tensorflow
>>> tensorflow.__version__
'2.4.0-rc0'


在尝试运行一下网上扒下来简单的代码

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)

结果

>>> model.evaluate(x_test, y_test)
313/313 [==============================] - 0s 273us/step - loss: 0.0921 - accuracy: 0.9738
[0.09207689017057419, 0.973800003528595]
>>> print(end - start)
3.7963240146636963

成功

你可能感兴趣的:(python)