【发布时间】:2021-01-08 00:07:44
【问题描述】:
我正在尝试使用 sklearn 将以下数据输入随机森林算法。
数据(以 csv 格式呈现):
id,CAP,astroturf,fake_follower,financial,other,overall,self-declared,labels
3039154799,0.7828265255249504,0.1,1.8,1.4,3.2,1.4,0.4,1
390617262,1.0,0.8,1.4,1.0,5.0,5.0,0.2,0
4611389296,0.7334998320027682,0.2,0.6,0.1,1.8,1.1,0.0,1
我的代码:
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import numpy as np
master_training_set_path = "data_bank/cleaning_data/master_training_data_id/master_train_one_hot.csv"
df = pd.read_csv(master_training_set_path)
labels = np.array(df["labels"].values)
train, test, train_labels, test_labels = train_test_split(df, labels,
stratify=labels,
test_size=0.3)
model = RandomForestClassifier(n_estimators=100, bootstrap=True, max_features='sqrt')
# this is the problematic line
model.fit(train, train_labels)
有问题的行是最后一行,当我运行它时,它返回以下回溯:
Traceback (most recent call last):
File "path\random_forest.py", line 39, in
<module>
model.fit(train, train_labels)
File "path\sklearn\ensemble\forest.py", line 247, in fit
X = check_array(X, accept_sparse="csc", dtype=DTYPE)
File "path\sklearn\utils\validation.py", line 434, in check_array
array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: could not convert string to float: 'self-declared'
我已尝试确保 'train' 和 'train_label' 变量是 numpy 2d 数组,但我仍然遇到同样的错误
我的困惑来自于“自我声明”特征不是一个值,而是我的数据集中某个特征的名称。为什么 sklearn 在训练数据之前不删除标头?
【问题讨论】:
-
代码为我运行(也许再看看你的 csv 文件)。旁注:请注意
train和test包含标签。 -
好的,看了一下csv文件,有一些小问题。即标题在数据集中。感谢您的帮助。
标签: python pandas dataframe scikit-learn random-forest