Welcome to the world of Machine Learning !

Confusion-Matrix Python Code Implementation

In this code we have used iris dataset of sklearn library. You can copy the code and execute it in juypter or PyCharm.

import pandas as pd
from sklearn.datasets import load_iris
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import seaborn as sns # Load the iris dataset into a pandas DataFrame
iris = load_iris()
data = pd.DataFrame(iris.data, columns=iris.feature_names)
data['target'] = iris.target
# Split the data into independent (X) and dependent (y) variables
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Create the K-nearest neighbors classifier
classifier = KNeighborsClassifier(n_neighbors=5)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
# Create the confusion matrix
cm = confusion_matrix(y_test, y_pred)
print('Confusion Matrix:')
print(cm)
sns.heatmap(cm, annot=True, cmap='Reds', fmt='g')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.title('Confusion matrix')
plt.show()

The output of the above code:

Confusion Matrix:
[[11 0 0]
[ 0 12 1]
[ 0 0 6]]

Heat Map

Image heat map

Advertisement

Advertisement