坊间有传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的价格是多少呢?