Keras Out of memory with small batch size

I built an autoencoder using just tensorflow libraries with a network shape of:

I built an autoencoder using just tensorflow libraries with a network shape of:

Layer (type) Output Shape Param #

input_1 (InputLayer) (None, 168, 120, 3) 0

flatten_1 (Flatten) (None, 60480) 0

dense_1 (Dense) (None, 1024) 61932544

dense_2 (Dense) (None, 256) 262400

dense_3 (Dense) (None, 1024) 263168

dense_4 (Dense) (None, 60480) 61992000

reshape_1 (Reshape) (None, 168, 120, 3) 0

Total params: 124,450,112
Trainable params: 124,450,112
Non-trainable params: 0

In the project just using tensorflow, I was able to train using my GPUs with no problem, with a batch size of 128. I wanted to recreate the autoencoder with just keras, and I run into an out of memory exception even with a batch size of one. From researching the problem, I've found that the best solution to this problem is to reduce the batch size, but I can't reduce it any further. My machine has 2 GTX 970 cards running in SLI (CUDA doesn't care about SLI) for a total of 8GB of memory. Why would I not be able to train this network with keras, even though I was able to train the same one with 64x the batch size using tensorflow?

Here is the relevant code:


# Constants

WIDTH = 120
HEIGHT = 168


INPUT_PATH = './input/'
VALIDATION_PATH = './validation/'
MODEL_PATH = './model/'

MODEL_FILE = 'my_model.h5'
EPOCH_FILE = 'initial_epoch.txt'

Initialization and save:

# this is our input placeholder
input_img = Input(shape=(constants.HEIGHT,constants.WIDTH,constants.CHANNELS))

flatten image into one dimension

flatten = Flatten()(input_img)

hidden layer 1

hidden = Dense(constants.HIDDEN_WIDTH, activation='relu')(flatten)

"encoded" is the encoded representation of the input

encoded = Dense(constants.ENCODING_WIDTH, activation='relu')(hidden)

hidden layer 3

hidden = Dense(constants.HIDDEN_WIDTH, activation='relu')(encoded)

"decoded" is the lossy reconstruction of the input

decoded = Dense(constants.NUM_INPUTS, activation='relu')(hidden)

reshape to image dimensions

reshape = Reshape((constants.HEIGHT,constants.WIDTH,constants.CHANNELS))(decoded)

this model maps an input to its reconstruction

autoencoder = Model(input_img, reshape)


autoencoder.compile(optimizer='adam', loss='mean_squared_error')

train_datagen = ImageDataGenerator(data_format='channels_last',

test_datagen = ImageDataGenerator(data_format='channels_last',

train_generator = train_datagen.flow_from_directory(

validation_generator = test_datagen.flow_from_directory(


Creates a HDF5 file 'my_model.h5'
with open(constants.MODEL_PATH+constants.EPOCH_FILE, 'w') as f:

print("Done, model created in: " + constants.MODEL_PATH)

Part of the error log:

2019-01-29 16:40:10.522222: W tensorflow/core/common_runtime/] ***********************************************************************************************_____
2019-01-29 16:40:10.525191: W tensorflow/core/framework/] OP_REQUIRES failed at : Resource exhausted: OOM when allocating tensor with shape[60480,1024] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
Traceback (most recent call last):
File "", line 53, in <module>
File "C:\Users\dekke\Anaconda3\envs\tensorflow\lib\site-packages\keras\legacy\", line 91, in wrapper
return func(*args, **kwargs)
File "C:\Users\dekke\Anaconda3\envs\tensorflow\lib\site-packages\keras\engine\", line 1418, in fit_generator
File "C:\Users\dekke\Anaconda3\envs\tensorflow\lib\site-packages\keras\engine\", line 217, in fit_generator
File "C:\Users\dekke\Anaconda3\envs\tensorflow\lib\site-packages\keras\engine\", line 1217, in train_on_batch
outputs = self.train_function(ins)
File "C:\Users\dekke\Anaconda3\envs\tensorflow\lib\site-packages\keras\backend\", line 2715, in call
return self._call(inputs)
File "C:\Users\dekke\Anaconda3\envs\tensorflow\lib\site-packages\keras\backend\", line 2675, in _call
fetched = self._callable_fn(*array_vals)
File "C:\Users\dekke\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\", line 1439, in call
File "C:\Users\dekke\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\", line 528, in exit
tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[1024,60480] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
[[{{node training/Adam/gradients/dense_4/MatMul_grad/MatMul_1}} = MatMul[T=DT_FLOAT, _class=["loc:@training/Adam/gradients/dense_4/MatMul_grad/MatMul"], transpose_a=true, transpose_b=false, _device="/job:localhost/replica:0/task:0/device:GPU:0"](dense_3/Relu, training/Adam/gradients/dense_4/Relu_grad/ReluGrad)]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Top Python Development Companies | Hire Python Developers

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When you look for the developer in hurry you may forget to take note of review and ratings of the company's aspects, but we at TopDevelopers have done a clear analysis of these top reviewed Python development companies listed here and have picked the best ones for you.

List of Best Python Web Development Companies & Expert Python Programmers.

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Job Interview Preparation Questions
& Much More

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language