Function Title: Create Confusion Matrix def create_confusion_matrix(actual, predicted, classes): matrix = [[0 for _ in range(len(classes))] for _ in range(len(classes))] for i in range(len(actual)): actual_index = classes.index(actual[i]) predicted_index = classes.index(predicted[i]) matrix[actual_index][predicted_index] += 1 return matrix

Posted by

Understanding Confusion Matrix Function in Python

Confusion Matrix Function in Python

In machine learning, a confusion matrix is a table that is often used to describe the performance of a classification model. It allows visualization of the performance of an algorithm by comparing actual and predicted values. In Python, the confusion matrix function is a powerful tool that helps in evaluating the performance of machine learning models.

To create a confusion matrix in Python, you can use the confusion_matrix function from the scikit-learn library. This function takes in two arrays – the actual values and the predicted values – and returns a 2D array that shows the counts of true positive, false positive, true negative, and false negative values.

Here is an example of how you can use the confusion matrix function in Python:


from sklearn.metrics import confusion_matrix

actual = [1, 0, 1, 0, 1, 1]
predicted = [1, 1, 1, 0, 1, 1]

cm = confusion_matrix(actual, predicted)
print(cm)

The output of this code will be a 2D array that looks like this:

2 1
1 2

From this confusion matrix, you can determine the performance of your machine learning model based on the calculations of the true positive, false positive, true negative, and false negative values. This information can help you make improvements to your model and optimize its performance.

Overall, the confusion matrix function in Python is a valuable tool for evaluating the performance of machine learning models and making informed decisions based on the results it provides.