当试图对数据执行GaussianNB时获取TypeError - python beginner

时间:2018-01-08 18:01:26

标签: python-3.x typeerror gaussian naivebayes sklearn-pandas

我正在尝试使用GaussianNB构建预测模型。

我有一个csv文件,如下所示: csv data

我的代码如下所示:

encoded_df = pd.read_csv('path to file')

y = encoded_df.iloc[:,12]

X = encoded_df.iloc[:,0:12]
model = GaussianNB()
model.fit(X, y)

prediction_test_naive = ['427750', '426259', '2', '1610', '2', '1', '2', '1', '4', '1', '47', '2']

naive_predicted_class = model.predict(np.reshape(prediction_test_naive, [1, -1]))

print("predicted Casualty Severity: 1 = slight, 2 = serious, 3 = fatal: ", naive_predicted_class)

expected_bayes = y
predicted_bayes = model.predict(X)

classification_report_bayes = metrics.classification_report(expected_bayes, predicted_bayes)

print(classification_report_bayes)

运行时我得到类型错误:

TypeError:ufunc'sundract'不包含带签名匹配类型的循环dtype('U32')dtype('U32')dtype('U32')

错误似乎来自上面示例代码中的第7行。但除此之外,我不知道。

我不确定如何解决这个问题,我有一个有效的决策树,但也想使用贝叶斯定理。

1 个答案:

答案 0 :(得分:0)

错误是由于这一行:

prediction_test_naive = ['427750', '426259', '2', '1610', '2', '1', '2', '1', '4', '1', '47', '2']

在这里,您要声明一个字符串列表(通过在值周围使用单个引号),然后将其用于预测。但在模型中,只允许数值。所以你需要将它们转换为数字。

为此,您可以使用以下方式:

1)将prediction_test_naive声明为这样的数字(请注意已删除引号):

prediction_test_naive = [427750, 426259, 2, 1610, 2, 1, 2, 1, 4, 1, 47, 2]

2)使用numpy

将prediction_test_naive转换为数字

这一行之后:

prediction_test_naive = ['427750', '426259', '2', '1610', '2', '1', '2', '1', '4', '1', '47', '2']

这样做:

prediction_test_naive = np.array(prediction_test_naive, dtype=float)