Keras makes building and training neural networks simple and fast. It is easy to use and helps you focus on your ideas, not the complex code.
Keras as TensorFlow's high-level API
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
TensorFlow
import tensorflow as tf from tensorflow import keras input_size = 20 model = keras.Sequential([ keras.layers.Dense(units=10, activation='relu', input_shape=(input_size,)), keras.layers.Dense(units=1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5)
Keras is part of TensorFlow and accessed via tensorflow.keras.
The Sequential model stacks layers in order.
Examples
TensorFlow
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(100,)),
keras.layers.Dense(10, activation='softmax')
])TensorFlow
model.compile(optimizer='sgd', loss='mean_squared_error')
TensorFlow
model.fit(x_train, y_train, epochs=10, batch_size=32)
Sample Model
This program creates a small neural network using Keras inside TensorFlow. It trains on random data for 3 rounds and prints predictions for 5 samples.
TensorFlow
import tensorflow as tf from tensorflow import keras import numpy as np # Create dummy data x_train = np.random.random((100, 20)) y_train = np.random.randint(2, size=(100, 1)) # Build model model = keras.Sequential([ keras.layers.Dense(16, activation='relu', input_shape=(20,)), keras.layers.Dense(1, activation='sigmoid') ]) # Compile model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Train model history = model.fit(x_train, y_train, epochs=3, batch_size=10, verbose=2) # Make predictions predictions = model.predict(x_train[:5]) print('Predictions:', predictions.flatten())
Important Notes
Keras hides many complex details, so you can build models quickly.
Use model.compile to set how the model learns and measures success.
Training with model.fit shows progress and updates model weights.
Summary
Keras is a simple way to build neural networks inside TensorFlow.
It uses easy-to-understand code to create layers and train models.
You can quickly try ideas and get results without deep coding.
Practice
1. What is the main purpose of Keras in TensorFlow?
easy
Solution
Step 1: Understand Keras role in TensorFlow
Keras is designed as a user-friendly API to build and train neural networks easily within TensorFlow.Step 2: Compare options with Keras purpose
Options B, C, and D describe unrelated tasks. Only To provide a simple way to build and train neural networks correctly states Keras's main purpose.Final Answer:
To provide a simple way to build and train neural networks -> Option BQuick Check:
Keras purpose = simple neural network building [OK]
Hint: Keras makes neural networks easy to build and train [OK]
Common Mistakes:
- Thinking Keras replaces TensorFlow core
- Confusing Keras with data visualization tools
- Assuming Keras manages databases
2. Which of the following is the correct way to import Keras from TensorFlow?
easy
Solution
Step 1: Recall the standard import syntax for Keras in TensorFlow
The recommended way is to import Keras as a module from TensorFlow using 'from tensorflow import keras'.Step 2: Evaluate each option
import keras imports standalone keras (not recommended). import tensorflow.keras as tfk is valid syntax but aliases it as 'tfk' (keras not directly available). from keras import tensorflow reverses the import incorrectly. Only from tensorflow import keras is correct.Final Answer:
from tensorflow import keras -> Option AQuick Check:
Correct import = from tensorflow import keras [OK]
Hint: Use 'from tensorflow import keras' to import Keras [OK]
Common Mistakes:
- Using 'import keras' without tensorflow prefix
- Swapping import order incorrectly
- Trying to alias with invalid syntax
3. What will be the output shape of the model defined below?
from tensorflow import keras
model = keras.Sequential([
keras.layers.Dense(10, input_shape=(5,)),
keras.layers.Dense(3)
])
print(model.output_shape)medium
Solution
Step 1: Analyze model layers and input shape
The first Dense layer outputs 10 units for each input of shape (5,). The second Dense layer outputs 3 units. The batch size is None (unknown).Step 2: Determine final output shape
The model output shape is (None, 3), where None is batch size and 3 is output units of last layer.Final Answer:
(None, 3) -> Option CQuick Check:
Output shape = (None, 3) [OK]
Hint: Output shape matches last layer units with batch size None [OK]
Common Mistakes:
- Confusing input shape with output shape
- Using batch size 5 instead of None
- Mixing layer output units
4. Identify the error in the following Keras model code:
from tensorflow import keras model = keras.Sequential() model.add(keras.layers.Dense(10)) model.add(keras.layers.Dense(1)) model.compile(optimizer='adam', loss='mse') model.summary() model.fit(x_train, y_train, epochs=5)
medium
Solution
Step 1: Check model layer definitions
The first Dense layer lacks an input shape, which is required for the model to know input dimensions.Step 2: Verify compile and fit parameters
Optimizer 'adam' and loss 'mse' are valid. Batch size is optional in fit. So no error there.Final Answer:
Missing input shape in first Dense layer -> Option AQuick Check:
Input shape missing = error [OK]
Hint: Always specify input shape in first layer [OK]
Common Mistakes:
- Assuming batch_size is mandatory in fit
- Thinking 'mse' is invalid loss
- Confusing optimizer names
5. You want to build a Keras model that accepts images of size 28x28 with 1 color channel and outputs 10 class probabilities. Which model definition is correct?
hard
Solution
Step 1: Check input shape and layer compatibility
Images have shape (28,28,1). Flatten layer must match this shape exactly to convert to vector.Step 2: Verify output layer for classification
Output layer with 10 units and softmax activation correctly outputs class probabilities.Step 3: Evaluate each option
model = keras.Sequential([ keras.layers.Flatten(input_shape=(28,28,1)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ]) correctly uses Flatten with input_shape (28,28,1) and final Dense with softmax. model = keras.Sequential([ keras.layers.Dense(128, input_shape=(28,28,1), activation='relu'), keras.layers.Dense(10, activation='softmax') ]) incorrectly uses Dense with 3D input. model = keras.Sequential([ keras.layers.Conv2D(32, (3,3), input_shape=(28,28)), keras.layers.Dense(10, activation='softmax') ]) misses channel dimension and uses Conv2D incorrectly. model = keras.Sequential([ keras.layers.Flatten(input_shape=(28,28)), keras.layers.Dense(10) ]) misses channel dimension and lacks activation.Final Answer:
model = keras.Sequential([ keras.layers.Flatten(input_shape=(28,28,1)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ]) -> Option DQuick Check:
Correct input shape and softmax output = model = keras.Sequential([ keras.layers.Flatten(input_shape=(28,28,1)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ]) [OK]
Hint: Match input shape exactly and use softmax for classes [OK]
Common Mistakes:
- Ignoring channel dimension in input shape
- Using Dense layer directly on 3D input
- Missing softmax activation for classification
