我在使用R语言进行随机森林预测,使用的数据集是Aggregate_sample.csv。
Company Index,Is Customer,videos,videoswatched,tutorials,workshops,casestudies,productpages,other,totalActivities,youngTitleCount,oldTitleCount,Median between two Activities,Max between 2 activities,Time since100thactivitySTPT,0,0,3,0,0,0,0,19,22,0,22,120,64074480,0STPR,0,0,1,0,1,1,0,61,64,0,64,120,56004420,0PLNRTKNLJS,0,0,0,0,0,0,0,25,25,25,0,810,4349940,0ASSSNNSP,0,0,0,0,0,3,0,17,20,0,20,60,2220,0STPP,1,164,32,25,36,26,0,2525,2808,498,2310,60,2938260,76789992AJKMPTNKSL,0,0,0,0,0,0,0,1,1,0,1,0,0,0FNKL,0,0,0,1,0,0,0,21,22,0,22,300,2415900,0FNKK,0,0,1,0,0,0,0,1,2,2,0,60,60,0FNKN,1,2,0,1,0,0,0,22,25,0,25,480,150840,0
以下是我的R脚本
# 安装并加载决策树和森林所需的包library(rpart)install.packages('randomForest')library(randomForest)Aggregate <- read.csv("~/Documents/Machine Lerning/preprocessed data/Aggregate_sample.csv")# splitdf 函数splitdf <- function(dataframe, seed=NULL) {if (!is.null(seed)) set.seed(seed)index <- 1:nrow(dataframe)trainindex <- sample(index, trunc(length(index)*0.7))trainset <- dataframe[trainindex, ]testset <- dataframe[-trainindex, ]list(trainset=trainset,testset=testset)}splits <- splitdf(Aggregate, seed=808)#它返回一个列表 - 两个名为trainset和testset的数据框str(splits)lapply(splits,nrow)#查看每个数据框的前几列lapply(splits,head)training <- splits$trainsettesting <- splits$testset#拟合随机森林模型model <- randomForest(as.factor(Aggregate$Is.Customer) ~ Aggregate$seniorTitleCount +Aggregate$juniorTitleCount + Aggregate$totalActivities + Aggregate$Max.between.2.activities+ Aggregate$Time.since.100th.activity + Aggregate$downloads , data=training,importance=TRUE, ntree=2000)#print(mode)# 哪些变量是重要的varImpPlot(model)
但我一直收到以下错误,无法继续进行。看起来我的IsCustomer列有问题,但它只是一个包含”0″和”1″的列(我的数据集中没有NA值)。
Error in [<-.factor("*tmp*", keep, value = c("0", "0", "0", "0", "1", : NAs are not allowed in subscripted assignments In addition: Warning message:'newdata' had 3 rows but variables found have 9 rows
我阅读了以下相关问题,但没有找到答案。在lapply中赋值时”NAs are not allowed in subscripted assignments”
提前感谢。
回答:
看起来你只想从training
数据框中提取数据,所以在你的公式中不应该引用Aggregate
。使用测试数据中实际存在的变量名,这样似乎可以正常工作。
randomForest(as.factor(Is.Customer) ~ oldTitleCount + youngTitleCount + totalActivities + Max.between.2.activities + Time.since100thactivity + videos , data=training,importance=TRUE, ntree=2000)
返回结果如下
Call: randomForest(formula = as.factor(Is.Customer) ~ oldTitleCount + youngTitleCount + totalActivities + Max.between.2.activities + Time.since100thactivity + videos, data = training, importance = TRUE, ntree = 2000) Type of random forest: classification Number of trees: 2000No. of variables tried at each split: 2 OOB estimate of error rate: 16.67%Confusion matrix: 0 1 class.error0 4 0 0.01 1 1 0.5