【问题标题】:Prepare scipy.io.loadarff result for scikit-learn为 scikit-learn 准备 scipy.io.loadarff 结果
【发布时间】:2014-05-17 09:28:41
【问题描述】:

我正在尝试将scikit-learn.arff 文件一起使用。考虑以下代码:

from sklearn.ensemble import RandomForestClassifier
from scipy.io.arff import loadarff

import scipy as sp
import numpy as np

dataset = loadarff(open('iris.arff','r'))
target = np.array(dataset[0]['class'])
train = np.array(dataset[0][['sepallength', 'sepalwidth', 'petallength', 'petalwidth']])
rf = RandomForestClassifier(n_estimators = 20, n_jobs = 8)
rf.fit(train, target)

它返回以下错误:

ValueError: need more than 1 value to unpack

我认为这与train 是一个元组数组而不是列表(或数组?)这一事实有关;检查sklearn.datasets.load_iris() 会发现与RandomForestClassifier 一起成功工作的列表数组(数组?)。

【问题讨论】:

    标签: python scipy scikit-learn


    【解决方案1】:

    自 4 月以来似乎发生了一些变化,loadarff 现在返回一个由 ndarrayMetaData 组成的元组

    with open('training_set.arff','r') as f:
        data, meta = loadarff(f)
    
    print(type(data)) # <class 'numpy.ndarray'> 
    print(type(meta)) # <class 'scipy.io.arff.arffread.MetaData'>
    

    更具体地说,data 似乎是一个记录数组。可以使用以下 sn-p 将其转换为普通的 numpy 数组

    train_data = data[meta.names()[:-1]] #everything but the last column
    train_data = train_data.view(np.float).reshape(data.shape + (-1,)) #converts the record array to a normal numpy array
    

    【讨论】:

    • FutureWarning: Numpy has detected that you may be viewing or writing to an array returned by selecting multiple fields in a structured array. This code may break in numpy 1.13 because this will return a view instead of a copy -- see release notes for details.
    【解决方案2】:

    RandomForestClassifier 的文档会告诉您,fitX 参数作为其(n_samples, n_features) 形状的二维数组,但您所拥有的确实是一维数组:

    >>> target.shape
    (150,)
    >>> train.shape
    (150,)
    

    令人惊讶的是,这个数组的内容不是元组,而是我以前从未遇到过的类型:

    >>> train[0]
    (5.1, 3.5, 1.4, 0.2)
    >>> type(train[0])
    <type 'numpy.void'>
    

    这种类型没有记录,并且对asarrayastype 的响应相当奇怪,但是转换为列表列表并返回数组就可以了:

    >>> X = np.asarray(train.tolist(), dtype=np.float32)
    >>> X.shape
    (150, 4)
    >>> rf.fit(X, target)
    RandomForestClassifier(bootstrap=True, compute_importances=None,
                criterion='gini', max_depth=None, max_features='auto',
                max_leaf_nodes=None, min_density=None, min_samples_leaf=1,
                min_samples_split=2, n_estimators=20, n_jobs=8,
                oob_score=False, random_state=None, verbose=0)
    

    【讨论】:

      猜你喜欢
      • 2015-08-24
      • 2015-04-07
      • 2017-05-26
      • 2016-08-12
      • 2016-07-15
      • 2012-12-06
      • 2022-01-08
      • 2012-09-03
      • 1970-01-01
      相关资源
      最近更新 更多