![](/img/trans.png)
[英]Scikit-learn linear model fit after running matplotlib plot returns Value error
[英]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.