关于macos:事实胜于雄辩苹果MacOs能不能玩儿机器深度mldl学习Python310Tensorflow2

3次阅读

共计 4343 个字符,预计需要花费 11 分钟才能阅读完成。

坊间有传 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 张 32×32 像素的彩色图像,分为 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 的价格是多少呢?

正文完
 0