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]]
Sử dụng //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:
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 instancePhâ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.
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=NoneDanh 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:
display_labelsarray giống như hình dạng [n_ classes,], mặc định = khôngarray-like of shape [n_classes,], default=None
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.
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
và >>> 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.
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.
Colormap được công nhận bởi matplotlib.
AXMATPLOTLIB AXES, DEFAULT = Không cómatplotlib Axes, default=NoneTrục đối tượng để vẽ trên. Nếu None
, một hình và trục mới được tạo ra.
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_r
0:displayrocket_r
0Đố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[]