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¥Anaconda¥lib¥site-packages¥matplotlib¥figure.py:397:UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure
これはスクリーンショットです。
インポート中に%matplotlib inlineを追加すると、ノートブックのプロットをスムーズにすることができます。
%matplotlib inline
import matplotlib.pyplot as plt
%matplotlib inlineは、matplotlibのバックエンドを「inline」バックエンドに設定します。 このバックエンドを使用すると、プロットコマンドの出力が、Jupyterノートブックなどのフロントエンド内のインラインで、それを作成したコードセルの真下に表示されます。 結果のプロットは、ノートブックドキュメントにも保存されます。
をインクルードすることで、matplotlibが使用するバックエンドを変更することができます:
import matplotlib
matplotlib.use('TkAgg')
**行目の import matplotlib.pyplot as pl
の前に記述してください。詳細はこの回答を参照してください。
(バックエンドオプションは他にもありますが、同様の問題が発生したときにバックエンドを TkAgg
に変更するとうまくいきました)
https://matplotlib.org/examples/animation/dynamic_image.html を使ってテストしている。
%matplotlib notebook
を追加してみた。時々カーネルを止めなければならない :-(
「matplotlibは現在非GUIバックエンドを使用しています」というエラーは、コマンド「fig.show()」を使用してプロットを表示しようとしたときにも発生しました。 Jupyter Notebookでは、プロットをレンダリングするために、コマンド fig、ax = plt.subplots()
とplotコマンドを同じセルに配置する必要があることがわかりました。
たとえば、次のコードは、Out [5]のバープロットを正常に表示します。
[3]:
import matplotlib.pyplot as plt
%matplotlib inline
[4]:
x = 'A B C D E F G H'.split()
y = range(1, 9)
[5]:
fig, ax = plt.subplots()
ax.bar(x, y)
Out [5]:(8人のアーティストのコンテナオブジェクト)。
一方、次のコードにはプロットが表示されません。
[5]:
fig, ax = plt.subplots()
アウト[5]:
[6]:
ax.bar(x, y)
Out [6]:(8人のアーティストのコンテナオブジェクト)。
Out [6]では、「8人のアーティストのコンテナオブジェクト」の記述しかありませんでしたが、バープロットは表示されていません。
同じエラーがありました。 次に
を使用しました。
matplotlibをインポートします。 matplotlib.use( 'WebAgg')
。
うまくいきます。(Webで表示するには、竜巻をインストールする必要があります(「pip install tornado」))。
Pythonバージョン:3.7。 matplotlibバージョン:3.1.1。