While working on a deep learning project, I encountered an error that stopped me in my tracks – AttributeError: module ‘tensorflow’ has no attribute ‘summary’. This is a common error that many TensorFlow users face, especially when working with code examples from different versions of the library.
In this article, I’ll show you several proven methods to fix this error, based on my decade of Python development experience. I’ll explain why this error occurs and provide practical solutions you can implement right away.
Let’s get started and resolve the issues with your TensorFlow code!
Understand the Error
The error AttributeError: module 'tensorflow' has no attribute 'summary' typically occurs because of version incompatibility or improper imports. This happens for a few key reasons:
- You’re using code that was written for an older version of TensorFlow
- The TensorFlow API has changed, and the method has been moved or renamed
- You haven’t imported the correct modules
This is particularly common when working with TensorFlow 2.x while using code examples designed for TensorFlow 1.x.
Read ModuleNotFoundError: No module named tensorflow Keras
Method 1: Use the Correct Import Statement
In TensorFlow 2.x, many features have been reorganized for better structure. The summary functions have been moved to a separate module.
Instead of:
import tensorflow as tf
tf.summary.scalar('loss', loss) # This will cause the errorUse this:
import tensorflow as tf
from tensorflow.summary import scalar
scalar('loss', loss) # This works in TensorFlow 2.xAlternatively, you can access the summary operations like this:
import tensorflow as tf
tf.compat.v1.summary.scalar('loss', loss)Check out ModuleNotFoundError: No module named ‘tensorflow.keras.utils.np_utils’
Method 2: Check Your TensorFlow Version
Sometimes the error occurs simply because you’re using a TensorFlow version that doesn’t match your code. Let’s check which version you have installed:
import tensorflow as tf
print(tf.__version__)I executed the above example code and added the screenshot below.

If you’re using TensorFlow 2.x but need TensorFlow 1.x functionality, you have two options:
Option 1: Enable TensorFlow 1.x Compatibility Mode
import tensorflow as tf
tf.compat.v1.disable_eager_execution() # Disable TF 2.x behaviorThis allows you to use TensorFlow 1.x code in a TensorFlow 2.x environment.
Option 2: Install the Specific Version Required
If your code requires a specific version of TensorFlow, you can install it using pip:
pip uninstall tensorflow
pip install tensorflow==1.15.0 # Install TF 1.15 for exampleRead ModuleNotFoundError: No Module Named ‘keras.utils.vis_utils’
Method 3: Use TensorBoard Instead of Direct Summary Calls
In newer TensorFlow versions, TensorBoard integration has been streamlined. Here’s a modern approach:
import tensorflow as tf
import datetime
import os
# Simulated values for demonstration
loss_value = 0.42
epoch = 1
# Create a log directory
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
os.makedirs(log_dir, exist_ok=True)
# Create a file writer
file_writer = tf.summary.create_file_writer(log_dir)
# Log the loss scalar to TensorBoard
with file_writer.as_default():
tf.summary.scalar('loss', loss_value, step=epoch)
print(f"Logged loss={loss_value} at epoch={epoch} to {log_dir}")I executed the above example code and added the screenshot below.

This approach works well with TensorFlow 2.x and is the recommended way to log metrics for TensorBoard.
Check out ModuleNotFoundError: No module named ‘tensorflow.python.keras’
Method 4: Update Your Code to Use TensorFlow 2.x API
If you’re working with older code examples, the best long-term solution is to update them to use the TensorFlow 2.x API:
import tensorflow as tf
import datetime
import os
# Simulated loss and step value
loss = 0.37
step_value = 2
# Set up log directory
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
os.makedirs(log_dir, exist_ok=True)
# Create a summary writer
writer = tf.summary.create_file_writer(log_dir)
# Log the scalar using the TF 2.x API
with writer.as_default():
tf.summary.scalar('loss', loss, step=step_value)
print(f"Logged loss={loss} at step={step_value} using TF 2.x API to {log_dir}")I executed the above example code and added the screenshot below.

The new API is more intuitive and works better with eager execution, which is the default in TensorFlow 2.x.
Read AttributeError: module ‘tensorflow’ has no attribute ‘count_nonzero’
Method 5: Use tf.compat.v1 Module
For a quick fix without rewriting your entire codebase, you can use the compatibility layer that TensorFlow provides:
import tensorflow as tf
# Replace all tf.summary calls with tf.compat.v1.summary
summary_op = tf.compat.v1.summary.scalar('loss', loss)
merged = tf.compat.v1.summary.merge_all()
writer = tf.compat.v1.summary.FileWriter('/path/to/logs')This approach lets you keep most of your code intact while still using TensorFlow 2.x.
Check out AttributeError: module ‘tensorflow’ has no attribute ‘reduce_sum’
Real-World Example: Stock Price Prediction Model
Let’s look at a practical example where we might encounter this error. Imagine we’re building a stock price prediction model for companies in the S&P 500:
import tensorflow as tf
import numpy as np
import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
# Load stock data for Apple
data = pd.read_csv('AAPL_stock_data.csv')
# Preprocess data...
# Create and train model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mean_squared_error')
# Set up TensorBoard logging correctly in TF 2.x
log_dir = "logs/fit/"
tensorboard_callback = tf.keras.callbacks.TensorBoard(
log_dir=log_dir, histogram_freq=1)
# Train the model with proper TensorBoard integration
model.fit(x_train, y_train,
batch_size=32,
epochs=100,
callbacks=[tensorboard_callback])This example shows how to properly integrate TensorBoard logging in a TensorFlow 2.x environment, avoiding the summary attribute error.
Read Solve AttributeError: module ‘tensorflow’ has no attribute ‘py_function’
Troubleshoot Tips
If you’re still experiencing issues, here are some additional troubleshooting steps:
- Check if you have multiple TensorFlow installations that might be conflicting
- Ensure you’re not mixing import styles (e.g., mixing
tf.summaryandtf.compat.v1.summary) - Clear your Jupyter notebook kernel or restart your Python environment
- Check the official TensorFlow documentation for the specific function you’re trying to use
Prevent the Error in Future Projects
To avoid this error in future projects:
- Always check the TensorFlow version compatibility when using code examples
- Use version-specific documentation that matches your installed TensorFlow version
- Consider using a virtual environment for each project with specific dependencies
- Add version checks in your code for better error messages
I hope this guide helps you solve the AttributeError: module 'tensorflow' has no attribute 'summary' error. Remember that TensorFlow’s API has evolved significantly between versions, so keeping up with these changes is key to successful development.
You may read:
- ModuleNotFoundError: No module named ‘tensorflow.keras.layers’
- TensorFlow Convolution Neural Network
- AttributeError: Module ‘tensorflow’ has no attribute ‘placeholder’

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.