Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Unexpected plot behavior when running stock code for confusion matrix #15368

Closed
@vkng12

Description

@vkng12

Bug report

Bug summary

I'm fairly new to matplotlib and I was trying to create a confusion matrix following the tutorial here:https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html. I downloaded the example code and when I ran it, the plots looked slightly cropped on the top and bottom edges.

Code for reproduction

print(__doc__)importnumpyasnpimportmatplotlib.pyplotaspltfromsklearnimportsvm,datasetsfromsklearn.model_selectionimporttrain_test_splitfromsklearn.metricsimportconfusion_matrixfromsklearn.utils.multiclassimportunique_labels# import some data to play withiris=datasets.load_iris()X=iris.datay=iris.targetclass_names=iris.target_names# Split the data into a training set and a test setX_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0)# Run classifier, using a model that is too regularized (C too low) to see# the impact on the resultsclassifier=svm.SVC(kernel='linear',C=0.01)y_pred=classifier.fit(X_train,y_train).predict(X_test)defplot_confusion_matrix(y_true,y_pred,classes,normalize=False,title=None,cmap=plt.cm.Blues):"""    This function prints and plots the confusion matrix.    Normalization can be applied by setting `normalize=True`.    """ifnottitle:ifnormalize:title='Normalized confusion matrix'else:title='Confusion matrix, without normalization'# Compute confusion matrixcm=confusion_matrix(y_true,y_pred)# Only use the labels that appear in the dataclasses=classes[unique_labels(y_true,y_pred)]ifnormalize:cm=cm.astype('float')/cm.sum(axis=1)[:,np.newaxis]print("Normalized confusion matrix")else:print('Confusion matrix, without normalization')print(cm)fig,ax=plt.subplots()im=ax.imshow(cm,interpolation='nearest',cmap=cmap)ax.figure.colorbar(im,ax=ax)# We want to show all ticks...ax.set(xticks=np.arange(cm.shape[1]),yticks=np.arange(cm.shape[0]),# ... and label them with the respective list entriesxticklabels=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'ifnormalizeelse'd'thresh=cm.max()/2.foriinrange(cm.shape[0]):forjinrange(cm.shape[1]):ax.text(j,i,format(cm[i,j],fmt),ha="center",va="center",color="white"ifcm[i,j]>threshelse"black")fig.tight_layout()returnaxnp.set_printoptions(precision=2)# Plot non-normalized confusion matrixplot_confusion_matrix(y_test,y_pred,classes=class_names,title='Confusion matrix, without normalization')# Plot normalized confusion matrixplot_confusion_matrix(y_test,y_pred,classes=class_names,normalize=True,title='Normalized confusion matrix')plt.show()

Actual outcome

Screenshot from 2019-10-03 10-12-56

Expected outcome

The plots were expected to not look cropped.

Matplotlib version

  • Operating system: Ubunto 18.04
  • Matplotlib version: 3.1.1
  • Matplotlib backend (print(matplotlib.get_backend())):
  • Python version: 3.7
  • Jupyter version (if applicable):
  • Other libraries:

matplotlib installed via pip.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp