master 4220d581799e cached
12 files
29.6 KB
8.5k tokens
5 symbols
1 requests
Download .txt
Repository: wcipriano/pretty-print-confusion-matrix
Branch: master
Commit: 4220d581799e
Files: 12
Total size: 29.6 KB

Directory structure:
gitextract_mfctpddf/

├── .flake8
├── .github/
│   └── FUNDING.yml
├── .gitignore
├── .pre-commit-config.yaml
├── LICENSE
├── README.md
├── examples/
│   ├── arrays_example.py
│   ├── df_example.py
│   └── docs.py
├── pretty_confusion_matrix/
│   ├── __init__.py
│   └── pretty_confusion_matrix.py
└── pyproject.toml

================================================
FILE CONTENTS
================================================

================================================
FILE: .flake8
================================================
[flake8]
ignore = E203, E266, E501, W503, F403, F401
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9

================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: wcipriano
buy_me_a_coffee: wcipriano


================================================
FILE: .gitignore
================================================
__pycache__
dist
.venv/
.idea
bkp/*
*-local-*
matrix-output-*

================================================
FILE: .pre-commit-config.yaml
================================================
repos:
-   repo: https://github.com/ambv/black
    rev: 20.8b1
    hooks:
    - id: black
-   repo: https://gitlab.com/pycqa/flake8
    rev: 3.8.4
    hooks:
    - id: flake8
- repo: https://github.com/kynan/nbstripout
  rev: 0.5.0
  hooks:
    - id: nbstripout


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pretty-confusion-matrix?logo=python&logoColor=%23FFFFFF)
<a href="https://pypi.org/project/pretty-confusion-matrix/"><img alt="PyPI" src="https://img.shields.io/pypi/v/pretty-confusion-matrix?logo=pypi&logoColor=%23FFFFFF"></a>
<a href="https://github.com/psf/black"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg?logo=codeclimate&logoColor=%23FFFFFF"></a>
![PyPI - Wheel](https://img.shields.io/pypi/wheel/pretty-confusion-matrix)
<a href="https://libraries.io/pypi/pretty-confusion-matrix"><img alt="GitHub Repo stars" src="https://img.shields.io/librariesio/github/wcipriano/pretty-print-confusion-matrix"></a>
<a href="https://github.com/wcipriano"><img alt="GitHub Repo stars" src="https://img.shields.io/github/license/wcipriano/pretty-print-confusion-matrix?logo=apache"></a>
<a href="https://github.com/wcipriano/pretty-print-confusion-matrix/blob/master/LICENSE"><img alt="GitHub License" src="https://img.shields.io/github/stars/wcipriano/pretty-print-confusion-matrix?style=flat&logo=github"></a>
![PyPI - Downloads](https://img.shields.io/pypi/dm/pretty-confusion-matrix?logo=download)

# Confusion Matrix in Python
Plot a pretty confusion matrix (like Matlab) in python using seaborn and matplotlib.

This module get a pretty print confusion matrix from a NumPy matrix or from 2 NumPy arrays (`y_test` and `predictions`).


## Become a sponsor
Please, consider contributing it to the project.
Support the developers who power open source!
Invest in open source. It powers your world.
Become a sponsor now!

If my open source projects could bring you closer to your goals and you want to say thank you, and you can contribute, feel free to do [Buy me a ☕](https://buymeacoffee.com/wcipriano) !

Or Become a sponsor directly on [GitHub sponsors page](https://github.com/sponsors/wcipriano?frequency=recurring&) ! 
You will receive a **sponsor badge** on your profile.


I will be really thankfull for anything even if it is a coffee or just a kind comment towards my work, because that helps me a lot. 

See my projects and my contacts in my [Linktree](https://linktr.ee/wagner.cipriano) if you want to stay connected!






## Installation
```bash
pip install pretty-confusion-matrix
```

## Get Started

### Plotting from DataFrame:
```python
import numpy as np
import pandas as pd
from pretty_confusion_matrix import pp_matrix

array = np.array([[13,  0,  1,  0,  2,  0],
                  [0, 50,  2,  0, 10,  0],
                  [0, 13, 16,  0,  0,  3],
                  [0,  0,  0, 13,  1,  0],
                  [0, 40,  0,  1, 15,  0],
                  [0,  0,  0,  0,  0, 20]])

# get pandas dataframe
df_cm = pd.DataFrame(array, index=range(1, 7), columns=range(1, 7))
# colormap: see this and choose your more dear
cmap = 'PuRd'
pp_matrix(df_cm, cmap=cmap)
```
![alt text](https://raw.githubusercontent.com/khuyentran1401/pretty-print-confusion-matrix/master/Screenshots/Conf_matrix_default.png)


### Plotting from vectors


```python
import numpy as np
from pretty_confusion_matrix import pp_matrix_from_data

y_test = np.array([1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2,
                  3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5])
predic = np.array([1, 2, 4, 3, 5, 1, 2, 4, 3, 5, 1, 2, 3, 4, 4, 1, 4, 3, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 3, 3, 5, 1, 2, 3, 3, 5, 1, 2,
                  3, 4, 4, 1, 2, 3, 4, 1, 1, 2, 3, 4, 1, 1, 2, 3, 4, 1, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5])

pp_matrix_from_data(y_test, predic)
```

![alt text](https://raw.githubusercontent.com/khuyentran1401/pretty-print-confusion-matrix/master/Screenshots/Conf_matrix_default_2.png)


## Using custom labels in axis
You can customize the labels in axis, whether by DataFrame or vectors.

### From DataFrame
To plot the matrix with text labels in axis rather than integer, change the params `index` and `columns` of your dataframe.
Getting the example one above, just change the line `df_cm = pd.DataFrame(array, index=range(1, 7), columns=range(1, 7))` by
```python
col = ['Dog', 'Cat', 'Mouse', 'Fox', 'Bird', 'Chicken']
df_cm = pd.DataFrame(array, index=col, columns=col)
```
It'll replace the integer labels (**1...6**) in the axis, by **Dog, Cat, Mouse**, and so on..


### From vectors
It's very similar, in this case you just need to use the `columns` param like the example below.
This param is a positional array, i.e., the order must be the same of the data representation. 
In this example _Dog_ will be assigned to the class 0, _Cat_ will be assigned to the class 1, and so on and so forth.
Getting the example two above, just change the line `pp_matrix_from_data(y_test, predic)`, by
```python
columns = ['Dog', 'Cat', 'Mouse', 'Fox', 'Bird'] 
pp_matrix_from_data(y_test, predic, columns)
```
It'll replace "class A, ..., class E" in the axis, by **Dog, Cat, ..., Bird**.

More information about "_How to plot confusion matrix with string axis rather than integer in python_" in [this Stackoverflow answer](https://stackoverflow.com/a/51176855/1809554).



## Choosing Colormaps

You can choose the layout of the your matrix by a lot of colors options like PuRd, Oranges and more... 
To customizer your color scheme, use the param cmap of funcion pp_matrix. 
To see all the colormap available, please do this:
```python
from matplotlib import colormaps
list(colormaps)
```

More information about Choosing Colormaps in Matplotlib is available [here](https://matplotlib.org/stable/users/explain/colors/colormaps.html).




## References:
### 1. MATLAB confusion matrix:

a) [Plot Confusion](https://www.mathworks.com/help/nnet/ref/plotconfusion.html)
   
b) [Plot Confusion Matrix Using Categorical Labels](https://www.mathworks.com/help/examples/nnet/win64/PlotConfusionMatrixUsingCategoricalLabelsExample_02.png)



### 2. Examples and more on Python:

  a) [How to plot confusion matrix with string axis rather than integer in python](https://stackoverflow.com/questions/5821125/how-to-plot-confusion-matrix-with-string-axis-rather-than-integer-in-python/51176855#51176855)
  
  b) [Plot-scikit-learn-classification-report](https://stackoverflow.com/questions/28200786/how-to-plot-scikit-learn-classification-report)
  
  c) [Plot-confusion-matrix-with-string-axis-rather-than-integer-in-Python](https://stackoverflow.com/questions/5821125/how-to-plot-confusion-matrix-with-string-axis-rather-than-integer-in-python)
  
  d) [Seaborn heatmap](https://www.programcreek.com/python/example/96197/seaborn.heatmap)
  
  e) [Sklearn-plot-confusion-matrix-with-labels](https://stackoverflow.com/questions/19233771/sklearn-plot-confusion-matrix-with-labels/31720054)

  f) [Model-selection-plot-confusion-matrix](http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py)



================================================
FILE: examples/arrays_example.py
================================================
import numpy as np

from pretty_confusion_matrix import pp_matrix_from_data

y_test = np.array([1, 2, 3, 4, 5])
predic = np.array([3, 2, 4, 3, 5])

cmap = "PuRd"
path_to_save_img = './matrix-output-from-array.png'
title = 'Confusion matrix from array'
pp_matrix_from_data(y_test, predic, cmap=cmap, path_to_save_img=path_to_save_img, title=title)


================================================
FILE: examples/df_example.py
================================================
import numpy as np
import pandas as pd

from pretty_confusion_matrix import pp_matrix

array = np.array(
    [
        [13, 0, 1, 0, 2, 0],
        [0, 50, 2, 0, 10, 0],
        [0, 13, 16, 0, 0, 3],
        [0, 0, 0, 13, 1, 0],
        [0, 40, 0, 1, 15, 0],
        [0, 0, 0, 0, 0, 20],
    ]
)

# get pandas dataframe
df_cm = pd.DataFrame(array, index=range(1, 7), columns=range(1, 7))
# colormap: see this and choose your more dear
cmap = "PuRd"
title = 'Confusion matrix from dataframe'
pp_matrix(df_cm, cmap=cmap, title=title)


================================================
FILE: examples/docs.py
================================================
import pretty_confusion_matrix

print('VERSION: ', pretty_confusion_matrix.__version__)


================================================
FILE: pretty_confusion_matrix/__init__.py
================================================
import importlib.metadata
__version__ = importlib.metadata.version("pretty_confusion_matrix")

from .pretty_confusion_matrix import pp_matrix, pp_matrix_from_data


================================================
FILE: pretty_confusion_matrix/pretty_confusion_matrix.py
================================================
# -*- coding: utf-8 -*-
"""
plot a pretty confusion matrix with seaborn
Created on Mon Jun 25 14:17:37 2018
@author: Wagner Cipriano - wagnerbhbr - gmail - CEFETMG / MMC
REFerences:
  https://www.mathworks.com/help/nnet/ref/plotconfusion.html
  https://stackoverflow.com/questions/28200786/how-to-plot-scikit-learn-classification-report
  https://stackoverflow.com/questions/5821125/how-to-plot-confusion-matrix-with-string-axis-rather-than-integer-in-python
  https://www.programcreek.com/python/example/96197/seaborn.heatmap
  https://stackoverflow.com/questions/19233771/sklearn-plot-confusion-matrix-with-labels/31720054
  http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py
"""

import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sn
from matplotlib.collections import QuadMesh


def get_new_fig(fn, figsize=[9, 9]):
    """Init graphics"""
    fig1 = plt.figure(fn, figsize)
    ax1 = fig1.gca()  # Get Current Axis
    ax1.cla()  # clear existing plot
    return fig1, ax1


def configcell_text_and_colors(
    array_df, lin, col, oText, facecolors, posi, fz, fmt, show_null_values=0
):
    """
    config cell text and colors
    and return text elements to add and to dell
    @TODO: use fmt
    """
    text_add = []
    text_del = []
    cell_val = array_df[lin][col]
    tot_all = array_df[-1][-1]
    per = (float(cell_val) / tot_all) * 100
    curr_column = array_df[:, col]
    ccl = len(curr_column)

    # last line  and/or last column
    if (col == (ccl - 1)) or (lin == (ccl - 1)):
        # tots and percents
        if cell_val != 0:
            if (col == ccl - 1) and (lin == ccl - 1):
                tot_rig = 0
                for i in range(array_df.shape[0] - 1):
                    tot_rig += array_df[i][i]
                per_ok = (float(tot_rig) / cell_val) * 100
            elif col == ccl - 1:
                tot_rig = array_df[lin][lin]
                per_ok = (float(tot_rig) / cell_val) * 100
            elif lin == ccl - 1:
                tot_rig = array_df[col][col]
                per_ok = (float(tot_rig) / cell_val) * 100
            per_err = 100 - per_ok
        else:
            per_ok = per_err = 0

        per_ok_s = ["%.2f%%" % (per_ok), "100%"][per_ok == 100]

        # text to DEL
        text_del.append(oText)

        # text to ADD
        font_prop = fm.FontProperties(weight="bold", size=fz)
        text_kwargs = dict(
            color="w",
            ha="center",
            va="center",
            gid="sum",
            fontproperties=font_prop,
        )
        lis_txt = ["%d" % (cell_val), per_ok_s, "%.2f%%" % (per_err)]
        lis_kwa = [text_kwargs]
        dic = text_kwargs.copy()
        dic["color"] = "g"
        lis_kwa.append(dic)
        dic = text_kwargs.copy()
        dic["color"] = "r"
        lis_kwa.append(dic)
        lis_pos = [
            (oText._x, oText._y - 0.3),
            (oText._x, oText._y),
            (oText._x, oText._y + 0.3),
        ]
        for i in range(len(lis_txt)):
            newText = dict(
                x=lis_pos[i][0],
                y=lis_pos[i][1],
                text=lis_txt[i],
                kw=lis_kwa[i],
            )
            text_add.append(newText)

        # set background color for sum cells (last line and last column)
        carr = [0.27, 0.30, 0.27, 1.0]
        if (col == ccl - 1) and (lin == ccl - 1):
            carr = [0.17, 0.20, 0.17, 1.0]
        facecolors[posi] = carr

    else:
        if per > 0:
            txt = "%s\n%.2f%%" % (cell_val, per)
        else:
            if show_null_values == 0:
                txt = ""
            elif show_null_values == 1:
                txt = "0"
            else:
                txt = "0\n0.0%"
        oText.set_text(txt)

        # main diagonal
        if col == lin:
            # set color of the textin the diagonal to white
            oText.set_color("w")
            # set background color in the diagonal to blue
            facecolors[posi] = [0.35, 0.8, 0.55, 1.0]
        else:
            oText.set_color("r")

    return text_add, text_del


def insert_totals(df_cm):
    """insert total column and line (the last ones)"""
    sum_col = []
    for c in df_cm.columns:
        sum_col.append(df_cm[c].sum())
    sum_lin = []
    for item_line in df_cm.iterrows():
        sum_lin.append(item_line[1].sum())
    df_cm["sum_lin"] = sum_lin
    sum_col.append(np.sum(sum_lin))
    df_cm.loc["sum_col"] = sum_col


def pp_matrix(
    df_cm,
    annot=True,
    cmap="Oranges",
    fmt=".2f",
    fz=11,
    lw=0.5,
    cbar=False,
    figsize=[8, 8],
    show_null_values=0,
    pred_val_axis="y",
    path_to_save_img="",
    title="Confusion matrix",
):
    """
    print conf matrix with default layout (like matlab)
    params:
      df_cm          dataframe (pandas) without totals
      annot          print text in each cell
      cmap           Oranges,Oranges_r,YlGnBu,Blues,RdBu, ... see:
      fz             fontsize
      lw             linewidth
      pred_val_axis  where to show the prediction values (x or y axis)
                      'col' or 'x': show predicted values in columns (x axis) instead lines
                      'lin' or 'y': show predicted values in lines   (y axis)
    """
    if pred_val_axis in ("col", "x"):
        xlbl = "Predicted"
        ylbl = "Actual"
    else:
        xlbl = "Actual"
        ylbl = "Predicted"
        df_cm = df_cm.T

    # create "Total" column
    insert_totals(df_cm)

    # this is for print allways in the same window
    fig, ax1 = get_new_fig("Conf matrix default", figsize)

    ax = sn.heatmap(
        df_cm,
        annot=annot,
        annot_kws={"size": fz},
        linewidths=lw,
        ax=ax1,
        cbar=cbar,
        cmap=cmap,
        linecolor="w",
        fmt=fmt,
    )

    # set ticklabels rotation
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, fontsize=10)
    ax.set_yticklabels(ax.get_yticklabels(), rotation=25, fontsize=10)

    # Turn off all the ticks
    for (tx, ty) in zip(ax.xaxis.get_major_ticks(), ax.yaxis.get_major_ticks()):
        tx.tick1line.set_visible(False)
        tx.tick2line.set_visible(False)
        ty.tick1line.set_visible(False)
        ty.tick2line.set_visible(False)

    # face colors list
    quadmesh = ax.findobj(QuadMesh)[0]
    facecolors = quadmesh.get_facecolors()

    # iter in text elements
    array_df = np.array(df_cm.to_records(index=False).tolist())
    text_add = []
    text_del = []
    posi = -1  # from left to right, bottom to top.
    for t in ax.collections[0].axes.texts:  # ax.texts:
        pos = np.array(t.get_position()) - [0.5, 0.5]
        lin = int(pos[1])
        col = int(pos[0])
        posi += 1

        # set text
        txt_res = configcell_text_and_colors(
            array_df, lin, col, t, facecolors, posi, fz, fmt, show_null_values
        )

        text_add.extend(txt_res[0])
        text_del.extend(txt_res[1])

    # remove the old ones
    for item in text_del:
        item.remove()
    # append the new ones
    for item in text_add:
        ax.text(item["x"], item["y"], item["text"], **item["kw"])

    # titles and legends
    ax.set_title(title)
    ax.set_xlabel(xlbl)
    ax.set_ylabel(ylbl)
    plt.tight_layout()  # set layout slim

    # save or show the img result
    if not path_to_save_img:
        plt.show()
    else:
        plt.savefig(path_to_save_img)


def pp_matrix_from_data(
    y_test,
    predictions,
    columns=None,
    annot=True,
    cmap="Oranges",
    fmt=".2f",
    fz=11,
    lw=0.5,
    cbar=False,
    figsize=[8, 8],
    show_null_values=0,
    pred_val_axis="lin",
    path_to_save_img="",
    title="Confusion matrix",
):
    """
    plot confusion matrix function with y_test (actual values) and predictions (predic),
    whitout a confusion matrix yet
    """
    from pandas import DataFrame
    from sklearn.metrics import confusion_matrix

    # data
    if not columns:
        from string import ascii_uppercase

        columns = [
            "class %s" % (i)
            for i in list(ascii_uppercase)[0 : len(np.unique(y_test))]
        ]

    confm = confusion_matrix(y_test, predictions)
    df_cm = DataFrame(confm, index=columns, columns=columns)
    pp_matrix(
        df_cm,
        fz=fz,
        cmap=cmap,
        figsize=figsize,
        show_null_values=show_null_values,
        pred_val_axis=pred_val_axis,
        path_to_save_img=path_to_save_img,
        title=title,
        annot=annot,
        fmt=fmt,
        lw=lw,
        cbar=cbar
    )


================================================
FILE: pyproject.toml
================================================
[tool.poetry]
name = "pretty-confusion-matrix"
version = "0.6.0"
description = "plot a pretty confusion matrix (like Matlab) in python using seaborn and matplotlib"
repository = "https://github.com/wcipriano/pretty-print-confusion-matrix"
authors = ["Wagner Cipriano <wagnao@gmail.com>", "Khuyen Tran <khuyentran1476@gmail.com>"]
keywords = ["confusion matrix"]
readme = "README.md"

[project.urls]
homepage = "https://pypi.org/project/pretty-confusion-matrix"
source = "https://github.com/wcipriano/pretty-print-confusion-matrix"
download = "https://pypi.org/project/pretty-confusion-matrix/#files"
tracker = "https://github.com/wcipriano/pretty-print-confusion-matrix/issues"

[tool.poetry.dependencies]
python = ">=3.9,<3.12"
numpy = [
    {version = "^2.0.0", python = ">=3.9"},
]
matplotlib = [
    {version = "^3.9.0", python = ">=3.9"},
]
seaborn = "^0.13.2"
pandas = [
    {version = "^2.2.2", python = ">=3.9"},
]
scikit-learn = [
    {version = "^1.5", python = ">=3.9"},
]

[tool.poetry.dev-dependencies]
pre-commit = "^3.5.0"
black = "^24.4.2"
flake8 = "^5.0.4"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
	\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build   
)/ 
'''
Download .txt
gitextract_mfctpddf/

├── .flake8
├── .github/
│   └── FUNDING.yml
├── .gitignore
├── .pre-commit-config.yaml
├── LICENSE
├── README.md
├── examples/
│   ├── arrays_example.py
│   ├── df_example.py
│   └── docs.py
├── pretty_confusion_matrix/
│   ├── __init__.py
│   └── pretty_confusion_matrix.py
└── pyproject.toml
Download .txt
SYMBOL INDEX (5 symbols across 1 files)

FILE: pretty_confusion_matrix/pretty_confusion_matrix.py
  function get_new_fig (line 22) | def get_new_fig(fn, figsize=[9, 9]):
  function configcell_text_and_colors (line 30) | def configcell_text_and_colors(
  function insert_totals (line 131) | def insert_totals(df_cm):
  function pp_matrix (line 144) | def pp_matrix(
  function pp_matrix_from_data (line 250) | def pp_matrix_from_data(
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (32K chars).
[
  {
    "path": ".flake8",
    "chars": 118,
    "preview": "[flake8]\nignore = E203, E266, E501, W503, F403, F401\nmax-line-length = 79\nmax-complexity = 18\nselect = B,C,E,F,W,T4,B9"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 92,
    "preview": "# These are supported funding model platforms\n\ngithub: wcipriano\nbuy_me_a_coffee: wcipriano\n"
  },
  {
    "path": ".gitignore",
    "chars": 61,
    "preview": "__pycache__\ndist\n.venv/\n.idea\nbkp/*\n*-local-*\nmatrix-output-*"
  },
  {
    "path": ".pre-commit-config.yaml",
    "chars": 262,
    "preview": "repos:\n-   repo: https://github.com/ambv/black\n    rev: 20.8b1\n    hooks:\n    - id: black\n-   repo: https://gitlab.com/p"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 7253,
    "preview": "![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pretty-confusion-matrix?logo=python&logoColor=%23FFFFFF)"
  },
  {
    "path": "examples/arrays_example.py",
    "chars": 347,
    "preview": "import numpy as np\n\nfrom pretty_confusion_matrix import pp_matrix_from_data\n\ny_test = np.array([1, 2, 3, 4, 5])\npredic ="
  },
  {
    "path": "examples/df_example.py",
    "chars": 532,
    "preview": "import numpy as np\nimport pandas as pd\n\nfrom pretty_confusion_matrix import pp_matrix\n\narray = np.array(\n    [\n        ["
  },
  {
    "path": "examples/docs.py",
    "chars": 88,
    "preview": "import pretty_confusion_matrix\n\nprint('VERSION: ', pretty_confusion_matrix.__version__)\n"
  },
  {
    "path": "pretty_confusion_matrix/__init__.py",
    "chars": 163,
    "preview": "import importlib.metadata\n__version__ = importlib.metadata.version(\"pretty_confusion_matrix\")\n\nfrom .pretty_confusion_ma"
  },
  {
    "path": "pretty_confusion_matrix/pretty_confusion_matrix.py",
    "chars": 8684,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\nplot a pretty confusion matrix with seaborn\nCreated on Mon Jun 25 14:17:37 2018\n@author: Wag"
  },
  {
    "path": "pyproject.toml",
    "chars": 1311,
    "preview": "[tool.poetry]\nname = \"pretty-confusion-matrix\"\nversion = \"0.6.0\"\ndescription = \"plot a pretty confusion matrix (like Mat"
  }
]

About this extraction

This page contains the full source code of the wcipriano/pretty-print-confusion-matrix GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (29.6 KB), approximately 8.5k tokens, and a symbol index with 5 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!