gpt4 book ai didi

r - BNlearn R 错误 “variable Variable1 must have at least two levels.”

转载 作者:行者123 更新时间:2023-12-03 16:04:01 24 4
gpt4 key购买 nike

尝试使用 BNlearn 创建 BN,但我一直收到错误消息;

Error in check.data(data, allowed.types = discrete.data.types) : variable Variable1 must have at least two levels.

它给了我每个变量的错误,即使它们都是因素并且有超过 1 个级别,正如您所看到的 - 在这种情况下,我的变量“模型”有 4 个级别

由于我无法共享变量和数据集,因此我创建了一个小集并属于数据集的代码。我遇到同样的问题。我知道我只共享了 2 个变量,但是所有变量都出现了相同的错误。
library(tidyverse)
library (bnlearn)
library(openxlsx)

DataFull <- read.xlsx("(.....)/test.xlsx", sheet = 1, startRow = 1, colNames = TRUE)
set.seed(600)
DataFull <- as_tibble(DataFull)

DataFull$Variable1 <- as.factor(DataFull$Variable1)
DataFull$TargetVar <- as.factor(DataFull$TargetVar)

DataFull <- na.omit(DataFull)
DataFull <- droplevels(DataFull)

DataFull <- DataFull[sample(nrow(DataFull)),]
Data <- DataFull[1:as.integer(nrow(DataFull)*0.70)-1,]
Datatest <- DataFull[as.integer(nrow(DataFull)*0.70):nrow(DataFull),]
nrow(Data)+nrow(Datatest)==nrow(DataFull)

FocusVar <- as.character("TargetVar")
BN.naive <- naive.bayes(Data, FocusVar)

使用 str(data) ,我可以看到变量已经有 2 个或更多级别:

str(Data)


Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   27586 obs. of  2 variables:
$ Variable1: Factor w/ 3 levels "Small","Medium",..: 2 2 3 3 3 3 3 3 3 3 ...
$ TargetVar: Factor w/ 2 levels "Yes","No": 1 1 1 1 1 1 2 1 1 1 ...

数据集链接: https://drive.google.com/open?id=1VX2xkPdeHKdyYqEsD0FSm1BLu1UCtOj9eVIVfA_KJ3g

最佳答案

bnlearn期待 data.frame : 不适用于 tibbles , 所以把你的数据保存为 data.frame通过省略行 DataFull <- as_tibble(DataFull)
例子

library(tibble)
library (bnlearn)

d <- as_tibble(learning.test)
hc(d)

Error in check.data(x) : variable A must have at least two levels.



特别是,它是来自 bnlearn:::check.data 的线路
if (nlevels(x[, col]) < 2) 
stop("variable ", col, " must have at least two levels.")

在标准 data.frame , learning.test[,"A"]返回一个向量等 nlevels(learning.test[,"A"])按预期工作,但是,根据设计,您无法从 tibbles 中提取这样的向量: d[,"A"])仍然是 tbl_df而不是向量,因此 nlevels(d[,"A"])没有按预期工作,并返回零。

关于r - BNlearn R 错误 “variable Variable1 must have at least two levels.”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54922515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com