【问题标题】:Applying sklearn function to pandas dataframe gives ValueError("Unknown label type: %r" % y)将 sklearn 函数应用于 pandas 数据帧会给出 ValueError("Unknown label type: %r" % y)
【发布时间】:2016-03-24 14:28:42
【问题描述】:

以下代码给出错误信息:

    >>> import pandas as pd
    >>> from sklearn import preprocessing, svm
    >>> df = pd.DataFrame({"a": [0,1,2], "b":[0,1,2], "c": [0,1,2]})
    >>> clf = svm.SVC()
    >>> df = df.apply(lambda x: preprocessing.scale(x))
    >>> clf.fit(df[["a", "b"]], df["c"])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\Alexander\Anaconda\lib\site-packages\sklearn\svm\base.py", lin
     151, in fit
        y = self._validate_targets(y)
      File "C:\Users\Alexander\Anaconda\lib\site-packages\sklearn\svm\base.py", lin
     515, in _validate_targets
        check_classification_targets(y)
      File "C:\Users\Alexander\Anaconda\lib\site-packages\sklearn\utils\multiclass.
    y", line 173, in check_classification_targets
        raise ValueError("Unknown label type: %r" % y)
    ValueError: Unknown label type: 0   -1.224745
    1    0.000000
    2    1.224745
    Name: c, dtype: float64

pandas DataFrame 的 dtype 不是对象,所以应用 sklearn svm 函数应该没问题,但由于某种原因它无法识别分类标签。是什么导致了这个问题?

【问题讨论】:

  • 试试df[["a", "b"]].valuesdf["c"].values SKLearn 通常需要数组,而不是数据帧。
  • 同样的问题,错误信息是:
  • raise ValueError("Unknown label type: %r" % y) ValueError: Unknown label type: array([-1.22474487, 0. , 1.22474487])
  • 当我尝试运行 df = df.apply(lambda x: preprocessing.scale(x)) 时出现错误。 TypeError: ("Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') ...
  • 这很奇怪 - 我收到了一些警告,但我省略了,但没有错误消息.. 你使用的是什么版本的 python?我正在使用 Python 2.7.11。

标签: python pandas scikit-learn


【解决方案1】:

问题是在您的缩放步骤之后,标签是浮点值,这不是有效的标签类型;如果您转换为 intstr 它应该可以工作:

In [32]: clf.fit(df[["a", "b"]], df["c"].astype(int))
Out[32]: 
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 2019-03-21
    • 2017-04-28
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 2016-03-21
    • 2021-12-30
    • 2020-02-17
    相关资源
    最近更新 更多