ValueError:条件所期望的布尔数组,而不是对象



我试图用sklearn构建一个分类器,当我运行我的代码时,在我的控制台中得到以下错误。

ValueError: Boolean array expected for the condition, not object

我试着调整我的数据(填充空值)以及玩重塑属性(但无济于事)。

以下是相关代码

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.tree import DecisionTreeClassifier
from sklearn.externals import joblib
# Get the dataset
dataset = pd.read_csv('master_info_final_v12_conversion.csv')
# Split the dataset into features and labels
X = dataset[dataset[['Happy', 'Stress', 'Eyes']]]
y = dataset[dataset['phenotype']]
# Split the dataset into training and testing data
X_train, X_test, y_train, y_test = train_test_split(X, y)
# Build the classifier and make prediction
classifier = DecisionTreeClassifier()
classifier.fit(X_train, y_train)
prediction = classifier.predict(X_test)
# Print the confusion matrix
print(confusion_matrix(y_test, prediction))
# Save the model to disk
joblib.dump(classifier, 'classifier.joblib')

这是我的数据快照:

<表类>名称评级表型快乐压力眼睛tbody><<tr>汤米7.1男孩562319吉尔2.3女孩7457卡洛斯4.4无论是45

此错误最常发生在尝试使用数据框架选择列时。例如,在OP中,使用整个数据框(而不是列名的列表/数组)来选择列,这会抛出此错误。

X = dataset[dataset[['Happy', 'Stress', 'Eyes']]]  # <----- error
X = dataset[['Happy', 'Stress', 'Eyes']]           # <----- no error

另一种情况是不带布尔条件调用where()。例如,

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['a', 'b', 'c']})
df.where(df['col2'])                               # <----- error
df.where(df['col2'] == 'a')                        # <----- no error

事实上,如果我们查看源代码,当您将数据帧传递给__getitem__(即[])时,就像在第一种情况下一样,调用where(),因此两种情况归结为代码的同一部分。

最新更新