python-2.7 - 我正在尝试根据肝脏疾病数据集构建随机森林分类器。但 fit 方法返回错误,例如 :

标签 python-2.7 machine-learning dataset classification data-analysis

from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.read_csv("data.csv")
df['is_train'] = np.random.uniform(0,1,len(df)) <= 0.75
train, test = df[df['is_train'] == True], df[df['is_train'] == False]
features = df.columns[:10]
y = pd.factorize(train['Selector'])[0]
clf = RandomForestClassifier(n_jobs = 2, random_state = 0)
clf.fit(train[features],y)
<小时/>

ValueError Traceback (most recent call last) in () ----> 1 clf.fit(train[features],y)

C:\Users\abhir\Anaconda2\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight) 244 """ 245 # Validate or convert input data --> 246 X = check_array(X, accept_sparse="csc", dtype=DTYPE) 247 y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None) 248 if sample_weight is not None:

C:\Users\abhir\Anaconda2\lib\site-packages\sklearn\utils\validation.pyc in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 400 force_all_finite) 401 else: --> 402 array = np.array(array, dtype=dtype, order=order, copy=copy) 403 404 if ensure_2d:

ValueError: could not convert string to float: Male


对于为什么会发生这种情况以及如何解决这个问题有任何帮助吗?链接至dataset

最佳答案

Scikit learn 的 RandomForestClassifier 不支持分类数据,例如您的情况中值为“男性”和“女性”的“性别”:请参阅 this询问详情。

要解决这个问题,您可以使用标签编码器对分类变量进行编码:

from sklearn import preprocessing

le = preprocessing.LabelEncoder()
le.fit(['Male', 'Female'])
df.loc[:,'gender'] =  le.transform(df['gender'])

数据集的 Alkphos 列中还包含一些 NaN,您需要在训练分类器之前对其进行处理。最简单但不一定是最好的选择是删除缺少值的数据集:

df = df[np.isfinite(df['Alkphos'])]

您需要在将数据分为训练集和测试集之前进行此预处理,因此两个数据集都会经历相同的转换和过滤。

关于python-2.7 - 我正在尝试根据肝脏疾病数据集构建随机森林分类器。但 fit 方法返回错误,例如 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46127741/

相关文章:

python异常.UnicodeDecodeError : 'ascii' codec can't decode byte 0xa7 in

python - sklearn 上的逻辑回归函数

c# - 将数据集放入工作表的最快方法

python - super() 在类方法中不起作用

Python:将两个独立的对象融合为一个?

python - 为什么不能这样使用star运算符? def foo(* args,此=“default”,** kwargs)

python - 如何在 DecisionTreeClassifier 中设置类权重以进行多类设置

machine-learning - 逻辑回归和最优参数 w

c# - windows窗体datagridview添加按钮

database - 大型公共(public)数据集?