Last active
June 28, 2024 14:23
-
-
Save FRodrigues21/837f4e62bb2ae2b4d2b1085e91e7825a to your computer and use it in GitHub Desktop.
Array Confusion Matrix to LaTeX Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def gen_align(align, size): | |
texto = "" | |
for i in range(0,size): | |
texto += align | |
return texto | |
def gen_header(size): | |
header = " " | |
for i in range(0, size): | |
header += "& " + str(i) + " " | |
header += "\\\ \\midrule\n" | |
return header | |
def cm_to_latex(array, align="l"): | |
n_cols = len(array[0]) | |
table = "\\begin{table}\n" | |
table += "\caption{Table of Confusion Matrix generated with python}\n" | |
table += "\label{cm:python:generated}\n" | |
table += "\small\n" | |
table += "\\centering\n" | |
table += "\\begin{tabular}{@{}"+ gen_align(align, n_cols+1) + "@{}}\n" | |
table += "\\toprule\n" | |
table += gen_header(n_cols) | |
for i, linha in enumerate(array): | |
table += str(i) + " " | |
for val in linha: | |
table += "& " + str(val) + " " | |
if i+1 == n_cols: | |
table += "\\\ \\bottomrule \n" | |
else: | |
table += "\\\ \n" | |
table += "\end{tabular}\n" | |
table += "\end{table}" | |
print(table) | |
# Test | |
array = [[3682, 7, 127, 107, 277, 3, 3, 5], | |
[ 108, 9, 14, 6, 20, 0, 0, 0], | |
[ 70, 1, 162, 3, 14, 0, 0, 0], | |
[ 63, 2, 5, 112, 15, 0, 3, 3], | |
[ 73, 0, 11, 6, 354, 0, 0, 8], | |
[ 0, 0, 0, 0, 0, 5, 0, 0], | |
[ 1, 0, 0, 3, 2, 0, 8, 0], | |
[ 22, 0, 2, 0, 15, 0, 0, 30]] | |
cm_to_latex(array) | |
# Result | |
""" | |
\begin{table} | |
\caption{Table of Confusion Matrix generated with python} | |
\label{cm:python:generated} | |
\small | |
\centering | |
\begin{tabular}{@{}lllllllll@{}} | |
\toprule | |
& 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ \midrule | |
0 & 3682 & 7 & 127 & 107 & 277 & 3 & 3 & 5 \\ | |
1 & 108 & 9 & 14 & 6 & 20 & 0 & 0 & 0 \\ | |
2 & 70 & 1 & 162 & 3 & 14 & 0 & 0 & 0 \\ | |
3 & 63 & 2 & 5 & 112 & 15 & 0 & 3 & 3 \\ | |
4 & 73 & 0 & 11 & 6 & 354 & 0 & 0 & 8 \\ | |
5 & 0 & 0 & 0 & 0 & 0 & 5 & 0 & 0 \\ | |
6 & 1 & 0 & 0 & 3 & 2 & 0 & 8 & 0 \\ | |
7 & 22 & 0 & 2 & 0 & 15 & 0 & 0 & 30 \\ \bottomrule | |
\end{tabular} | |
\end{table} | |
""" |
Author
FRodrigues21
commented
Sep 9, 2019
Thank you for this. Appreciate it.
Thanks a lot, it is greatly appreciated!
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment