【问题标题】:Name 'Ridge' is not defined in Python SpyderPython Spyder 中未定义名称“Ridge”
【发布时间】:2016-11-12 11:11:50
【问题描述】:

我已经在 conda 环境雪花中安装了 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 将它们全部显示出来。

【问题讨论】:

  • 这样做会给出 /home/sridhar/anaconda3/lib/python3.5/site-packages/sklearn/utils/validation.py:386: DeprecationWarning: Passing 1d array as data is deprecated in 0.17 and将在 0.19 中引发 ValueError。如果您的数据具有单个特征,则使用 X.reshape(-1, 1) 或 X.reshape(1, -1) 如果它包含单个样本,则使用 X.reshape(1, -1) 重塑您的数据。 DeprecationWarning) >>> 但我没有使用一维数组?
  • 实际上有一个警告标记说 sklearn 已导入但未使用

标签: machine-learning scipy scikit-learn spyder


【解决方案1】:

对我来说,它工作正常:

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 在 import 语句中没有定义。

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

【讨论】:

  • 添加 from sklearn.linear_model import Ridge 后我得到 /home/sridhar/anaconda3/lib/python3.5/site-packages/sklearn/utils/validation.py:‌​386: DeprecationWarning: Passing 1d 数组作为数据在 0.17 中已弃用,并将在 0.19 中引发 ValueError。如果您的数据具有单个特征,则使用 X.reshape(-1, 1) 或 X.reshape(1, -1) 如果它包含单个样本,则使用 X.reshape(1, -1) 重塑您的数据。弃用警告)>
  • 其实有个警告符号说sklearn imported but not used!
猜你喜欢
  • 2016-01-18
  • 1970-01-01
  • 2021-10-18
  • 2016-05-16
  • 2013-01-26
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多