tensorflow
keras
tf.keras
machine learning
python

How to import keras from tf.keras in Tensorflow?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Importing Keras from tf.keras in TensorFlow

TensorFlow, an open-source machine learning framework, has its own high-level neural networks API called Keras, built under the module tf.keras. This official submodule provides a simplified way to build, train, and evaluate deep learning models. Understanding how to effectively import and use tf.keras is essential for building scalable and efficient models. In this article, we will explore the details of importing and using Keras within the context of TensorFlow.

Keras in TensorFlow

Keras was initially an independent project but was later integrated into TensorFlow starting from TensorFlow 2.0. Open-sourcing it under TensorFlow's umbrella enabled several optimizations unique to this framework, such as seamless support for distributed training and TensorFlow-specific optimizations.

How to Import Keras

  1. Standard Import: To use Keras within TensorFlow, import it from the tf.keras package. Here is how you typically handle imports:
python
   import tensorflow as tf
   from tensorflow.keras.models import Sequential
   from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten
  1. Flexible Modular Imports: Import specifically what's required:
python
   from tensorflow.keras.layers import Dense
  1. Accessing Pretrained Models:
python
   from tensorflow.keras.applications import VGG16

Building a Model with tf.keras

Keras models can be instantiated via two ways: Sequential API and Functional API. Below, we illustrate the usage of the Sequential API to create a simple feedforward neural network:

python
1model = Sequential([
2    Dense(64, activation='relu', input_shape=(784,)),
3    Dense(64, activation='relu'),
4    Dense(10, activation='softmax')
5])

Alternatively, using the Functional API, which is more flexible for complex architectures:

python
1inputs = tf.keras.Input(shape=(784,))
2x = Dense(64, activation='relu')(inputs)
3x = Dense(64, activation='relu')(x)
4outputs = Dense(10, activation='softmax')(x)
5
6model = tf.keras.Model(inputs=inputs, outputs=outputs)

Compiling the Model

After defining the model architecture, the model must be compiled with an optimizer, loss function, and evaluation metric:

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

Training the Model

Use the fit method to train:

python
history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_split=0.2)

Evaluating and Making Predictions

Evaluate the model using:

python
loss, accuracy = model.evaluate(x_test, y_test)
print(f'Test accuracy: {accuracy}')

Make predictions on new data:

python
predictions = model.predict(x_new)

Key Points

The table below summarizes key points and considerations in the process of using tf.keras:

Key AspectDetails
ImportingUse import tensorflow as tf followed by tf.keras functionalities
Model DefinitionUtilizes Sequential or Functional API to define architecture
CompilationRequires specification of optimizer, loss, and metrics
TrainingConducted using the fit method with options for epoch, batch size, etc.
EvaluationUse evaluate method to measure performance against test dataset
PredictionEmploy the predict method to obtain outputs for new data

Advanced Usage

  • Custom Layers: Enhance your model with custom layers by subclassing tf.keras.layers.Layer.
  • Callbacks: Implement events like early stopping or learning rate schedules using tf.keras.callbacks.
  • Distributed Training: Leverage tf.distribute.Strategy for training on TPU, multiple GPUs, or across different nodes.

Conclusion

The integration of Keras inside TensorFlow as tf.keras provides a cohesive and powerful API for building neural networks. Its high-level simplicity, coupled with TensorFlow's robust performance, allows developers to prototype and deploy models efficiently. As you build your deep learning projects, mastering tf.keras ensures not only rapid development but also robust integration with TensorFlow’s features.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.