运行scikit学习示例时matplotlib出错

时间:2015-06-10 15:13:37

标签: python python-2.7 scikit-learn

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

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很新,只是很快就想弄清楚我是否可以使用这个包来快速生成图表。任何帮助摆脱这个错误的人都表示赞赏。

1 个答案:

答案 0 :(得分:3)

我怀疑您是在尝试在远程计算机上运行代码(可能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