【问题标题】:When trying to perform GaussianNB on data get TypeError - python beginner尝试对数据执行 GaussianNB 时得到 TypeError - python 初学者
【发布时间】:2018-06-17 17:59:00
【问题描述】:

我正在尝试使用 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 'subtract' 不包含签名匹配类型 dtype('U32') dtype('U32') dtype('U32') 的循环

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

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

【问题讨论】:

  • 您能否将示例数据发布为产生此错误的文本。
  • 418241,442351,2,1905,2,2,2,1,1,1,38,7,2 424993,432898,2,1615,1,2,2,1,1 ,2,50,1,1 431159,436397,2,1645,1,2,1,1,1,1,26,1,1 431159,436397,2,1645,1,2,1,1,2 ,2,22,1,1 439313,432376,2,956,2,1,1,1,1,1,57,2,1 426994,439957,2,1115,2,2,1,1,1,1 ,59,2,2 427813,431257,1,1352,3,1,1,1,1,2,53,1,2 431496,432727,2,2015,1,1,2,3,2,2 ,22,1,1 431880,430498,2,1110,3,1,1,1,2,2,20,1,1 有一个例子,实际数据大约有2500个条目
  • 这个样本数据会产生错误吗?
  • 是的,我实际上有 2 个不同的数据集,它们都产生错误。但是,决策树函数可以正确处理数据。

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


【解决方案1】:

错误是由于这一行:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2010-11-25
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    相关资源
    最近更新 更多