Hướng dẫn how do you plot confusion matrix with labels in python? - làm thế nào để bạn vẽ ma trận nhầm lẫn với các nhãn trong python?

from sklearn import model_selection
test_size = 0.33
seed = 7
X_train, X_test, y_train, y_test = model_selection.train_test_split(feature_vectors, y, test_size=test_size, random_state=seed)

from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

model = LogisticRegression()
model.fit(X_train, y_train)
result = model.score(X_test, y_test)
print("Accuracy: %.3f%%" % (result*100.0))
y_pred = model.predict(X_test)
print("F1 Score: ", f1_score(y_test, y_pred, average="macro"))
print("Precision Score: ", precision_score(y_test, y_pred, average="macro"))
print("Recall Score: ", recall_score(y_test, y_pred, average="macro")) 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix

def cm_analysis(y_true, y_pred, labels, ymap=None, figsize=(10,10)):
    """
    Generate matrix plot of confusion matrix with pretty annotations.
    The plot image is saved to disk.
    args: 
      y_true:    true label of the data, with shape (nsamples,)
      y_pred:    prediction of the data, with shape (nsamples,)
      filename:  filename of figure file to save
      labels:    string array, name the order of class labels in the confusion matrix.
                 use `clf.classes_` if using scikit-learn models.
                 with shape (nclass,).
      ymap:      dict: any -> string, length == nclass.
                 if not None, map the labels & ys to more understandable strings.
                 Caution: original y_true, y_pred and labels must align.
      figsize:   the size of the figure plotted.
    """
    if ymap is not None:
        # change category codes or labels to new labels 
        y_pred = [ymap[yi] for yi in y_pred]
        y_true = [ymap[yi] for yi in y_true]
        labels = [ymap[yi] for yi in labels]
    # calculate a confusion matrix with the new labels
    cm = confusion_matrix(y_true, y_pred, labels=labels)
    # calculate row sums (for calculating % & plot annotations)
    cm_sum = np.sum(cm, axis=1, keepdims=True)
    # calculate proportions
    cm_perc = cm / cm_sum.astype(float) * 100
    # empty array for holding annotations for each cell in the heatmap
    annot = np.empty_like(cm).astype(str)
    # get the dimensions
    nrows, ncols = cm.shape
    # cycle over cells and create annotations for each cell
    for i in range(nrows):
        for j in range(ncols):
            # get the count for the cell
            c = cm[i, j]
            # get the percentage for the cell
            p = cm_perc[i, j]
            if i == j:
                s = cm_sum[i]
                # convert the proportion, count, and row sum to a string with pretty formatting
                annot[i, j] = '%.1f%%\n%d/%d' % (p, c, s)
            elif c == 0:
                annot[i, j] = ''
            else:
                annot[i, j] = '%.1f%%\n%d' % (p, c)
    # convert the array to a dataframe. To plot by proportion instead of number, use cm_perc in the DataFrame instead of cm
    cm = pd.DataFrame(cm, index=labels, columns=labels)
    cm.index.name = 'Actual'
    cm.columns.name = 'Predicted'
    # create empty figure with a specified size
    fig, ax = plt.subplots(figsize=figsize)
    # plot the data using the Pandas dataframe. To change the color map, add cmap=..., e.g. cmap = 'rocket_r'
    sns.heatmap(cm, annot=annot, fmt='', ax=ax)
    #plt.savefig(filename)
    plt.show()

cm_analysis(y_test, y_pred, model.classes_, ymap=None, figsize=(10,10))

Hướng dẫn how do you plot confusion matrix with labels in python? - làm thế nào để bạn vẽ ma trận nhầm lẫn với các nhãn trong python?

Sử dụng https://gist.github.com/hitvoice/36CF44689065CA9B927431546381A3F7

Lưu ý rằng nếu bạn sử dụng rocket_r, nó sẽ đảo ngược màu sắc và bằng cách nào đó, nó trông tự nhiên hơn và tốt hơn như dưới đây:

Hướng dẫn how do you plot confusion matrix with labels in python? - làm thế nào để bạn vẽ ma trận nhầm lẫn với các nhãn trong python?

sklearn.metrics.plot_confusion_matrix (công cụ ước tính, x, y_true, *, nhãn = none, sample_weight = none ax = none, colorbar = true) [nguồn] ¶plot_confusion_matrix(estimator, X, y_true, *, labels=None, sample_weight=None, normalize=None, display_labels=None, include_values=True, xticks_rotation='horizontal', values_format=None, cmap='viridis', ax=None, colorbar=True)[source]

Không dùng nữa: Hàm plot_confusion_matrix không được dùng để loại bỏ trong 1.0 và sẽ bị xóa trong 1.2. Sử dụng một trong các phương thức lớp: nhầm lẫnMatrixDisplay.From_Predictions hoặc InfusionMatrixDisplay.From_estimator.

Âm mưu ma trận nhầm lẫn.

plot_confusion_matrix không được dùng trong 1.0 và sẽ bị loại bỏ trong 1.2. Sử dụng một trong các phương thức lớp sau: from_predictions hoặc from_estimator.

Đọc thêm trong Hướng dẫn sử dụng.User Guide.

Tham số: Phiên bản của EDOPATORESTimator:estimatorestimator instance

Phân loại được trang bị hoặc được trang bị Pipeline trong đó công cụ ước tính cuối cùng là một trình phân loại.

X {giống như mảng, ma trận thưa thớt} của hình dạng (n_samples, n_features){array-like, sparse matrix} of shape (n_samples, n_features)

Giá trị đầu vào.

Y_TrueArray giống như hình dạng (n_samples,)array-like of shape (n_samples,)

Giá trị mục tiêu.

LabelsArray giống như hình dạng (n_ classes,), mặc định = không cóarray-like of shape (n_classes,), default=None

Danh sách các nhãn để lập chỉ mục ma trận. Điều này có thể được sử dụng để sắp xếp lại hoặc chọn một tập hợp con của nhãn. Nếu None được đưa ra, những người xuất hiện ít nhất một lần trong y_true hoặc

>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.metrics import plot_confusion_matrix
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.svm import SVC
>>> X, y = make_classification(random_state=0)
>>> X_train, X_test, y_train, y_test = train_test_split(
...         X, y, random_state=0)
>>> clf = SVC(random_state=0)
>>> clf.fit(X_train, y_train)
SVC(random_state=0)
>>> plot_confusion_matrix(clf, X_test, y_test)  
>>> plt.show()
0 được sử dụng theo thứ tự được sắp xếp.

sample_weightarray giống như hình dạng (n_samples,), mặc định = không cóarray-like of shape (n_samples,), default=None

Trọng lượng mẫu.

Bình thường hóa {’true{‘true’, ‘pred’, ‘all’}, default=None

Để bình thường hóa hiển thị số đếm trong ma trận:

  • Nếu

    >>> import matplotlib.pyplot as plt
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.metrics import plot_confusion_matrix
    >>> from sklearn.model_selection import train_test_split
    >>> from sklearn.svm import SVC
    >>> X, y = make_classification(random_state=0)
    >>> X_train, X_test, y_train, y_test = train_test_split(
    ...         X, y, random_state=0)
    >>> clf = SVC(random_state=0)
    >>> clf.fit(X_train, y_train)
    SVC(random_state=0)
    >>> plot_confusion_matrix(clf, X_test, y_test)  
    >>> plt.show()
    
    1, ma trận nhầm lẫn được chuẩn hóa trong các điều kiện thực (ví dụ: các hàng);

  • Nếu

    >>> import matplotlib.pyplot as plt
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.metrics import plot_confusion_matrix
    >>> from sklearn.model_selection import train_test_split
    >>> from sklearn.svm import SVC
    >>> X, y = make_classification(random_state=0)
    >>> X_train, X_test, y_train, y_test = train_test_split(
    ...         X, y, random_state=0)
    >>> clf = SVC(random_state=0)
    >>> clf.fit(X_train, y_train)
    SVC(random_state=0)
    >>> plot_confusion_matrix(clf, X_test, y_test)  
    >>> plt.show()
    
    2, ma trận nhầm lẫn được chuẩn hóa trong các điều kiện dự đoán (ví dụ: cột);

  • Nếu

    >>> import matplotlib.pyplot as plt
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.metrics import plot_confusion_matrix
    >>> from sklearn.model_selection import train_test_split
    >>> from sklearn.svm import SVC
    >>> X, y = make_classification(random_state=0)
    >>> X_train, X_test, y_train, y_test = train_test_split(
    ...         X, y, random_state=0)
    >>> clf = SVC(random_state=0)
    >>> clf.fit(X_train, y_train)
    SVC(random_state=0)
    >>> plot_confusion_matrix(clf, X_test, y_test)  
    >>> plt.show()
    
    3, ma trận nhầm lẫn được chuẩn hóa bởi tổng số mẫu;

  • Nếu None (mặc định), ma trận nhầm lẫn sẽ không được chuẩn hóa.

display_labelsarray giống như hình dạng (n_ classes,), mặc định = khôngarray-like of shape (n_classes,), default=None

Tên mục tiêu được sử dụng để vẽ đồ thị. Theo mặc định,

>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.metrics import plot_confusion_matrix
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.svm import SVC
>>> X, y = make_classification(random_state=0)
>>> X_train, X_test, y_train, y_test = train_test_split(
...         X, y, random_state=0)
>>> clf = SVC(random_state=0)
>>> clf.fit(X_train, y_train)
SVC(random_state=0)
>>> plot_confusion_matrix(clf, X_test, y_test)  
>>> plt.show()
5 sẽ được sử dụng nếu được xác định, nếu không các nhãn duy nhất của y_true
>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.metrics import plot_confusion_matrix
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.svm import SVC
>>> X, y = make_classification(random_state=0)
>>> X_train, X_test, y_train, y_test = train_test_split(
...         X, y, random_state=0)
>>> clf = SVC(random_state=0)
>>> clf.fit(X_train, y_train)
SVC(random_state=0)
>>> plot_confusion_matrix(clf, X_test, y_test)  
>>> plt.show()
0 sẽ được sử dụng.

bao gồm_valuesbool, mặc định = truebool, default=True

Bao gồm các giá trị trong ma trận nhầm lẫn.

Xticks_rotation {‘dọc,‘ ngang} hoặc float, mặc định ={‘vertical’, ‘horizontal’} or float, default=’horizontal’

Xoay của nhãn XTICK.

value_formatstr, mặc định = khôngstr, default=None

Định dạng đặc tả cho các giá trị trong ma trận nhầm lẫn. Nếu None, đặc tả định dạng là ‘D, hoặc‘ .2g, tùy theo thời gian ngắn hơn.

CMAPSTR hoặc matplotlib colormap, mặc định = xông Viridis,str or matplotlib Colormap, default=’viridis’

Colormap được công nhận bởi matplotlib.

AXMATPLOTLIB AXES, DEFAULT = Không cómatplotlib Axes, default=None

Trục đối tượng để vẽ trên. Nếu None, một hình và trục mới được tạo ra.

colorbarbool, mặc định = truebool, default=True

Có hay không thêm một colorbar vào cốt truyện.

Mới trong phiên bản 0.24.

Returns:displayrocket_r0:displayrocket_r0

Đối tượng lưu trữ các giá trị tính toán.

Ví dụ

>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.metrics import plot_confusion_matrix
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.svm import SVC
>>> X, y = make_classification(random_state=0)
>>> X_train, X_test, y_train, y_test = train_test_split(
...         X, y, random_state=0)
>>> clf = SVC(random_state=0)
>>> clf.fit(X_train, y_train)
SVC(random_state=0)
>>> plot_confusion_matrix(clf, X_test, y_test)  
>>> plt.show()

Hướng dẫn how do you plot confusion matrix with labels in python? - làm thế nào để bạn vẽ ma trận nhầm lẫn với các nhãn trong python?

Làm thế nào để bạn vẽ nhãn cho ma trận nhầm lẫn?

Tóm tắt: Cách tốt nhất để vẽ một ma trận nhầm lẫn với các nhãn, là sử dụng đối tượng InfusionMatrixDisplay từ mô -đun sklearn.metrics. Một cách đơn giản và thanh lịch khác là sử dụng Seaborn. hàm nhiệt ().use the ConfusionMatrixDisplay object from the sklearn. metrics module. Another simple and elegant way is to use the seaborn. heatmap() function.

Làm cách nào để tìm nhãn cho ma trận nhầm lẫn trong Python?

@Revolucionformonica Khi bạn nhận được sự bối rối_matrix, các nhãn đánh dấu trục X là nhãn 1, 0 và y trục là 0, 1 (theo giá trị trục tăng).Nếu trình phân loại là CLF, bạn có thể nhận được thứ tự lớp bằng CLF.the X axis tick labels are 1, 0 and Y axis tick labels are 0, 1 (in the axis values increasing order). If the classifier is clf , you can get the class order by clf.

Làm thế nào để bạn vẽ một ma trận nhầm lẫn cho một mô hình trong Python?

Ma trận nhầm lẫn sơ đồ cho các lớp nhị phân với nhãn bạn cần tạo danh sách các nhãn và chuyển đổi nó thành một mảng bằng NP.Phương pháp Asarray () có hình 2,2.Sau đó, mảng nhãn này phải được chuyển đến Annot thuộc tính.Điều này sẽ vạch ra ma trận nhầm lẫn với chú thích nhãn.create a list of the labels and convert it into an array using the np. asarray() method with shape 2,2 . Then, this array of labels must be passed to the attribute annot . This will plot the confusion matrix with the labels annotation.

Làm thế nào để bạn vẽ một ma trận nhầm lẫn trong Python bằng cách sử dụng Seaborn?

Hiển thị ma trận nhầm lẫn bằng cách sử dụng Seaborn để hoàn thành nhiệm vụ này, bạn sẽ cần thêm hai thành phần sau vào mã: Nhập Seaborn dưới dạng SN.Sn.HeatMap (Confusion_Matrix, Annot = true)import seaborn as sn. sn. heatmap(confusion_matrix, annot=True)