User Tools

Site Tools


blog:install_tensorflow_on_macbook_pro_m1_and_kerns_for_r

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 https://developer.apple.com/metal/tensorflow-plugin/ 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 https://developer.apple.com/metal/tensorflow-plugin/ 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 test.py.

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(
    include_top=True,
    weights=None,
    input_shape=(32, 32, 3),
    classes=100,)

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

Then, test it using python test.py.

Install keras for R

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

install.packages('tensorflow')
install.packages('keras')

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)
set.seed(13)
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
library(keras)

## 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")

summary(modnn)
## communicate with python

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


## conduct the analysis
nn.fit.1layer <- 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.
blog/install_tensorflow_on_macbook_pro_m1_and_kerns_for_r.txt · Last modified: 2024/09/17 16:03 by 127.0.0.1