How can Keras be used to train the model using Python?

TensorFlow is a machine learning framework provided by Google. It is an open-source framework used with Python to implement algorithms, deep learning applications, and much more. Keras is a high-level deep learning API that runs on top of TensorFlow, making it easier to build and train neural networks.

Installation

The TensorFlow package (which includes Keras) can be installed using ?

pip install tensorflow

Importing Keras

Keras is already integrated within TensorFlow and can be accessed using ?

import tensorflow as tf
from tensorflow import keras
import numpy as np

print("TensorFlow version:", tf.__version__)
print("Keras version:", keras.__version__)
TensorFlow version: 2.x.x
Keras version: 2.x.x

Creating a Simple Model

Let's create a basic neural network model using Keras Sequential API ?

import tensorflow as tf
from tensorflow import keras
import numpy as np

# Create a simple sequential model
model = keras.Sequential([
    keras.layers.Dense(64, activation='relu', input_shape=(10,)),
    keras.layers.Dense(32, activation='relu'),
    keras.layers.Dense(1, activation='sigmoid')
])

# Compile the model
model.compile(optimizer='adam', 
              loss='binary_crossentropy', 
              metrics=['accuracy'])

print("Model created successfully!")
print(model.summary())
Model created successfully!
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 64)                704       
dense_1 (Dense)              (None, 32)                2080      
dense_2 (Dense)              (None, 1)                 33        
=================================================================
Total params: 2,817
Trainable params: 2,817
Non-trainable params: 0

Training the Model

Here's how to train a Keras model with sample data ?

import tensorflow as tf
from tensorflow import keras
import numpy as np

# Create sample data
X_train = np.random.random((1000, 10))  # 1000 samples, 10 features each
y_train = np.random.randint(2, size=(1000, 1))  # Binary classification

# Create and compile model
model = keras.Sequential([
    keras.layers.Dense(64, activation='relu', input_shape=(10,)),
    keras.layers.Dense(32, activation='relu'),
    keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', 
              loss='binary_crossentropy', 
              metrics=['accuracy'])

print("Training the model...")
# Train the model
history = model.fit(X_train, y_train, 
                    epochs=3, 
                    batch_size=32, 
                    validation_split=0.2,
                    verbose=1)

print("Training completed!")
Training the model...
Epoch 1/3
25/25 [==============================] - 1s 15ms/step - loss: 0.6935 - accuracy: 0.5125 - val_loss: 0.6889 - val_accuracy: 0.5400
Epoch 2/3
25/25 [==============================] - 0s 4ms/step - loss: 0.6874 - accuracy: 0.5275 - val_loss: 0.6838 - val_accuracy: 0.5450
Epoch 3/3
25/25 [==============================] - 0s 4ms/step - loss: 0.6820 - accuracy: 0.5537 - val_loss: 0.6794 - val_accuracy: 0.5550
Training completed!

Multi-Input Multi-Output Model Training

For complex models with multiple inputs and outputs, use the Functional API ?

import tensorflow as tf
from tensorflow import keras
import numpy as np

# Define model parameters
num_words = 1000
num_tags = 10
num_classes = 5

# Create inputs
title_input = keras.Input(shape=(10,), name='title')
body_input = keras.Input(shape=(100,), name='body')
tags_input = keras.Input(shape=(num_tags,), name='tags')

# Process inputs
title_features = keras.layers.Embedding(num_words, 64)(title_input)
title_features = keras.layers.LSTM(32)(title_features)

body_features = keras.layers.Embedding(num_words, 64)(body_input)
body_features = keras.layers.LSTM(32)(body_features)

# Combine all features
combined = keras.layers.concatenate([title_features, body_features, tags_input])
combined = keras.layers.Dense(64, activation='relu')(combined)

# Create outputs
priority_output = keras.layers.Dense(1, activation='sigmoid', name='priority')(combined)
class_output = keras.layers.Dense(num_classes, activation='softmax', name='class')(combined)

# Create and compile model
model = keras.Model(inputs=[title_input, body_input, tags_input],
                   outputs=[priority_output, class_output])

model.compile(optimizer='adam',
              loss={'priority': 'binary_crossentropy', 
                    'class': 'categorical_crossentropy'},
              metrics=['accuracy'])

# Generate sample data
title_data = np.random.randint(num_words, size=(1000, 10))
body_data = np.random.randint(num_words, size=(1000, 100))
tags_data = np.random.randint(2, size=(1000, num_tags)).astype('float32')

priority_targets = np.random.random(size=(1000, 1))
dept_targets = keras.utils.to_categorical(np.random.randint(num_classes, size=(1000,)), num_classes)

# Train the model
print("Training multi-input model...")
model.fit(
    {'title': title_data, 'body': body_data, 'tags': tags_data},
    {'priority': priority_targets, 'class': dept_targets},
    epochs=2,
    batch_size=32
)

Key Training Parameters

Parameter Description Example Values
epochs Number of complete passes through training data 10, 50, 100
batch_size Number of samples processed before updating weights 16, 32, 64, 128
validation_split Fraction of data reserved for validation 0.1, 0.2, 0.3

Conclusion

Keras simplifies neural network training with its intuitive API. Use model.fit() to train models with your data, specifying epochs and batch size. The Functional API enables complex multi-input/output architectures for advanced applications.

Updated on: 2026-03-25T14:49:43+05:30

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements