运行 个 scikit 学习示例时 matplotlib 出错

Error with matplotlib when running examples of scikit learn

我最近在学习 python,我遇到了一个名为 scikit learn 的包,我们可以在其中使用 python 库和自定义代码来生成各种图。我已经安装了所有依赖项,然后下载并安装了 scikit learn,但是当我尝试 运行 示例代码时,我在生成绘图时遇到错误。

代码

from sklearn import datasets
from sklearn.cross_validation import cross_val_predict
from sklearn import linear_model
import matplotlib.pyplot as plt

lr = linear_model.LinearRegression()
boston = datasets.load_boston()
y = boston.target

# cross_val_predict returns an array of the same size as `y` where each entry
# is a prediction obtained by cross validated:
predicted = cross_val_predict(lr, boston.data, y, cv=10)

fig,ax = plt.subplots() ## error comes from calling the function plt.subplots()
ax.scatter(y, predicted)
ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4)
ax.set_xlabel('Measured')
ax.set_ylabel('Predicted')
fig.show()

错误

fig,ax = plt.subplots()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 866, in subplots
    fig = figure(**fig_kw)
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 343, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
    window = Tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1712, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

这与设置环境变量有关吗?我正在使用 python 2.7.3 并且这个包应该可以使用它或者我是否必须放置路径或其他东西?抱歉,我是 python 的新手,只是想快速弄清楚我是否可以使用这个包来快速生成绘图。感谢任何帮助消除此错误的帮助。

我怀疑您正在尝试 运行 您的代码在远程机器上(可能 ssh)或者只是 matplotlib 没有安装好。

如果您是第一种情况,我建议将 savefig 与命令 matplotlib.use('Agg') 一起使用,该命令告诉 matplotlib 不使用默认显示。这将生成一个 .png 文件,您可以使用 scp:

将其导入您的家中
import matplotlib
matplotlib.use('Agg')
from pylab import savefig
from sklearn import datasets
from sklearn.cross_validation import cross_val_predict
from sklearn import linear_model
import matplotlib.pyplot as plt

lr = linear_model.LinearRegression()
boston = datasets.load_boston()
y = boston.target

# cross_val_predict returns an array of the same size as `y` where each entry
# is a prediction obtained by cross validated:
predicted = cross_val_predict(lr, boston.data, y, cv=10)

fig,ax = plt.subplots() ## error comes from calling the function plt.subplots()
ax.scatter(y, predicted)
ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4)
ax.set_xlabel('Measured')
ax.set_ylabel('Predicted')

# don't use fig.show()

savefig('FIGURE_NAME.png') # savefig from matplotlib