【问题标题】:R error: all arguments must have the same lengthR错误:所有参数必须具有相同的长度
【发布时间】:2019-05-04 06:39:38
【问题描述】:

我在用 R 做朴素贝叶斯时出错,这是我的代码和错误

library(e1071) 

#data

train_data <- read.csv('https://raw.githubusercontent.com/JonnyyJ/data/master/train.csv',header=T)
test_data <- read.csv('https://raw.githubusercontent.com/JonnyyJ/data/master/test.csv',header=T)      

efit <- naiveBayes(y~job+marital+education+default+contact+month+day_of_week+
                        poutcome+age+pdays+previous+cons.price.idx+cons.conf.idx+euribor3m
                       ,train_data)  

pre <- predict(efit, test_data)
bayes_table <- table(pre, test_data[,ncol(test_data)])
accuracy_test_bayes <- sum(diag(bayes_table))/sum(bayes_table)
    list('predict matrix'=bayes_table, 'accuracy'=accuracy_test_bayes)

错误:

bayes_table

我真的不明白发生了什么,因为我是 R 新手

【问题讨论】:

  • 能否提供一些数据,以便我们重现错误?
  • 错误是自定义的:两个向量之一不同。我们没有你的数据,所以我不知道我们是否能够重现这一点。
  • 抱歉,我已经更新了我的问题@Lyngbakr
  • 抱歉,我已经更新了我的问题
  • 你需要调试,首先检查这些是否相等length(pre)length(test_data[,ncol(test_data)])

标签: r naivebayes


【解决方案1】:

由于某种原因,默认的 predict(efit, test_data, type = "class") 在这种情况下不起作用(可能是因为您的模型预测了测试数据集中所有观察值的 0)。您还需要使用您的结果构建表格(即test_data[,ncol(test_data)] 返回euribor3m)。以下应该有效:

pre <- predict(efit, test_data, type = "raw") %>%
  as.data.frame() %>%
  mutate(prediction = if_else(0 < 1, 0, 1)) %>%
  pull(prediction)

bayes_table <- table(pre, test_data$y)

accuracy_test_bayes <- sum(diag(bayes_table)) / sum(bayes_table)

list('predict matrix' = bayes_table, 'accuracy' = accuracy_test_bayes)
# $`predict matrix`
#    
# pre    0    1
#   0 7282  956
# 
# $accuracy
# [1] 0.8839524

【讨论】:

  • 谢谢兄弟,你点亮了我的夜晚。
  • 不管怎样,如何得到一个2X2的metrix,你发的metrix是2x1的。
  • 您的预测都不是1。这就是为什么您没有对应于pre = 1 的行的原因。您的数据非常支持0 预测。
猜你喜欢
  • 1970-01-01
  • 2021-07-12
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多