gpt4 book ai didi

python - 运行 scikit 学习示例时 matplotlib 出错

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:18 25 4
gpt4 key购买 nike

我最近在学习 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

关于python - 运行 scikit 学习示例时 matplotlib 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30760457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com