Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 40 ยท Getting Started

Installing and Your First Model

Install TensorFlow 2 and Keras 3 with pip, check versions and GPU, then read a complete first model and rebuild its forward pass and parameter count in NumPy.

Before you train anything you need a working installation. This lesson walks through the options (your own machine, a virtual environment, Google Colab), shows how to check that everything works, and then builds a first complete model. Because TensorFlow does not run in the browser runner, the model code is read-only; the runnable examples reproduce its parameter counts and forward pass in NumPy so you can verify every number yourself.

Choose where to run

Option Good for Notes
Google Colab Beginners, free GPU Nothing to install; TensorFlow and Keras 3 are preinstalled
Local virtual environment Daily work Full control, works offline
Docker image Reproducible setups Official tensorflow/tensorflow images exist
Cloud notebooks Larger jobs Vertex AI, SageMaker, Kaggle

For a local setup you need a supported 64-bit Python (3.9 or newer; check the TensorFlow install page for the newest supported version, because it lags the newest Python release slightly).

Local install with a virtual environment

Always use a virtual environment so TensorFlow's many dependencies do not collide with other projects.

Terminal
python -m venv .venv

# macOS / Linux
source .venv/bin/activate
# Windows (PowerShell)
.venv\Scripts\Activate.ps1

pip install --upgrade pip
pip install tensorflow

That single pip install tensorflow brings in Keras 3, NumPy and everything else needed for CPU training. For NVIDIA GPU support on Linux, the documented route is pip install "tensorflow[and-cuda]", which installs matching CUDA libraries. On native Windows, recent TensorFlow versions run on CPU only; use WSL2 for a GPU.

Not sure whether you need a GPU? You do not, for this course. Every model in the early chapters trains in seconds to minutes on a laptop CPU. A GPU matters for large image and text models.

Check the installation

Python
import tensorflow as tf
import keras
import numpy as np

print("TensorFlow:", tf.__version__)
print("Keras     :", keras.__version__)
print("NumPy     :", np.__version__)
print("GPUs      :", tf.config.list_physical_devices("GPU"))

x = tf.constant([[1.0, 2.0], [3.0, 4.0]])
print(tf.matmul(x, x))

The exact version numbers depend on your machine. If keras.__version__ starts with 3, you are on Keras 3. An empty GPU list simply means you are training on the CPU. The matrix product prints [[ 7. 10.] [15. 22.]] as a tensor.

If you see messages about oneDNN custom operations or cuda drivers not found when importing TensorFlow, they are informational logs, not errors. Silence them with the environment variable TF_CPP_MIN_LOG_LEVEL=2 set before importing.

Reproducibility in one line

Weights start random, so two runs differ. Fix the seeds when you want repeatable experiments:

Python
import keras
keras.utils.set_random_seed(42)   # seeds Python, NumPy and the backend

Exact repeatability across different hardware is not guaranteed, but this removes most run-to-run noise.

Your first model

Here is a complete model for a made-up task: 20 numeric features in, one probability out. Data is random, which is fine for checking that the pipeline runs.

Python
import numpy as np
import keras
from keras import layers

keras.utils.set_random_seed(42)

# 1. data (random stand-in data)
x = np.random.rand(1000, 20).astype("float32")
y = (x.sum(axis=1) > 10).astype("float32")      # a rule the model can learn

# 2. model
model = keras.Sequential([
    keras.Input(shape=(20,)),
    layers.Dense(32, activation="relu"),
    layers.Dense(1, activation="sigmoid"),
])

# 3. compile
model.compile(optimizer="adam",
              loss="binary_crossentropy",
              metrics=["accuracy"])

# 4. train
history = model.fit(x, y, epochs=5, batch_size=32, validation_split=0.2)

# 5. use
print(model.predict(x[:3]))
model.summary()

model.summary() prints a table of layers with output shapes and parameter counts. The layer names carry a counter, but the numbers are fixed by the architecture:

TEXT
dense   (Dense)   (None, 32)   672
dense_1 (Dense)   (None, 1)     33
Total params: 705

None is the batch size: the model accepts any number of examples at once.

Where do 672 and 33 come from?

A Dense(units) layer fed with n inputs has an n x units weight matrix plus units biases. So the first layer has 20 * 32 + 32 = 672 and the second 32 * 1 + 1 = 33. Let us rebuild the same network in NumPy and confirm.

Python Stand-in: the first model's parameters and forward pass (NumPy)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An untrained network outputs probabilities near 0.5, because the weights know nothing yet. Training changes w1, b1, w2, b2 so the outputs match the labels.

Reading the compile line

compile answers three questions, which are the subject of Chapter 4:

  • optimizer: how to update the weights ("adam" is a strong default).
  • loss: what number to minimize (binary_crossentropy for yes/no labels).
  • metrics: what to report for humans (accuracy). Metrics do not affect training.

A stand-in for "fit"

fit loops over the data for several epochs (full passes). In each epoch it splits the data into batches and updates the weights after each batch. Here is that skeleton with counting only, so you see the bookkeeping:

Python Stand-in: epochs and batches (NumPy)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

That matches the "25/25" progress counter Keras prints for 800 training examples with batch size 32.

flowchart TB
    A["Data x, y"] --> B["Split into batches"]
    B --> C["Forward pass: predictions"]
    C --> D["Loss: how wrong?"]
    D --> E["Backward pass: gradients"]
    E --> F["Optimizer updates weights"]
    F --> B

One pass around this loop is a training step; a full pass over the data is an epoch.

Common installation problems

  • ModuleNotFoundError: No module named 'tensorflow': the environment where you run Python is not the one where you installed. Activate the virtual environment first.
  • Version conflicts with NumPy: install into a fresh virtual environment and let pip choose compatible versions.
  • Very old Python: TensorFlow wheels exist only for supported Python versions; check with python --version.
  • Mixing keras and tf.keras: with TensorFlow 2.16+, tf.keras is Keras 3. Pick one import style and keep it; this course uses import keras.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many parameters does Dense(32) have when its input has 20 features?

    20 x 32 weights plus 32 biases equals 672.
  2. 2. What does None mean in the output shape (None, 32)?

    The first dimension is the batch size, which can vary between calls.
  3. 3. Which compile argument does NOT change how the weights are trained?

    Metrics only report numbers for humans. The optimizer and loss drive the updates.
  4. 4. Why use a virtual environment?

    A virtual environment keeps this project's packages separate from the rest of your system.

Summary

  • Use Colab for zero setup, or pip install tensorflow in a virtual environment locally.
  • Check tf.__version__, keras.__version__ and tf.config.list_physical_devices("GPU").
  • A first model: Sequential, compile, fit, predict, summary.
  • Dense parameters = inputs x units + units; the stand-in confirms 672 + 33 = 705.
  • One epoch = many batch steps, each doing forward pass, loss, gradients and an update.

Next: How Neural Networks Learn