簡體   English   中英

運行scikit學習示例時matplotlib錯誤

[英]Error with matplotlib when running examples of scikit learn

我最近正在學習python,遇到了一個名為scikit learning的軟件包,在這里我們可以使用python庫和定制代碼生成各種圖表。 我已經安裝了所有依賴項,然后下載並安裝了scikit learning,但是當我嘗試運行示例代碼時,卻在生成圖時出錯。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM