Introduction to Keras
Keras is a high-level deep learning API that makes it much easier to create, train, evaluate, and use neural networks with Python. With TensorFlow, Keras provides a simple way to build neural networks without manually implementing every mathematical operation.
What Is Keras?
Keras is a high-level API for building machine learning and deep learning models.
In simple words, Keras gives us easy Python commands for creating neural networks.
Without a high-level API
You manually handle:
↓
Weights
Biases
Matrix calculations
Gradients
Backpropagation
Weight updates
Training
With Keras
Define Model
↓
Add Layers
↓
Compile
↓
Train
↓
Predict
Keras does not remove the concepts we learned earlier. It provides convenient tools that implement those concepts for us.
Keras and TensorFlow
You may see code such as:
import tensorflow as tf
and then:
tf.keras
Here, Keras provides the high-level API, while TensorFlow provides the underlying machine learning framework and computation engine.
Python
↓
Keras API
↓
TensorFlow
↓
Mathematical Computation
↓
Neural Network
This combination lets us write relatively simple Python code while TensorFlow handles the underlying numerical computations.
Why Do We Use Keras?
Building a neural network directly from low-level mathematical operations can require a lot of code.
Keras gives us simple building blocks.
Layers
↓
Model
↓
Loss Function
↓
Optimizer
↓
Training
↓
Prediction
Instead of manually writing all the mathematics, we can describe what the neural network should look like.
Your First Keras Model
Let's create a very simple neural network.
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(4, activation="relu"),
tf.keras.layers.Dense(1, activation="sigmoid")
])
This code creates a neural network with two layers.
Input
↓
Dense Layer
4 neurons
ReLU
↓
Dense Layer
1 neuron
Sigmoid
↓
Output
We don't have to manually calculate the weights, biases, matrix multiplication, or activation functions. Keras creates and manages these components for us.
What Is Sequential?
The Sequential model is one of the simplest ways to create a neural network in Keras.
model = tf.keras.Sequential([
layer1,
layer2,
layer3
])
Sequential means that the data flows through the layers in order.
Input
↓
Layer 1
↓
Layer 2
↓
Layer 3
↓
Output
This is perfect for many basic neural networks where each layer connects directly to the next layer.
What Is a Layer?
A neural network is made up of layers.
A layer contains neurons and their trainable parameters.
Neural Network
↓
Layers
↓
Neurons
↓
Weights + Bias
↓
Calculation
↓
Activation
In Keras, we can create a dense layer using:
tf.keras.layers.Dense(4)
The 4 means that the layer contains 4 neurons.
Understanding a Dense Layer
Consider:
tf.keras.layers.Dense(
8,
activation="relu"
)
This means:
8
↓
Number of neurons
activation="relu"
↓
Use ReLU activation function
Keras handles the weights and biases associated with the layer.
Input Shape
A neural network needs to know the shape of its input data.
Suppose every training example has two features:
Feature 1
Feature 2
The input shape is:
input_shape=(2,)
For example:
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(2,)),
tf.keras.layers.Dense(
4,
activation="relu"
),
tf.keras.layers.Dense(
1,
activation="sigmoid"
)
])
The input contains two numerical values.
[feature_1, feature_2]
Keras Makes Training Easier
After creating the model, we can configure its training process with compile().
model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy"]
)
This tells Keras:
optimizer="adam"
→ How weights should be updated
loss="binary_crossentropy"
→ How prediction error should be measured
metrics=["accuracy"]
→ What additional result we want to monitor
We already learned these concepts in the previous lessons. Keras simply gives us a convenient way to configure them.
Training With Keras
Once the model is compiled, we can train it using fit().
model.fit(
X_train,
y_train,
epochs=10
)
Keras handles the training process:
Input Data
↓
Forward Propagation
↓
Prediction
↓
Loss
↓
Backpropagation
↓
Gradients
↓
Optimizer
↓
Update Weights
↓
Repeat
You don't need to manually write all those steps for a standard Keras training workflow.
Making Predictions
After training, we can use the model to make predictions.
prediction = model.predict(
[[1.0, 0.0]]
)
print(prediction)
The model receives the input:
[1.0, 0.0]
and produces a prediction.
Input
[1.0, 0.0]
↓
Neural Network
↓
Prediction
0.87
The meaning of 0.87 depends on the problem and how the output layer was designed.
Complete Keras Example
Now let's put the main pieces together.
import tensorflow as tf
# Training data
X_train = [
[0.0, 0.0],
[0.0, 1.0],
[1.0, 0.0],
[1.0, 1.0]
]
y_train = [
0.0,
1.0,
1.0,
1.0
]
# Create model
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(2,)),
tf.keras.layers.Dense(
4,
activation="relu"
),
tf.keras.layers.Dense(
1,
activation="sigmoid"
)
])
# Configure model
model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy"]
)
# Train model
model.fit(
X_train,
y_train,
epochs=100,
verbose=0
)
# Make prediction
prediction = model.predict(
[[1.0, 1.0]],
verbose=0
)
print(prediction)
This is the basic Keras workflow:
1. Import TensorFlow
↓
2. Prepare Data
↓
3. Create Model
↓
4. Add Layers
↓
5. Compile Model
↓
6. Train Model
↓
7. Make Predictions
What Keras Is Doing Behind the Scenes
The short code:
model.fit(
X_train,
y_train,
epochs=10
)
represents a much larger process.
For each batch:
1. Take input
2. Calculate neuron outputs
3. Perform forward propagation
4. Calculate loss
5. Calculate gradients
6. Optimizer updates weights
7. Repeat
Keras doesn't eliminate these operations. It automates the implementation of them for you.
Two Simple Examples
Example 1 — Small Network
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(2,)),
tf.keras.layers.Dense(4, activation="relu"),
tf.keras.layers.Dense(1, activation="sigmoid")
])
This is useful for understanding the basic structure of a neural network.
Example 2 — Larger Hidden Layer
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(2,)),
tf.keras.layers.Dense(16, activation="relu"),
tf.keras.layers.Dense(8, activation="relu"),
tf.keras.layers.Dense(1, activation="sigmoid")
])
Here there are two hidden layers:
Input
↓
16 neurons
↓
8 neurons
↓
1 output neuron
The important point is that Keras lets us describe the network structure very clearly.
Keras Does Not Replace Understanding
This is important.
If you only memorize:
model.fit(...)
model.compile(...)
model.predict(...)
you can write code, but you won't understand why the model works or why it fails.
You should understand what happens underneath:
model.fit()
↓
Forward Propagation
↓
Loss
↓
Backpropagation
↓
Gradients
↓
Optimizer
↓
Weight Updates
Keras is the convenient interface. The underlying neural network concepts are still the same concepts you learned in the previous lessons.
Understand the Python Code
import tensorflow as tf
Imports TensorFlow.
model = tf.keras.Sequential([...])
Creates a neural network where the layers are arranged sequentially.
tf.keras.layers.Input(shape=(2,))
Defines an input containing two features.
tf.keras.layers.Dense(
4,
activation="relu"
)
Creates a dense layer containing four neurons using ReLU.
tf.keras.layers.Dense(
1,
activation="sigmoid"
)
Creates the output layer with one neuron using sigmoid.
model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy"]
)
Configures how the model will be trained.
model.fit(
X_train,
y_train,
epochs=100
)
Trains the model using the training data for 100 epochs.
model.predict([[1.0, 1.0]])
Sends new data through the trained model to obtain a prediction.
The Main Idea
Keras
↓
Easy Neural Network API
↓
Create Model
↓
Add Layers
↓
Compile
↓
Train
↓
Predict
↓
Evaluate
The biggest advantage of Keras is that it lets you express a neural network using a small amount of readable Python code.
Remember This
Keras
→ High-level deep learning API
Sequential
→ Layers arranged one after another
Dense
→ Fully connected neural network layer
compile()
→ Configure training
fit()
→ Train the model
predict()
→ Make predictions
evaluate()
→ Measure model performance
The basic Keras workflow to remember is:
model = tf.keras.Sequential([
...
])
model.compile(
optimizer=...,
loss=...,
metrics=...
)
model.fit(
X_train,
y_train,
epochs=...
)
model.predict(
X_test
)
In the next topic, we will focus specifically on Creating a Neural Network and understand how the model structure is built step by step.
Check Your Understanding
What is Keras?
A high-level deep learning API that makes building and
training neural networks easier.
How is Keras related to TensorFlow?
Keras provides a high-level API, while TensorFlow
provides the underlying machine learning framework and
computation capabilities.
What does Sequential mean?
The layers are connected and processed in a sequential
order.
What does Dense(4) mean?
It creates a dense layer with 4 neurons.
What does compile() do?
It configures the model's training process, including
the optimizer and loss function.
What does fit() do?
It trains the model using the provided training data.
What does predict() do?
It sends new input through the trained model to produce
predictions.