R Academy · Lesson

Setting Up Keras and TensorFlow in R

Install the keras R package, configure a Python backend, and verify setup.

Lesson 1 of 413 steps

Setting Up Keras and TensorFlow in R is a free R Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.

Deep Learning in R with Keras

The keras R package provides a high-level interface to TensorFlow. It is maintained by Posit (formerly RStudio) and mirrors the Python Keras API closely. R keras uses reticulate to call Python TensorFlow under the hood, so you get the full power of TensorFlow with R syntax.

# Install the R package from CRAN
# install.packages('keras')

# Then install TensorFlow Python environment
library(keras)
install_keras()  # creates a Python venv with TF installed

# For GPU-enabled TensorFlow:
# install_keras(tensorflow = 'gpu')

install_keras() and Backends

install_keras() creates a dedicated Python environment (Miniconda or virtualenv) and installs TensorFlow and its dependencies. You can specify the TensorFlow version, the Python version, and whether to install CPU or GPU support. By default it installs the latest stable CPU version.

library(keras)

# Install specific TF version in a custom env
install_keras(
  method      = 'conda',
  envname     = 'r-keras-tf2',
  tensorflow  = '2.15',
  version     = 'default'
)

# Check which Python environment is active
reticulate::py_config()

library(keras) and is_keras_available()

library(keras) loads the R bindings. After loading, check whether the Keras/TF Python backend is actually reachable with is_keras_available(). This returns TRUE if TensorFlow is installed and importable, or FALSE with a helpful message if the Python environment is missing.

library(keras)

# Check backend availability
if (is_keras_available()) {
  cat('Keras is ready!\n')
} else {
  cat('Keras not available. Run install_keras() first.\n')
}

# Check TensorFlow Python availability
library(tensorflow)
tf$constant('Hello TensorFlow')

tensorflow Package

The tensorflow R package provides direct access to the TensorFlow Python API through reticulate. install_tensorflow() mirrors install_keras() but installs just TensorFlow without the Keras extras. Use it when you need low-level TF operations.

library(tensorflow)

# Install TF separately if needed
# tensorflow::install_tensorflow()

# Check TF version
tf_version()

# Low-level tensor operation
a <- tf$constant(c(1.0, 2.0, 3.0))
b <- tf$constant(c(4.0, 5.0, 6.0))
c_val <- tf$add(a, b)
print(c_val)

k_backend() — Identify the Backend

k_backend() returns a string identifying which backend Keras is using. Modern Keras R (keras3) always uses TensorFlow. In older keras (v2), it could also use Theano or CNTK. Knowing the backend is useful when debugging environment issues.

library(keras)

# Check which backend is active
k_backend()  # should return 'tensorflow'

# Check TF version via keras
tf_version()

# Number of tensor dimensions backend uses internally
k_image_data_format()  # 'channels_last' or 'channels_first'

Checking GPU Availability

Training on a GPU can be 10-50x faster than CPU for large networks. Check GPU availability and list detected devices using TensorFlow's device API. If you have NVIDIA GPU and CUDA installed, TensorFlow will use it automatically.

library(tensorflow)

# List all available devices
devices <- tf$config$list_physical_devices()
print(devices)

# Check specifically for GPUs
gpus <- tf$config$list_physical_devices('GPU')
if (length(gpus) > 0) {
  cat('GPU available:', gpus[[1]]$name, '\n')
} else {
  cat('No GPU found — using CPU\n')
}

Managing the Python Environment

Under the hood, R keras uses the reticulate package to call Python. Use reticulate::use_condaenv() or reticulate::use_virtualenv() to select the Python environment that has TensorFlow installed. This must be called before loading keras.

# Select the conda environment before loading keras
library(reticulate)
use_condaenv('r-keras-tf2', required = TRUE)

library(keras)

# Confirm Python path
py_config()$python

# Confirm TF is importable
pytf <- import('tensorflow', convert = FALSE)
cat('TF Version:', pytf$__version__)

keras3 vs keras2 API Differences

The keras R package went through a major rewrite with version 3 (keras3), released in 2024. The new API uses keras_model_sequential() instead of keras_model_sequential() |>, and the pipe-based layer addition style. Older code uses %>%; modern code uses the native R pipe |>.

library(keras3)  # or library(keras) for keras2

# Modern keras3 API with native pipe
model <- keras_model_sequential(input_shape = c(784)) |>
  layer_dense(units = 128, activation = 'relu') |>
  layer_dense(units = 10, activation = 'softmax')

summary(model)

Verifying a Full Setup

Before building any model, run a quick end-to-end verification: create a tiny model, compile it, and train it on synthetic data. If this runs without errors, your Keras + TF setup is working correctly.

library(keras)

# Quick smoke test
model <- keras_model_sequential(input_shape = c(10)) |>
  layer_dense(units = 32, activation = 'relu') |>
  layer_dense(units = 1,  activation = 'linear')

model |> compile(
  optimizer = 'adam',
  loss      = 'mse'
)

# Train on random data
x_rand <- matrix(rnorm(1000 * 10), ncol = 10)
y_rand <- rnorm(1000)

model |> fit(x_rand, y_rand, epochs = 3, batch_size = 32, verbose = 0)
cat('Setup OK!')

Session and Memory Management

TensorFlow uses GPU and RAM aggressively. In interactive R sessions, call keras::backend()$clear_session() to release memory when switching experiments. For reproducibility, set TF and R random seeds before building models.

library(keras)

# Set seeds for reproducibility
set.seed(42)
tensorflow::set_random_seed(42)

# Clear any previous session state
keras::backend()$clear_session()

# Limit GPU memory growth (prevents OOM errors)
gpus <- tensorflow::tf$config$list_physical_devices('GPU')
if (length(gpus) > 0) {
  tensorflow::tf$config$experimental$set_memory_growth(
    gpus[[1]], TRUE
  )
}

Workflow Overview

A typical deep learning workflow in R follows these steps:

  1. Install: install_keras() once per machine
  2. Load: library(keras)
  3. Prepare data: normalise features, convert to matrices
  4. Build model: keras_model_sequential() + layers
  5. Compile: specify loss, optimizer, metrics
  6. Fit: fit(model, x, y, epochs, callbacks)
  7. Evaluate/Predict: evaluate() + predict()
# Step-by-step outline (each step covered in next lessons)
library(keras)

# 1. Data ready as matrices (normalised)
# x_train, y_train, x_test, y_test

# 2. Model
model <- keras_model_sequential(input_shape = ncol(x_train)) |>
  layer_dense(128, activation = 'relu') |>
  layer_dense(1,   activation = 'sigmoid')

# 3. Compile
model |> compile('adam', 'binary_crossentropy', metrics = 'accuracy')

# 4. Fit
model |> fit(x_train, y_train, epochs = 20)

# 5. Evaluate
model |> evaluate(x_test, y_test)

Quick Check

What does calling install_keras() in R do?

Keras Setup Recap

Key takeaways from Setting Up Keras and TensorFlow in R:

  • install_keras() creates a Python env and installs TensorFlow — run once per machine.
  • is_keras_available() checks if the backend is reachable before training.
  • k_backend() identifies the backend (always TensorFlow in modern keras).
  • GPU availability is checked via tf$config$list_physical_devices('GPU').
  • Use reticulate::use_condaenv() to select the right Python environment.
  • Set seeds with set.seed() and tensorflow::set_random_seed() for reproducibility.
  • Call backend()$clear_session() between experiments to free memory.
# Minimal verified setup check
library(keras)

if (!is_keras_available()) {
  install_keras()
}

cat('Backend:', k_backend(), '\n')
cat('TF Version:', tf_version(), '\n')
cat('Image format:', k_image_data_format(), '\n')
Free to start

Learn R with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
43
Lessons
159

Frequently Asked Questions

Is the “Setting Up Keras and TensorFlow in R” lesson free?

Yes — any 3 lessons of the R Academy learning path, including “Setting Up Keras and TensorFlow in R”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.

What will I learn in “Setting Up Keras and TensorFlow in R”?

Install the keras R package, configure a Python backend, and verify setup. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Setting Up Keras and TensorFlow in R” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Setting Up Keras and TensorFlow in R
  2. Building Sequential Models
  3. Convolutional Neural Networks Basics
  4. Training, Validation, and Preventing Overfitting
← Back to R Academy