1. 程式人生 > 其它 >R語言:袋裝技術和提升技術進行使用者購買意願的預測

R語言:袋裝技術和提升技術進行使用者購買意願的預測

下面是是使用者的資料特徵(data_buqi1.csv),並對資料進行了補齊,最後的willing是使用者購買意願的資料,現在需要建立合理的模型對使用者購買意願進行預測

建立好模型後,需要對下面的使用者(need_test.csv)的購買意願進行預測

下面是用袋裝技術對模型進行預測

 1 a=read.csv("data_buqi1.csv",header=TRUE);head(a)
 2 b1<-a[,-1]
 3 b1<-b1[,-1]
 4 b1
 5 
 6 #按條件提取子集
 7 b1=subset(a,i==1);b1
 8 b2=subset(a,i==2);b2
9 b3=subset(a,i==3);b3 10 11 #袋裝技術進行預測 12 install.packages("adabag") 13 install.packages("repart") 14 library("rpart") 15 detach("package:ipred") 16 library("adabag") 17 #設定引數 18 Ct1<-rpart.control(minsplit=20,maxcompete=4,maxdepth=30,cp=0.01,xval=10) 19 20 b1$willing=as.factor(b1$willing)#將輸入變數設定為因子,否則會出錯
21 22 BAg<-bagging(willing~.,data=b1,control=Ct1,mfinal=25) 23 weight_bagging=BAg$importance 24 write.csv(weight_bagging,"pinpai3_bagging.csv") 25 pre<-predict.bagging(BAg,b1) 26 as.data.frame(pre$confusion) 27 as.data.frame(pre$error) 28 class=as.data.frame(pre$class) 29 prob=as.data.frame(pre$prob)
30 a$willing_pre=class 31 a$prob=prob[2] 32 33 #對需要測試的資料進行預測擬合 34 need_test=read.csv("need_test.csv",header=TRUE) 35 n_t<-need_test[,-59];n_t 36 n_t<-n_t[,-1];n_t 37 n_t<-n_t[,-1];n_t 38 pre1<-predict.bagging(BAg,n_t) 39 write.csv(class,"class_bag.csv") 40 pre

也可以利用Adaboost的方法,就結果而言,其預測效果更好

#推進技術
#con<-table(b1$willing,Boot$class);E4<-(sum(con)-sum(diag(con)))/sum(con);E4
#資料預處理
n=read.csv("need_test1.csv",header=TRUE);head(n)
n1<-n[,-1:-2]#去掉前兩列
a=read.csv("data_buqi1.csv",header=TRUE);head(a)
test=as.data.frame(a);head(test)
a1<-a[,-1:-2]
a1$willing=as.factor(a1$willing)#將輸入變數設定為
b1=subset(a,i==1);head(b1)
p1<-b1[,-1:-2]
p1$willing=as.factor(p1$willing)#將輸入變數設定為
head(p1)
b2=subset(a,i==2);head(b2)
p2<-b2[,-1:-2]
p2$willing=as.factor(p2$willing)#將輸入變數設定為
b3=subset(a,i==3);head(b3)
p3<-b3[,-1:-2]
p3$willing=as.factor(p3$willing)#將輸入變數設定為
library("adabag")
#總資料
Boot<-boosting(willing~.,data=a1,control=Ct1,boos=TRUE,mfinal=25,coeflearn="Breiman")
write.csv(Boot$importance,"boos_impor0.csv")
a.pred=predict.boosting(Boot,newdata = a1)
a.pred$class
boos_test=a.pred$prob
boos_test0=data.frame(boos_test);boos_test0
boos_test0$class=a.pred$class;head(boos_test0)
test$pro0=boos_test0[,1]
test$pro1=boos_test0[,2]
test$class=boos_test0[,3]
write.csv(test,"boos_data0.csv")
#拿總資料預測來測試待測試
a.pred=predict.boosting(Boot,newdata = n1)
boos_test=a.pred$prob
boos_test0=data.frame(boos_test);boos_test0
boos_test0$class=a.pred$class;head(boos_test0)
n$pro0=boos_test0[,1]
n$pro1=boos_test0[,2]
n$class=boos_test0[,3]
write.csv(n,"boos_test0.csv")

參考書籍:

薛薇《R語言資料探勘方法及應用》