我试图用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 男孩 56 23 19 吉尔2.3 女孩 74 57 卡洛斯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()
,因此两种情况归结为代码的同一部分。