User Tools

Site Tools


Install tensorflow on MacBook Pro M1 and kerns for R

I have a 2021 MacBook Pro with Apple M1 Pro chip. I tried to install tensor flow on it following the instruction of Apple here as well as many other instructions online but failed to make it work.

Install tensorflow

After trial and error, this is what worked for me.

  1. Follow the instruction here to install miniconda.
  2. Install tensorflow using python -m pip install tensorflow-macos==2.9
  3. Install tensorflow-metal using python -m pip install tensorflow-metal==0.5.0

After this, you can test the installation using the example below. First, save the following code to a file such as

import tensorflow as tf
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

cifar = tf.keras.datasets.cifar100
(x_train, y_train), (x_test, y_test) = cifar.load_data()
model = tf.keras.applications.ResNet50(
    input_shape=(32, 32, 3),

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"]), y_train, epochs=5, batch_size=64)

Then, test it using python

Install keras for R

To use tensorflow in R, first install the packages tensorflow and keras within R using


Then, create or open the .Renviron file within your user directory, e.g., using nano ~/.Renviron. Add the following in the file (this will allow R to find your python and tensorflow installation.

RETICULATE_PYTHON = "~/miniconda/bin/python"

Now, you can test whether it works or not within R using the example below (from the book Introduction to Machine Learning).

## Data
library(ISLR2)  ## install the package if not yet
Gitters <- na.omit(Hitters) 
n <- nrow(Gitters)
ntest <- trunc(n / 3)
testid <- sample(1:n, ntest)
x <- scale(model.matrix(Salary ~ . - 1, data = Gitters)) 
y <- Gitters$Salary

## Now run a simple example

## this is used to build the model
## first layer is the hidden layer with 50 nodes
## output one layer with one node active the linear activiation function
modnn <- keras_model_sequential() %>%
    layer_dense(units = 50, activation = "relu", input_shape = ncol(x)) %>%
    layer_dropout(rate = 0.4) %>% 
    layer_dense(units = 1, activation = "linear")

## communicate with python

modnn %>% compile(loss = "mse", 
                  optimizer = optimizer_rmsprop(),
                  metrics = list("mean_absolute_error") )

## conduct the analysis <- modnn %>% fit(
    x[-testid, ], y[-testid], 
    epochs = 1000, batch_size = 32, 
    validation_data = list(x[testid, ], y[testid])
You could leave a comment if you were logged in.

Page Tools