{"id":13570145,"url":"https://github.com/philipperemy/keract","last_synced_at":"2025-05-14T02:04:50.499Z","repository":{"id":45270548,"uuid":"91534719","full_name":"philipperemy/keract","owner":"philipperemy","description":"Layers Outputs and Gradients in Keras. Made easy.","archived":false,"fork":false,"pushed_at":"2025-04-07T02:04:56.000Z","size":4438,"stargazers_count":1056,"open_issues_count":3,"forks_count":189,"subscribers_count":31,"default_branch":"master","last_synced_at":"2025-05-13T05:26:10.360Z","etag":null,"topics":["deep-learning","keras","keras-neural-networks","keras-tutorials","keras-visualization","machine-learning","mnist","multi-inputs","visualize-activations"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/philipperemy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["philipperemy"]}},"created_at":"2017-05-17T04:50:57.000Z","updated_at":"2025-05-06T19:09:18.000Z","dependencies_parsed_at":"2022-08-29T08:50:13.380Z","dependency_job_id":"430f0596-53d5-410d-9e97-868577f085ba","html_url":"https://github.com/philipperemy/keract","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/philipperemy%2Fkeract","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/philipperemy%2Fkeract/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/philipperemy%2Fkeract/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/philipperemy%2Fkeract/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/philipperemy","download_url":"https://codeload.github.com/philipperemy/keract/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254052692,"owners_count":22006716,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deep-learning","keras","keras-neural-networks","keras-tutorials","keras-visualization","machine-learning","mnist","multi-inputs","visualize-activations"],"created_at":"2024-08-01T14:00:48.784Z","updated_at":"2025-05-14T02:04:50.462Z","avatar_url":"https://github.com/philipperemy.png","language":"Python","funding_links":["https://github.com/sponsors/philipperemy"],"categories":["Python Libraries(sort in alphabeta order)","Python","模型的可解释性","其他_机器学习与深度学习","Repos","Uncategorized"],"sub_categories":["Evaluation methods","Uncategorized"],"readme":"# Keract: Keras Activations + Gradients\n\n### Looking for contributors to upgrade this lib to Tensorflow 2.16+\n\n\n[![Downloads](https://pepy.tech/badge/keract)](https://pepy.tech/project/keract)\n[![Downloads](https://pepy.tech/badge/keract/month)](https://pepy.tech/project/keract)\n![Keract CI](https://github.com/philipperemy/keract/workflows/Keract%20CI/badge.svg) \n\nTested with Tensorflow 2.9, 2.10, 2.11, 2.12, 2.13, 2.14 and 2.15 (Nov 17, 2023).\n\nNot compatible with Tensorflow 2.16+.\n\n```bash\npip install keract\n```\n\n*You have just found a way to get the activations (outputs) and gradients for each layer of your Tensorflow/Keras model (LSTM, conv nets...).*\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/intro.png\"\u003e\n\u003c/p\u003e\n\n**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.\n\n## API\n\n- [get_activations](#get-activations-nodeslayers-outputs-as-numpy-arrays)\n- [display_activations](#display-the-activations-youve-obtained)\n- [display_heatmaps](#display-the-activations-as-a-heatmap-overlaid-on-an-image)\n- [get_gradients_of_trainable_weights](#get-gradients-of-weights)\n- [get_gradients_of_activations](#get-gradients-of-activations)\n- [persist_to_json_file](#persist-activations-to-json)\n- [load_activations_from_json_file](#load-activations-from-json)\n\n### Get activations (nodes/layers outputs as Numpy arrays)\n\n```python\nkeract.get_activations(model, x, layer_names=None, nodes_to_evaluate=None, output_format='simple', nested=False, auto_compile=True)\n```\n\nFetch activations (nodes/layers outputs as Numpy arrays) for a Keras model and an input X.\nBy default, all the activations for all the layers are returned.\n\n- `model`: Keras compiled model or one of ['vgg16', 'vgg19', 'inception_v3', 'inception_resnet_v2',\n    'mobilenet_v2', 'mobilenetv2', ...].\n- `x`: Numpy array to feed the model as input. In the case of multi-inputs, `x` should be of type List.\n- `layer_names`: (optional) Single name of a layer or list of layer names for which activations should be\n    returned. It is useful in very big networks when it is computationally expensive to evaluate all the layers/nodes.\n- `nodes_to_evaluate`: (optional) List of Keras nodes to be evaluated.\n- `output_format`: Change the output dictionary key of the function.\n   - `simple`: output key will match the names of the Keras layers. For example Dense(1, name='d1') will\n    return {'d1': ...}.\n   - `full`: output key will match the full name of the output layer name. In the example above, it will\n    return {'d1/BiasAdd:0': ...}.\n   - `numbered`: output key will be an index range, based on the order of definition of each layer within the model.\n- `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.\n- `auto_compile`: If set to True, will auto-compile the model if needed.\n\nReturns: Dict {layer_name (specified by output_format) -\u003e activation of the layer output/node (Numpy array)}.\n\n*Example*\n\n```python\nimport numpy as np\nfrom tensorflow.keras import Input, Model\nfrom tensorflow.keras.layers import Dense, concatenate\nfrom keract import get_activations\n\n# model definition\ni1 = Input(shape=(10,), name='i1')\ni2 = Input(shape=(10,), name='i2')\n\na = Dense(1, name='fc1')(i1)\nb = Dense(1, name='fc2')(i2)\n\nc = concatenate([a, b], name='concat')\nd = Dense(1, name='out')(c)\nmodel = Model(inputs=[i1, i2], outputs=[d])\n\n# inputs to the model\nx = [np.random.uniform(size=(32, 10)), np.random.uniform(size=(32, 10))]\n\n# call to fetch the activations of the model.\nactivations = get_activations(model, x, auto_compile=True)\n\n# print the activations shapes.\n[print(k, '-\u003e', v.shape, '- Numpy array') for (k, v) in activations.items()]\n\n# Print output:\n# i1 -\u003e (32, 10) - Numpy array\n# i2 -\u003e (32, 10) - Numpy array\n# fc1 -\u003e (32, 1) - Numpy array\n# fc2 -\u003e (32, 1) - Numpy array\n# concat -\u003e (32, 2) - Numpy array\n# out -\u003e (32, 1) - Numpy array\n```\n\n### Display the activations you've obtained\n\n```python\nkeract.display_activations(activations, cmap=None, save=False, directory='.', data_format='channels_last', fig_size=(24, 24), reshape_1d_layers=False)\n```\n\nPlot the activations for each layer using matplotlib\n\nInputs are:\n- `activations`: dict - a dictionary mapping layers to their activations (the output of get_activations)\n- `cmap`: (optional) string - a valid matplotlib colormap to be used\n- `save`: (optional) bool - if True the images of the activations are saved rather than being shown\n- `directory`: (optional) string - where to store the activations (if save is True)\n- `data_format`: (optional) string - one of \"channels_last\" (default) or \"channels_first\".\n- `reshape_1d_layers`: (optional) bool - tries to reshape large 1d layers to a square/rectangle.\n- `fig_size`: (optional) (float, float) - width, height in inches.\n\nThe 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).\n\n### Display the activations as a heatmap overlaid on an image\n\n```python\nkeract.display_heatmaps(activations, input_image, directory='.', save=False, fix=True, merge_filters=False)\n```\n\nPlot heatmaps of activations for all filters overlayed on the input image for each layer\n\nInputs are:\n- `activations`: a dictionary mapping layers to their activations (the output of get_activations).\n- `input_image`:  numpy array - the image that was passed as x to get_activations.\n- `directory`: (optional) string - where to store the heatmaps (if save is True).\n- `save`: (optional) bool - if True the heatmaps are saved rather than being shown.\n- `fix`: (optional) bool - if True automated checks and fixes for incorrect images will be ran.\n- `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\n\n### Get gradients of weights\n\n```python\nkeract.get_gradients_of_trainable_weights(model, x, y)\n```\n\n- `model`: a `keras.models.Model` object.\n- `x`: Numpy array to feed the model as input. In the case of multi-inputs, `x` should be of type List.\n- `y`: Labels (numpy array). Keras convention.\n\nThe output is a dictionary mapping each trainable weight to the values of its gradients (regarding x and y).\n\n### Get gradients of activations\n\n```python\nkeract.get_gradients_of_activations(model, x, y, layer_name=None, output_format='simple')\n```\n\n- `model`: a `keras.models.Model` object.\n- `x`: Numpy array to feed the model as input. In the case of multi-inputs, `x` should be of type List.\n- `y`: Labels (numpy array). Keras convention.\n- `layer_name`: (optional) Name of a layer for which activations should be returned.\n- `output_format`: Change the output dictionary key of the function.\n   - `simple`: output key will match the names of the Keras layers. For example Dense(1, name='d1') will\n    return {'d1': ...}.\n   - `full`: output key will match the full name of the output layer name. In the example above, it will\n    return {'d1/BiasAdd:0': ...}.\n   - `numbered`: output key will be an index range, based on the order of definition of each layer within the model.\n\nReturns: Dict {layer_name (specified by output_format) -\u003e grad activation of the layer output/node (Numpy array)}.\n\nThe output is a dictionary mapping each layer to the values of its gradients (regarding x and y).\n\n### Persist activations to JSON\n\n```python\nkeract.persist_to_json_file(activations, filename)\n```\n\n- `activations`: activations (dict mapping layers)\n- `filename`: output filename (JSON format)\n\n### Load activations from JSON\n\n```python\nkeract.load_activations_from_json_file(filename)\n```\n\n- `filename`: filename to read the activations from (JSON format)\n\nIt returns the activations.\n\n## Examples\n\nExamples are provided for:\n- `keras.models.Sequential` - mnist.py\n- `keras.models.Model` - multi_inputs.py\n- Recurrent networks - recurrent.py\n\nIn the case of MNIST with LeNet, we are able to fetch the activations for a batch of size 128:\n\n```\nconv2d_1/Relu:0\n(128, 26, 26, 32)\n\nconv2d_2/Relu:0\n(128, 24, 24, 64)\n\nmax_pooling2d_1/MaxPool:0\n(128, 12, 12, 64)\n\ndropout_1/cond/Merge:0\n(128, 12, 12, 64)\n\nflatten_1/Reshape:0\n(128, 9216)\n\ndense_1/Relu:0\n(128, 128)\n\ndropout_2/cond/Merge:0\n(128, 128)\n\ndense_2/Softmax:0\n(128, 10)\n```\n\nWe can visualise the activations. Here's another example using VGG16:\n\n```bash\ncd examples\npip install -r examples-requirements.txt\npython vgg16.py\n```\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/cat.jpg\"\u003e\n  \u003cbr\u003e\u003ci\u003eA cat.\u003c/i\u003e\n\u003c/p\u003e\n\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/cat_activations.png\" width=\"600\"\u003e\n  \u003cbr\u003e\u003ci\u003eOutputs of the first convolutional layer of VGG16.\u003c/i\u003e\n\u003c/p\u003e\n\nAlso, we can visualise the heatmaps of the activations:\n\n```bash\ncd examples\npip install -r examples-requirements.txt\npython heat_map.py\n```\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/heatmap.png\"\u003e\n\u003c/p\u003e\n\n## Limitations / Ways of improvement\n\nIn 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!\n\n## Citation\n\n```\n@misc{Keract,\n  author = {Philippe Remy},\n  title = {Keract: A library for visualizing activations and gradients},\n  year = {2020},\n  publisher = {GitHub},\n  journal = {GitHub repository},\n  howpublished = {\\url{https://github.com/philipperemy/keract}},\n}\n```\n\n## Contributors\n\n\u003ca href=\"https://github.com/philipperemy/keract/graphs/contributors\"\u003e\n  \u003cimg src=\"https://contrib.rocks/image?repo=philipperemy/keract\" /\u003e\n\u003c/a\u003e\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fphilipperemy%2Fkeract","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fphilipperemy%2Fkeract","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fphilipperemy%2Fkeract/lists"}