名称 'Ridge' 未在 Python Spyder 中定义

Name 'Ridge' is not defined in Python Spyder

我在conda环境snowflakes中安装了scikit learn等依赖

我输入以下起始代码

import numpy as np
import sklearn
from sklearn import linear_model
clf = linear_model.Ridge (alpha = .5)
clf.fit ([[0, 0], [0, 0], [1, 1]], [0, .1, 1]) 
Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None,
      normalize=False, random_state=None, solver='auto', tol=0.001)

clf.predict([1,1])

这会产生错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/sridhar/anaconda3/lib/python3.5/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)
  File "/home/sridhar/anaconda3/lib/python3.5/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 89, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "/home/sridhar/anaconda3/envs/snowflakes/Test/test.py", line 6, in <module>
    Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None,
NameError: name 'Ridge' is not defined

我对此有何看法?我安装了所有依赖项,因为 conda list 显示了所有依赖项。

对我来说,它工作正常:

In [4]: import numpy as np

In [5]: import sklearn

In [6]: from sklearn import linear_model

In [7]: clf = linear_model.Ridge (alpha = .5)

In [8]: clf.fit ([[0, 0], [0, 0], [1, 1]], [0, .1, 1])
Out[8]: 
Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None,
   normalize=False, random_state=None, solver='auto', tol=0.001)

In [9]: clf.predict([[1,1]])
Out[9]: [ 0.82727273]

看来您一定是从 Ipython 笔记本中复制了该代码,如果存在,它会自动打印输出。

因此,它会抛出错误,因为 Ridge 未在导入语句中定义。

如果你真的想在 Spyder 中 运行 这个,我考虑使用 print(clf.fit ([[0, 0], [0, 0], [1, 1]], [0, .1, 1])) 并完全删除下面的行。