gpt4 book ai didi

python - 为 scikit-learn 准备 scipy.io.loadarff 结果

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:20 24 4
gpt4 key购买 nike

我正在尝试将 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 一起成功工作。

最佳答案

RandomForestClassifier 的文档会告诉您 fit 将其 X 参数作为一个二维数组 (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)

关于python - 为 scikit-learn 准备 scipy.io.loadarff 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22873434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com