def plot_confusion_matrix(confusion_matrix, classes, title, normalize=False): plt.clf() plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Blues) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: confusion_matrix = confusion_matrix.astype( 'float') / confusion_matrix.sum(axis=1)[:, np.newaxis] thresh = confusion_matrix.max() / 2. for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])): plt.text(j, i, round(confusion_matrix[i, j], 3), horizontalalignment="center", color="white" if confusion_matrix[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('Реальные классы') plt.xlabel('Расчетные классы')
def plot_cnf_matrix(self, cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ import itertools if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') plt.imshow(cm, interpolation='nearest', cmap=cmap) tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.show()
def plot_confusion_matrix(cm, classes, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout()
def plot_confusion_matrix(confusion_matrix, y_class, plot_title, plot_y_label, plot_x_label, normalize=False): """ plot the confusion matrix. :param confusion_matrix: confusion matrix value :param y_class: target unique class name :param plot_title: plot title :param plot_y_label: plot y label :param plot_x_label: plot x label :param normalize: default to false :return: None """ try: plt.figure() plt.imshow(confusion_matrix, interpolation='nearest', cmap="Blues") plt.title(plot_title) plt.colorbar() tick_marks = np.arange(len(y_class)) plt.xticks(tick_marks, y_class, rotation=45) plt.yticks(tick_marks, y_class) # if normalize: # confusion_matrix = confusion_matrix.astype('float') / confusion_matrix.sum(axis=1)[:, np.newaxis] # print("Normalized Confusion Matrix") # else: # print('Confusion Matrix without Normalization') thresh = confusion_matrix.max() / 2. for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])): plt.text(j, i, confusion_matrix[i, j], horizontalalignment="center", color="white" if confusion_matrix[i, j] > thresh else "black") plt.ylabel(plot_y_label) plt.xlabel(plot_x_label) plt.tight_layout() plt.show() except Exception as ex: print( "An error occurred: {}".format(str(ex)))
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
def plot_confusion_matrix(confusion_matrix, class_labels, normalize=False, title='Confusion Matrix', cmap=plt.cm.Blues): """ Code courtesy of Abinav Sagar: https://towardsdatascience.com/convolutional-neural-network-for-breast-cancer-classification-52f1213dcc9 """ if normalize: confusion_matrix = confusion_matrix.astype( 'float') / confusion_matrix.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(confusion_matrix) plt.imshow(confusion_matrix, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(class_labels)) plt.xticks(tick_marks, class_labels, rotation=55) plt.yticks(tick_marks, class_labels) fmt = '.2f' if normalize else 'd' thresh = confusion_matrix.max() / 2. for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])): plt.text(j, i, format(confusion_matrix[i, j], fmt), horizontalalignment="center", color="white" if confusion_matrix[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout()
def plot_confusion_matrix(confusion_matrix, nb_classes, title, normalize=False, cmap=plt.cm.Blues): classes = np.arange(0, nb_classes) fig, ax = plt.subplots() im = ax.imshow(confusion_matrix, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(confusion_matrix.shape[1]), yticks=np.arange(confusion_matrix.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else '.0f' thresh = confusion_matrix.max() / 2. for i in range(confusion_matrix.shape[0]): for j in range(confusion_matrix.shape[1]): ax.text(j, i, format(confusion_matrix[i, j], fmt), ha="center", va="center", color="white" if confusion_matrix[i, j] > thresh else "black") fig.tight_layout() plt.savefig('./'+title+'_confusionmatrix.pdf', bbox_inches='tight') plt.show()
def plot_confusion_matrix(path, confusion_matrix, filename, class_names=['background', 'weed', 'sugar_beet'], normalize=False, color_map=plt.cm.Blues, eps=1e-6): """Reference: https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html """ accuracy = np.trace(confusion_matrix) / ( np.sum(confusion_matrix).astype('float') + eps) misclass = 1 - accuracy if normalize: confusion_matrix = confusion_matrix.astype('float') / ( confusion_matrix.sum(axis=1)[:, np.newaxis] + 1e-10) fig, ax = plt.subplots() im = ax.imshow(confusion_matrix, interpolation='nearest', cmap=color_map) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set( xticks=np.arange(confusion_matrix.shape[1]), yticks=np.arange(confusion_matrix.shape[0]), # ... and label them with the respective list entries xticklabels=class_names, yticklabels=class_names, title='Confusion Matrix: ' + Path(filename).stem, ylabel='Actual label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", va="center", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = confusion_matrix.max() / 2. for i in range(confusion_matrix.shape[0]): for j in range(confusion_matrix.shape[1]): ax.text( j, i, format(confusion_matrix[i, j], fmt), ha="center", va="center", color="white" if confusion_matrix[i, j] > thresh else "black") confusion_matrix_dir_path = path / 'confusion_matrix' if not confusion_matrix_dir_path.exists(): confusion_matrix_dir_path.mkdir() confusion_matrix_path = confusion_matrix_dir_path / filename ax.set_ylim(len(confusion_matrix) - 0.5, -0.5) fig.savefig(str(confusion_matrix_path), bbox_inches='tight') plt.close('all')
def plot_confusion_matrix(confusion_matrix, classes): # print(confusion_matrix) #plt.imshow 绘制热图 plt.figure() plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Blues) plt.title('confusion matrix') plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=0) plt.yticks(tick_marks, classes) thresh = confusion_matrix.max() / 2. for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])): plt.text(j, i, confusion_matrix[i, j], horizontalalignment="center", color="white" if confusion_matrix[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() print( '查准率为:', confusion_matrix[1, 1] / (confusion_matrix[1, 1] + confusion_matrix[0, 1])) print( '召回率为:', confusion_matrix[1, 1] / (confusion_matrix[1, 1] + confusion_matrix[1, 0])) print('准确率为:', (confusion_matrix[0, 0] + confusion_matrix[1, 1]) / (confusion_matrix[0, 0] + confusion_matrix[0, 1] + confusion_matrix[1, 1] + confusion_matrix[1, 0])) print( '*********************************************************************************' )
def plot_confusion_matrix(self, confusion_matrix, class_names, normalize=False, cmap="gray", path_to_save="./", name="temp"): # https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: confusion_matrix = confusion_matrix.astype( 'float') / confusion_matrix.sum(axis=1)[:, np.newaxis] # print("Normalized confusion matrix") else: pass # print('Confusion matrix, without normalization') # print(cm) plt.imshow(confusion_matrix, interpolation='nearest', cmap=cmap) # plt.colorbar() tick_marks = np.arange(len(class_names)) # plt.xticks(tick_marks, class_names, rotation=45) plt.xticks(tick_marks, class_names, rotation=0) plt.yticks(tick_marks, class_names) # tick_marks = np.arange(len(class_names) - 1) # plt.yticks(tick_marks, class_names[1:]) fmt = '.2f' if normalize else 'd' thresh = confusion_matrix.max() / 2. for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])): plt.text( j, i, format(confusion_matrix[i, j], fmt), horizontalalignment="center", color="white" if confusion_matrix[i, j] > thresh else "black") # plt.ylabel('True label') # plt.xlabel('Predicted label') plt.ylabel('true distortion type') plt.xlabel('predicted distortion type') n_classes = len(class_names) plt.ylim([n_classes - 0.5, -0.5]) plt.tight_layout() # plt.show() plt.savefig(path_to_save + name + ".png") plt.clf() plt.close()
def plotConfusionMatrix(confusion_matrix, classifier): classes = ['not buy', 'buy'] plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Blues) plt.title('confusion matrix') plt.colorbar() tick_marks = np.arange(2) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') fmt = 'd' thresh = confusion_matrix.max() / 2. for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])): plt.text(j, i, format(confusion_matrix[i, j], fmt), horizontalalignment="center", color="white" if confusion_matrix[i, j] > thresh else "black")
def plot_confusion_matrix(self, confusion_matrix, classes): fig = plt.figure(figsize=(6, 6)) plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Blues) plt.title('Confusion matrix') tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes) plt.yticks(tick_marks, classes) threshold = confusion_matrix.max() / 2. for i, j in itertools.product(range(2), range(2)): plt.text(j, i, format(confusion_matrix[i, j], 'd'), horizontalalignment="center", color="white" if confusion_matrix[i, j] > threshold else "black") plt.ylabel('True label') plt.xlabel('Predicted label') fig.savefig('fig.png')
def plot_confusion_matrix(confusion_matrix, classes, title, normalize=False): if normalize: confusion_matrix = confusion_matrix.astype( 'float') / confusion_matrix.sum(axis=1)[:, np.newaxis] plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Blues) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])): plt.text( j, i, format(confusion_matrix[i, j], '.2f' if normalize else 'd'), horizontalalignment="center", color="white" if confusion_matrix[i, j] > confusion_matrix.max() / 2. else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
print('Accuracy:', accuracy_score(y_test, y_pred)) """ #Individual variable importance importances = list(clf.feature_importances_) feature_importances = [(feature, round(importance, 2)) for feature, importance in zip(features_list, importances)] feature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True) [print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances] """ #Confusion matrix tells how many correct and incorrect predictions on training and testing data confusion_matrix = confusion_matrix(y_test, y_pred) fig, ax = plt.subplots(figsize=(8, 6)) ax.imshow(confusion_matrix, cmap=plt.cm.Blues) ax.grid(False) ax.xaxis.set(ticks=(0, 1), ticklabels=('Predicted No Migraines', 'Predicted Migraines')) ax.yaxis.set(ticks=(0, 1), ticklabels=('Actual No Migraines', 'Actual Migraines')) ax.set_ylim(1.5, -0.5) thresh = confusion_matrix.max() / 2. for i in range(confusion_matrix.shape[0]): for j in range(confusion_matrix.shape[1]): plt.text(j, i, format(confusion_matrix[i, j]), ha="center", va="center", color="black" if confusion_matrix[i, j] == 0 or confusion_matrix[i, j] < thresh else "white") plt.savefig('Confusion Matrix')