Installation of TensorFlow 2.4 on M1 MacBook
A simple step-by-step guide to install TensorFlow 2.4 on your MacBook M1!
The ecosystem of machine learning has a plethora of open-source libraries and core frameworks. And amongst all of them, popular libraries such as TensorFlow and Keras are widely used in deep learning.
While TensorFlow extensively supports Nvidia GPU drivers with CUDA-enabled cards, its setup proved to be a tad bit overwhelming for MacBook. Later, Apple’s new release of ARM based silicon chips has resolved this issue and made the configuration more robust and effortless.
So, here is a simple step-by-step guide to install TensorFlow 2.4 on your MacBook!
Pre-requisite: Please ensure you have the latest version of the following:
- macOS Big Sur 11.0
- python 3.8
- Xcode command line tool
Step 1: Open the terminal and verify the version of python
python3 --version
Step 2: Create a new virtual environment with python 3.8
python3 -m venv <name_of_the _new_virtual_environment>
Step 3: Activate the environment
source <name_of_the _new_virtual_environment>/bin/activate
Step 4: Run the TensorFlow installation script (taken from apple/tensorflow_macos GitHub )
/bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/apple/tensorflow_macos/master/scripts/download_and_install.sh)"
Step 5: Specify the path used while creating the environment in Step 2
/Users/<username>/<name_of_the _new_virtual_environment>
Step 6: Installation of TensorFlow in virtual environment is complete. Verify it.
source <name_of_the _new_virtual_environment>/bin/activate
python3 -c ‘imprt tensorflow as tf; print(tf.__version__)’
Step 7: Train a sample CNN model and test your architecture (taken from Benchmark: CNN proposal #25)
a) Install TensorFlow datasets
pip install tensorflow_datasets
b) Create a file with the following code:
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfdstf.enable_v2_behavior()from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()from tensorflow.python.compiler.mlcompute import mlcomputemlcompute.set_mlc_device(device_name=’gpu’)(ds_train, ds_test), ds_info = tfds.load(
‘mnist’,
split=[‘train’, ‘test’],
shuffle_files=True,
as_supervised=True,
with_info=True,
)def normalize_img(image, label):
“””Normalizes images: `uint8` -> `float32`.”””
return tf.cast(image, tf.float32) / 255., labelbatch_size = 128ds_train = ds_train.map(
normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE)
ds_train = ds_train.cache()
ds_train = ds_train.shuffle(ds_info.splits[‘train’].num_examples)
ds_train = ds_train.batch(batch_size)
ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)ds_test = ds_test.map(
normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_test = ds_test.batch(batch_size)
ds_test = ds_test.cache()
ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE)model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, kernel_size=(3, 3),activation=’relu’),
tf.keras.layers.Conv2D(64, kernel_size=(3, 3),activation=’relu’),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
# tf.keras.layers.Dropout(0.25),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=’relu’),
# tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation=’softmax’)
])model.compile(
loss=’sparse_categorical_crossentropy’,
optimizer=tf.keras.optimizers.Adam(0.001),
metrics=[‘accuracy’],
)model.fit(
ds_train,
epochs=12,
validation_data=ds_test,
)
c) Run the file
python test.py
Step 8: Verify the results.
- 12s/epoch
- 24ms/step
- 98.7% final accuracy
Voila! TensorFlow is configured on your Mac and you’re one step closer to the universe of Deep Learning. Happy learning :)
Please reach out to me on LinkedIn if you want to collaborate on a project or discuss new opportunities.
References used:
1. Photo by Aditya Joshi on Unsplash
2. Logo from https://www.tensorflow.org/
3. Logo from https://www.python.org/
4. TensorFlow installation script from https://github.com/apple/tensorflow_macos
5. TensorFlow test code from https://github.com/apple/tensorflow_macos/issues/25
6. Inspired by Data Driven Investor