当我在jupyter笔记本中使用matplotlib时,总是会出现“matplotlib当前正在使用非GUI后端”错误?

2024-06-06 17:55:42 发布

您现在位置:Python中文网/ 问答频道 /正文

import matplotlib.pyplot as pl
%matplot inline
def learning_curves(X_train, y_train, X_test, y_test):
""" Calculates the performance of several models with varying sizes of training data.
    The learning and testing error rates for each model are then plotted. """

print ("Creating learning curve graphs for max_depths of 1, 3, 6, and 10. . .")

# Create the figure window
fig = pl.figure(figsize=(10,8))

# We will vary the training set size so that we have 50 different sizes
sizes = np.rint(np.linspace(1, len(X_train), 50)).astype(int)
train_err = np.zeros(len(sizes))
test_err = np.zeros(len(sizes))

# Create four different models based on max_depth
for k, depth in enumerate([1,3,6,10]):

    for i, s in enumerate(sizes):

        # Setup a decision tree regressor so that it learns a tree with max_depth = depth
        regressor = DecisionTreeRegressor(max_depth = depth)

        # Fit the learner to the training data
        regressor.fit(X_train[:s], y_train[:s])

        # Find the performance on the training set
        train_err[i] = performance_metric(y_train[:s], regressor.predict(X_train[:s]))

        # Find the performance on the testing set
        test_err[i] = performance_metric(y_test, regressor.predict(X_test))

    # Subplot the learning curve graph
    ax = fig.add_subplot(2, 2, k+1)

    ax.plot(sizes, test_err, lw = 2, label = 'Testing Error')
    ax.plot(sizes, train_err, lw = 2, label = 'Training Error')
    ax.legend()
    ax.set_title('max_depth = %s'%(depth))
    ax.set_xlabel('Number of Data Points in Training Set')
    ax.set_ylabel('Total Error')
    ax.set_xlim([0, len(X_train)])

# Visual aesthetics
fig.suptitle('Decision Tree Regressor Learning Performances', fontsize=18, y=1.03)
fig.tight_layout()
fig.show()

当我运行learning_curves()函数时,它显示:

UserWarning:C:\Users\Administrator\Anaconda3\lib\site-packages\matplotlib\figure.py:397: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure

this is the screenshot


Tags: ofthetestperformancetrainingfigtrainax
3条回答

您可以更改matplotlib使用的后端,包括:

import matplotlib
matplotlib.use('TkAgg')

在您的第1行之前,因为必须先设置它。有关详细信息,请参见this answer

(还有其他后端选项,但当我遇到类似问题时,将后端更改为TkAgg对我有效)

导入时添加%matplotlib inline有助于在笔记本中平滑绘图

%matplotlib inline
import matplotlib.pyplot as plt

%matplotlib inline将matplotlib的后端设置为“内联”后端: 有了这个后端,打印命令的输出将在前端内联显示,就像Jupyter笔记本,就在生成它的代码单元的正下方。生成的绘图也将存储在笔记本文档中。

你不需要“fig.show()”这行。把它取下来。那就没有警告信息了。

相关问题 更多 >