-1

In order to get a Decision tree with sickit learn, I need to Labelencode a dataframe.

    S02Q01_Gender  S02Q02_Age_rec   S02Q03A_Region  S02Q03B_Settlement_type     S02Q03C_Province    S02Q10A_Employment  S02Q11_Professional_field   Segment Cluster
0   Female         12-19            Marrakesh       Urban                       Casablanca-Settat   Student             None                        Class1
1   Male           65 or above      Marakesh        Rural                       El Jadida           My Employed, part-time  Property                Class2
...

However, in order to plot it properly on a confusion matrix I need to save the labels of the target column.

I tried:

y_test_dencoded = label_encoder.inverse_transform(y_test)
y_pred_dencoded = label_encoder.inverse_transform(y_pred)

cnf_matrix = metrics.confusion_matrix(y_test_dencoded, y_pred_dencoded, labels=None, sample_weight=None)

And plotting it:

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt

df_cm = pd.DataFrame(cnf_matrix, index = [i for i in set(y_test_dencoded)],
                  columns = [i for i in set(y_pred_dencoded)])
plt.figure(figsize = (10,7))
ax = sn.heatmap(df_cm, annot=True)
bottom, top = ax.get_ylim()
ax.set_ylim(bottom + 0.5, top - 0.5)

It returns a confusion matrix but I don't know if I am labbeling it well ...

Revolucion for Monica
  • 2,848
  • 8
  • 39
  • 78

1 Answers1

0

If your classifier is clf, you can use clf.classes_ to identify the numbers assigned to labels by the model.

For example, if clf.classes_ is ["class1", "class3", "class2"] (assuming you have only three classes), that means the following mapping holds between predcted labels and actual labels: {0: "class1", 1:"class3", 2: "class2"}

In this case, in the sklearn confusion matrix output, the X axis tick labels are 2, 1, 0 and Y axis tick labels are 0, 1, 2 (in the axis values increasing order). You can map these back to labels using the above dictionary.

akilat90
  • 5,436
  • 7
  • 28
  • 42