事实胜于雄辩,苹果MacOs能不能玩儿机器/深度(ml/dl)学习(Python3.10/Tensorflow2)

事实胜于雄辩,苹果MacOs能不能玩儿机器/深度(ml/dl)学习(Python3.10/Tensorflow2)

    坊间有传MacOs系统不适合机器(ml)学习和深度(dl)学习,这是板上钉钉的刻板印象,就好像有人说女生不适合编程一样的离谱。现而今,无论是Pytorch框架的MPS模式,还是最新的Tensorflow2框架,都已经可以在M1/M2芯片的Mac系统中毫无桎梏地使用GPU显卡设备,本次我们来分享如何在苹果MacOS系统上安装和配置Tensorflow2框架(CPU/GPU)。

    Tensorflow2深度学习环境安装和配置

    首先并不需要任何虚拟环境,直接本地安装Python3.10即可,请参见:一网成擒全端涵盖,在不同架构(Intel x86/Apple m1 silicon)不同开发平台(Win10/Win11/Mac/Ubuntu)上安装配置Python3.10开发环境  ,这里不再赘述。

    随后安装Tensorflow本体:

pip3 install tensorflow-macos

    这里系统会自动选择当前Python版本的Tensorflow安装包:

➜  ~ pip install tensorflow-macos
Collecting tensorflow-macos
Downloading tensorflow_macos-2.12.0-cp310-cp310-macosx_12_0_arm64.whl (200.8 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 200.8/200.8 MB 4.7 MB/s eta 0:00:00

    安装包大小为200兆左右,如果下载不了,可以选择在pip官网直接下载基于python3.10的安装包:pypi.org/project/tensorflow-macos/#files


    然后直接将whl文件拖拽到终端安装即可。

    接着安装Tensorflow的GPU插件:tensorflow-metal,它是一个TensorFlow的后端,使用苹果的Metal图形API来加速神经网络计算。Metal是一种高性能图形和计算API,专门为苹果设备的GPU设计,可以实现更快的神经网络计算。使用tensorflow-metal可以显著提高在苹果设备上运行TensorFlow的性能,尤其是在使用Macs M1和M2等基于苹果芯片的设备时。

pip3 install --user tensorflow-metal

    注意这里安装命令必须带上--user参数,否则可能会报这个错误:

Non-OK-status: stream_executor::MultiPlatformManager::RegisterPlatform( std::move(cplatform)) status: INTERNAL: platform is already registered with name: "METAL"

    安装好之后,在Python终端运行命令:

import tensorflow
tensorflow.config.list_physical_devices()

    程序返回:

>>> import tensorflow
>>> tensorflow.config.list_physical_devices()
[PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'), PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

    可以看到,Tensorflow用于计算的物理设备既支持CPU,也支持GPU,也就是显卡。

    接着,在编写一个完整的测试脚本 test.py:

import sys
import tensorflow.keras
import pandas as pd
import sklearn as sk
import scipy as sp
import tensorflow as tf
import platform
print(f"Python Platform: {platform.platform()}")
print(f"Tensor Flow Version: {tf.__version__}")
print(f"Keras Version: {tensorflow.keras.__version__}")
print()
print(f"Python {sys.version}")
print(f"Pandas {pd.__version__}")
print(f"Scikit-Learn {sk.__version__}")
print(f"SciPy {sp.__version__}")
gpu = len(tf.config.list_physical_devices('GPU'))>0
print("GPU is", "available" if gpu else "NOT AVAILABLE")

    这里打印出深度学习场景下常用的库和版本号:

➜  chatgpt_async git:(main) ✗ /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/chatgpt_async/tensof_test.py"
Python Platform: macOS-13.3.1-arm64-arm-64bit
Tensor Flow Version: 2.12.0
Keras Version: 2.12.0

Python 3.10.9 (main, Dec 15 2022, 17:11:09) [Clang 14.0.0 (clang-1400.0.29.202)]
Pandas 1.5.2
Scikit-Learn 1.2.0
SciPy 1.10.0
GPU is available

    一望而知,在最新的macOS-13.3.1系统中,基于Python3.10.9玩儿Tensorflow2.1没有任何问题。

    至此,Tensorflow2就配置好了。

    Tensorflow框架GPU和CPU测试

    为什么一定要让Tensorflow支持GPU?GPU或图形处理单元与CPU类似,同样具有许多核心,允许它们同时进行更快的计算(并行性)。这个特性非常适合执行大规模的数学计算,如计算图像矩阵、计算特征值、行列式等等。

    简而言之,GPU可以以并行方式运行代码并获得简明的结果,同时由于能够处理高强度的计算,因此可以比CPU更快的获得计算结果。

    这里我们通过CIFAR-10项目进行测试,TensorFlow CIFAR-10项目是一个经典的计算机视觉项目,旨在训练一个模型,能够对CIFAR-10数据集中的图像进行分类。CIFAR-10数据集包含60,000张32x32像素的彩色图像,分为10个类别,每个类别包含6,000张图像。该项目的目标是训练一个深度神经网络模型,能够对这些图像进行准确的分类:

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
(X_train, y_train), (X_test, y_test) = keras.datasets.cifar10.load_data()

X_train_scaled = X_train/255
X_test_scaled = X_test/255
# one hot encoding labels
y_train_encoded = keras.utils.to_categorical(y_train, num_classes = 10, dtype = 'float32')
y_test_encoded = keras.utils.to_categorical(y_test, num_classes = 10, dtype = 'float32')

def get_model():
model = keras.Sequential([
keras.layers.Flatten(input_shape=(32,32,3)),
keras.layers.Dense(3000, activation='relu'),
keras.layers.Dense(1000, activation='relu'),
keras.layers.Dense(10, activation='sigmoid')
])
model.compile(optimizer='SGD',
loss='categorical_crossentropy',
metrics=['accuracy'])
return model

    首先测试CPU性能:

%%timeit -n1 -r1
# CPU
with tf.device('/CPU:0'):
model_cpu = get_model()
model_cpu.fit(X_train_scaled, y_train_encoded, epochs = 10)

    这段代码使用了%%timeit -n1 -r1魔术命令来测试在CPU上训练模型的时间。-n1表示只运行一次,-r1表示只运行一轮。如果没有指定这些参数,则会运行多次并计算平均值。/CPU:0指的是第一个CPU(如果计算机只有一个CPU,则是唯一的CPU)。

    这里使用get_model()函数获取模型,使用model_cpu.fit()方法在CPU上训练模型,使用X_train_scaled和y_train_encoded作为输入数据,并在10个epoch内进行训练。最后,使用%%timeit命令来测试训练模型所需的时间,以便比较不同设备的性能。

    程序返回:

50000/50000 [==========================] - 80s 2ms/sample

14min 9s

    需要14分钟。

    接着测试GPU性能:

%%timeit -n1 -r1
# GPU
with tf.device('/GPU:0'):
model_gpu = get_model()
model_gpu.fit(X_train_scaled, y_train_encoded, epochs = 10)

    程序返回:

50000/50000 [==========================] - 11s 227us/sample

1min 55s

    一分多钟,很明显在GPU上训练模型比在CPU上训练模型更快,因为GPU可以同时处理多个任务。

    结语

    苹果MacOs系统可以承担深度学习任务,但术业有专攻,算力层面还是比不上配置N卡的其他平台,这是不争的事实。没错,更好的选择是RTX3090,甚至是4090,但一块RTX4090显卡的价格是1500刀左右,这还意味着CPU、内存、主板和电源都得单买,而一台m2芯片的Mac book air的价格是多少呢?