• Stars
    star
    1,040
  • Rank 44,297 (Top 0.9 %)
  • Language
    Python
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Layers Outputs and Gradients in Keras. Made easy.

Keract: Keras Activations + Gradients

Downloads Downloads Keract CI

Tested with Tensorflow 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9 and 2.10 (Sep, 2022).

pip install keract

You have just found a way to get the activations (outputs) and gradients for each layer of your Tensorflow/Keras model (LSTM, conv nets...).

Important Note: The nested models are not well supported. The recent versions of Tensorflow made it extremely tricky to extract the layer outputs reliably. Please refer to the example section to see what is possible.

API

Get activations (nodes/layers outputs as Numpy arrays)

keract.get_activations(model, x, layer_names=None, nodes_to_evaluate=None, output_format='simple', nested=False, auto_compile=True)

Fetch activations (nodes/layers outputs as Numpy arrays) for a Keras model and an input X. By default, all the activations for all the layers are returned.

  • model: Keras compiled model or one of ['vgg16', 'vgg19', 'inception_v3', 'inception_resnet_v2', 'mobilenet_v2', 'mobilenetv2', ...].
  • x: Numpy array to feed the model as input. In the case of multi-inputs, x should be of type List.
  • layer_names: (optional) Single name of a layer or list of layer names for which activations should be returned. It is useful in very big networks when it is computationally expensive to evaluate all the layers/nodes.
  • nodes_to_evaluate: (optional) List of Keras nodes to be evaluated.
  • output_format: Change the output dictionary key of the function.
    • simple: output key will match the names of the Keras layers. For example Dense(1, name='d1') will return {'d1': ...}.
    • full: output key will match the full name of the output layer name. In the example above, it will return {'d1/BiasAdd:0': ...}.
    • numbered: output key will be an index range, based on the order of definition of each layer within the model.
  • nested: If specified, will move recursively through the model definition to retrieve nested layers. Recursion ends at leaf layers of the model tree or at layers with their name specified in layer_names. For example a Sequential model in another Sequential model is considered nested.
  • auto_compile: If set to True, will auto-compile the model if needed.

Returns: Dict {layer_name (specified by output_format) -> activation of the layer output/node (Numpy array)}.

Example

import numpy as np
from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Dense, concatenate
from keract import get_activations

# model definition
i1 = Input(shape=(10,), name='i1')
i2 = Input(shape=(10,), name='i2')

a = Dense(1, name='fc1')(i1)
b = Dense(1, name='fc2')(i2)

c = concatenate([a, b], name='concat')
d = Dense(1, name='out')(c)
model = Model(inputs=[i1, i2], outputs=[d])

# inputs to the model
x = [np.random.uniform(size=(32, 10)), np.random.uniform(size=(32, 10))]

# call to fetch the activations of the model.
activations = get_activations(model, x, auto_compile=True)

# print the activations shapes.
[print(k, '->', v.shape, '- Numpy array') for (k, v) in activations.items()]

# Print output:
# i1 -> (32, 10) - Numpy array
# i2 -> (32, 10) - Numpy array
# fc1 -> (32, 1) - Numpy array
# fc2 -> (32, 1) - Numpy array
# concat -> (32, 2) - Numpy array
# out -> (32, 1) - Numpy array

Display the activations you've obtained

keract.display_activations(activations, cmap=None, save=False, directory='.', data_format='channels_last', fig_size=(24, 24), reshape_1d_layers=False)

Plot the activations for each layer using matplotlib

Inputs are:

  • activations: dict - a dictionary mapping layers to their activations (the output of get_activations)
  • cmap: (optional) string - a valid matplotlib colormap to be used
  • save: (optional) bool - if True the images of the activations are saved rather than being shown
  • directory: (optional) string - where to store the activations (if save is True)
  • data_format: (optional) string - one of "channels_last" (default) or "channels_first".
  • reshape_1d_layers: (optional) bool - tries to reshape large 1d layers to a square/rectangle.
  • fig_size: (optional) (float, float) - width, height in inches.

The ordering of the dimensions in the inputs. "channels_last" corresponds to inputs with shape (batch, steps, channels) (default format for temporal data in Keras) while "channels_first" corresponds to inputs with shape (batch, channels, steps).

Display the activations as a heatmap overlaid on an image

keract.display_heatmaps(activations, input_image, directory='.', save=False, fix=True, merge_filters=False)

Plot heatmaps of activations for all filters overlayed on the input image for each layer

Inputs are:

  • activations: a dictionary mapping layers to their activations (the output of get_activations).
  • input_image: numpy array - the image that was passed as x to get_activations.
  • directory: (optional) string - where to store the heatmaps (if save is True).
  • save: (optional) bool - if True the heatmaps are saved rather than being shown.
  • fix: (optional) bool - if True automated checks and fixes for incorrect images will be ran.
  • merge_filters: (optional) bool - if True one heatmap (with all the filters averaged together) is produced for each layer, if False a heatmap is produced for each filter in each layer

Get gradients of weights

keract.get_gradients_of_trainable_weights(model, x, y)
  • model: a keras.models.Model object.
  • x: Numpy array to feed the model as input. In the case of multi-inputs, x should be of type List.
  • y: Labels (numpy array). Keras convention.

The output is a dictionary mapping each trainable weight to the values of its gradients (regarding x and y).

Get gradients of activations

keract.get_gradients_of_activations(model, x, y, layer_name=None, output_format='simple')
  • model: a keras.models.Model object.
  • x: Numpy array to feed the model as input. In the case of multi-inputs, x should be of type List.
  • y: Labels (numpy array). Keras convention.
  • layer_name: (optional) Name of a layer for which activations should be returned.
  • output_format: Change the output dictionary key of the function.
    • simple: output key will match the names of the Keras layers. For example Dense(1, name='d1') will return {'d1': ...}.
    • full: output key will match the full name of the output layer name. In the example above, it will return {'d1/BiasAdd:0': ...}.
    • numbered: output key will be an index range, based on the order of definition of each layer within the model.

Returns: Dict {layer_name (specified by output_format) -> grad activation of the layer output/node (Numpy array)}.

The output is a dictionary mapping each layer to the values of its gradients (regarding x and y).

Persist activations to JSON

keract.persist_to_json_file(activations, filename)
  • activations: activations (dict mapping layers)
  • filename: output filename (JSON format)

Load activations from JSON

keract.load_activations_from_json_file(filename)
  • filename: filename to read the activations from (JSON format)

It returns the activations.

Examples

Examples are provided for:

  • keras.models.Sequential - mnist.py
  • keras.models.Model - multi_inputs.py
  • Recurrent networks - recurrent.py

In the case of MNIST with LeNet, we are able to fetch the activations for a batch of size 128:

conv2d_1/Relu:0
(128, 26, 26, 32)

conv2d_2/Relu:0
(128, 24, 24, 64)

max_pooling2d_1/MaxPool:0
(128, 12, 12, 64)

dropout_1/cond/Merge:0
(128, 12, 12, 64)

flatten_1/Reshape:0
(128, 9216)

dense_1/Relu:0
(128, 128)

dropout_2/cond/Merge:0
(128, 128)

dense_2/Softmax:0
(128, 10)

We can visualise the activations. Here's another example using VGG16:

cd examples
pip install -r examples-requirements.txt
python vgg16.py


A cat.


Outputs of the first convolutional layer of VGG16.

Also, we can visualise the heatmaps of the activations:

cd examples
pip install -r examples-requirements.txt
python heat_map.py

Limitations / Ways of improvement

In some specific cases, Keract does not handle well some models that contain submodels. Feel free to fork this repo and propose a PR to fix it!

Citation

@misc{Keract,
  author = {Philippe Remy},
  title = {Keract: A library for visualizing activations and gradients},
  year = {2020},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/philipperemy/keract}},
}

Contributors

More Repositories

1

keras-attention

Keras Attention Layer (Luong and Bahdanau scores).
Python
2,804
star
2

tensorflow-1.4-billion-password-analysis

Deep Learning model to analyze a large corpus of clear text passwords.
Python
1,902
star
3

keras-tcn

Keras Temporal Convolutional Network.
Python
1,863
star
4

yolo-9000

YOLO9000: Better, Faster, Stronger - Real-Time Object Detection. 9000 classes!
1,179
star
5

deep-speaker

Deep Speaker: an End-to-End Neural Speaker Embedding System.
Python
897
star
6

n-beats

Keras/Pytorch implementation of N-BEATS: Neural basis expansion analysis for interpretable time series forecasting.
Python
852
star
7

name-dataset

The Python library for names.
Python
810
star
8

stanford-openie-python

Stanford Open Information Extraction made simple!
Python
628
star
9

deep-learning-bitcoin

Exploiting Bitcoin prices patterns with Deep Learning.
Python
525
star
10

FX-1-Minute-Data

HISTDATA - Dataset composed of all FX trading pairs / Crude Oil / Stock Indexes. Simple API to retrieve 1 Minute data (and tick data) Historical FX Prices (up to date).
Python
477
star
11

timit

The DARPA TIMIT Acoustic-Phonetic Continuous Speech Corpus.
287
star
12

Deep-Learning-Tinder

Simple Tinder algorithm able to swipe left and right based on the recommendations of a pre-trained deep neural network (Machine Learning).
Python
276
star
13

financial-news-dataset

Reuters and Bloomberg
223
star
14

cond_rnn

Conditional RNNs for Tensorflow / Keras.
Python
222
star
15

my-first-bitcoin-miner

For the curious minds who want to understand how Bitcoin Blockchain works!
Python
189
star
16

expressvpn-python

ExpressVPN - Python Wrapper (IP auto switch).
Python
182
star
17

tensorflow-multi-dimensional-lstm

Multi dimensional LSTM as described in Alex Graves' Paper https://arxiv.org/pdf/0705.2011.pdf
Jupyter Notebook
155
star
18

tensorflow-class-activation-mapping

Learning Deep Features for Discriminative Localization (2016)
Python
152
star
19

easy-encryption

A very simple C++ module to encrypt/decrypt strings based on B64 and Vigenere ciper.
C++
144
star
20

Order-Book-Matching-Engine

Order Book Matching Engine for Stock Exchanges (1us latency for matching)
Java
139
star
21

tensorflow-ctc-speech-recognition

Application of Connectionist Temporal Classification (CTC) for Speech Recognition (Tensorflow 1.0 but compatible with 2.0).
Python
131
star
22

tensorflow-phased-lstm

Phased LSTM: Accelerating Recurrent Network Training for Long or Event-based Sequences (NIPS 2016) - Tensorflow 1.0
Python
130
star
23

fractional-differentiation-time-series

As described in Advances of Machine Learning by Marcos Prado.
Python
121
star
24

amazon-reviews-scraper

Yet another multi language scraper for Amazon targeting reviews.
Python
116
star
25

lead-lag

Estimation of the lead-lag parameter from non-synchronous data.
Jupyter Notebook
108
star
26

google-news-scraper

Google News Scraper for languages like Japanese, Chinese... [VPN Support]
Python
95
star
27

stock-volatility-google-trends

Deep Learning Stock Volatility with Google Domestic Trends: https://arxiv.org/pdf/1512.04916.pdf
Python
92
star
28

mercari-python-api

The Python Mercari API.
Python
84
star
29

japanese-words-to-vectors

Word2vec (word to vectors) approach for Japanese language using Gensim and Mecab.
Python
84
star
30

Stanford-NER-Python

Stanford Named Entity Recognizer (NER) - Python Wrapper
Python
75
star
31

very-deep-convnets-raw-waveforms

Tensorflow - Very Deep Convolutional Neural Networks For Raw Waveforms - https://arxiv.org/pdf/1610.00087.pdf
Python
74
star
32

speaker-change-detection

Paper: https://arxiv.org/abs/1702.02285
Python
63
star
33

tensorflow-maxout

Maxout Networks TensorFlow implementation presented in https://arxiv.org/abs/1302.4389
Python
57
star
34

tensorflow-cnn-time-series

Feeding images of time series to Conv Nets! (Tensorflow + Keras)
Python
50
star
35

3.7-billion-passwords-tools

Tools to manipulate the data behind Collection #1 (and #2–5) - AntiPublic.
Python
48
star
36

keras-seq2seq-example

Toy Keras implementation of a seq2seq model with examples.
Python
48
star
37

tensorflow-fifo-queue-example

Example on how to use a Tensorflow Queue to feed data to your models.
Python
39
star
38

python-darknet-yolo-v4

Python to interface with Darknet Yolo V4 (multi GPU with load balancer supported).
Python
37
star
39

bitmex-liquidations

Minimal code to show how to receive the liquidations in realtime on Bitmex.
Python
33
star
40

Statistical-Arbitrage

Using Particle Markov Chain Monte Carlo
MATLAB
33
star
41

vision-api

Google Vision API made easy!
Python
30
star
42

tensorflow-grid-lstm

Implementation of the paper https://arxiv.org/pdf/1507.01526v3.pdf (Tensorflow 1.0, Python 3)
Python
29
star
43

advanced-deep-learning-keras

File repository for the course [Advanced Deep Learning with Keras]. Packt Publishing.
Jupyter Notebook
28
star
44

Facebook-Profile-Pictures-Downloader

πŸ˜† Download public profile pictures from Facebook.
Python
26
star
45

bitcoin-market-data

Largest tick market data for Bitcoin (mirror server of bitcoincharts.com).
Shell
24
star
46

beer-dataset

The biggest beer database is in this repo!
Python
23
star
47

NiceHash-api-monitoring-client

Simple NiceHash client to monitor your mining rigs. Configure alerts and emails!
Python
22
star
48

information-extraction-with-dominating-rules

Information extraction based on Stanford open IE Library and domination decision rules. http://philipperemy.github.io/information-extract/
Python
22
star
49

Market-Data

Module to retrieve realtime stock quotes of Paris stock exchange
Java
20
star
50

instant-music-playlist-downloader

Download MP3 songs from the web.
Python
20
star
51

Sentiment-Analysis-NLP

Sentiment Analysis applied to different datasets such as IMDB
Python
19
star
52

wavenet

A general TensorFlow implementation of the Wavenet network to be used to model long term sequences with less trainable parameters.
Python
18
star
53

keras-snail-attention

SNAIL Attention Block for Keras.
Python
17
star
54

which-of-your-friends-are-on-tinder

Discover which of your Facebook friends are on Tinder!
Python
16
star
55

LSTM-text-generation

Generating NEW Reuters articles from Reuters articles.
Python
16
star
56

Candlestick-Chart-Generator

Candlestick Charts in JavaScript.
JavaScript
15
star
57

keras-frn

Keras Filter Response Normalization Layer.
Python
15
star
58

keras-sde-net

Keras implementation of SDE-Net (ICML 2020).
Python
14
star
59

Peer-Group-Analysis-Clustering

Unsupervised Clustering of Time Series using Peer Group Analysis PGA
MATLAB
14
star
60

OrderBook-TWAP

Programming Test
C++
13
star
61

selenium-python-examples

Selenium examples in Python (web scraper).
Python
12
star
62

python-pubsub

A simple python implementation of a message router with many subscribers and many publishers.
Python
12
star
63

philipperemy.github.io

My blog.
SCSS
11
star
64

fxrt

Realtime FX prices from the Oanda broker.
Python
10
star
65

tensorflow-isan-rnn

Input Switched Affine Networks: An RNN Architecture Designed for Interpretability. http://proceedings.mlr.press/v70/foerster17a/foerster17a.pdf
Python
10
star
66

twitter-arxiv-sanity

Your daily "top hype" papers.
Python
9
star
67

japan-weather-forecast

Japanese Meteorological Agency (scraper + data)
Python
9
star
68

github-backup

Back up all your Github repositories in a directory.
Python
9
star
69

Leboncoin

Management of small ads (editing, publishing, deleting, re-publishing)
Java
9
star
70

Github-full-data-set

Generating GitHub data (~1M repositories May 2017).
Python
8
star
71

cocktails

Generate the best cocktail ever with Machine Learning !
Python
8
star
72

Technical-Analysis

Technical Analysis Tool based on TA Lib
C
8
star
73

Ransac-Java

Implementation of the Ransac algorithm written in Java.
Java
8
star
74

Data-Mining-Automaton

Quantitative Algobox based on Data Mining techniques
Java
8
star
75

HFT-FIX-Parser

Ultra low latency FIX Parser
7
star
76

GPU-Activity-Monitoring

Python monitoring tool for the nvidia-smi command on Linux.
Python
7
star
77

japanese-street-addresses-scraper

Scraper for Japanese street addresses (住所).
Python
7
star
78

bitstamp-realtime-order-book

Gives you low latency access to Bitstamp Realtime Order Book.
Python
7
star
79

arma-scipy-fit

Estimating coefficients of ARMA models with the Scipy package.
Python
7
star
80

urban-dictionary-transformers

Transformers applied to Urban Dictionary for fun.
Python
7
star
81

digital-setting-circles

Compatible with Raspberry Pi. Setting circles are used on telescopes equipped with an equatorial mount to find astronomical objects in the sky by their equatorial coordinates.
C++
7
star
82

binance-futures

Straightforward API endpoint to receive market data for Binance Futures.
Python
6
star
83

keras-mode-normalization

Keras Implementation of Mode Normalization (Lucas Deecke, Iain Murray, Hakan Bilen, 2018)
Python
6
star
84

Ogame-API

Ogame API
Java
6
star
85

bitflyer

Bitflyer API Realtime Feed Python.
Python
6
star
86

Kaggle-PKDD-Taxi-I

https://www.kaggle.com/c/pkdd-15-predict-taxi-service-trajectory-i
Python
6
star
87

ssh-failed-attempts

Tool to detect and analyze failed SSH attempts.
Python
5
star
88

Idealwine-wine-prices

API to retrieve quotes from daily wine auctions
Java
5
star
89

notifier

Receive notifications on your phone when your CLI tasks finish.
Python
5
star
90

API-Ratp

API to retrieve real time schedule times for Paris transports
5
star
91

Visual-Ballistic-Roulette-Vision

Ball and wheel zero tracking.
Python
5
star
92

Visual-Ballistic-Roulette-python

Visual Ballistic Roulette written in Python.
Python
5
star
93

tf-easy-model-saving

An easy way to load and save checkpoints in Tensorflow!
Python
5
star
94

Quantitative-Market-Data-Generator

Equity Prices Generator using Quantitative methods such as Brownian Motion
4
star
95

Monte-Carlo-Pi-Computation

This projects aims at computing PI using Monte Carlo method
4
star
96

Visual-Ballistic-Roulette-Timer-Android

Timer for Roulette written for Android
Java
4
star
97

EGAIN-pytorch

Python
4
star
98

Visual-Ballistic-Roulette-Display-Android

Android App
Java
4
star
99

record-your-internet-speed

Record your internet speed at fixed intervals.
Python
4
star
100

Martingale-Roulette-MonteCarlo

Monte Carlo simulations for Casino Roulette
MATLAB
4
star