par(mfrow=c(2,2),mar=c(4,4,2,2))
Dataplay<-read.table("Thirex.csv",sep=",",dec=".",header=T)
Dataplay$Belong<-factor(Dataplay$Belong,ordered=TRUE,levels=c(1:3),labels=c("Normale","Iper","Ipo"))
m<-10 # Numero di dati su cui effettuare la verifica del CART
n<-nrow(Dataplay)
Itotal<-1:n;Iselect<-sample(Itotal,n-m,replace=FALSE)
nm<-n-m;nm1<-nm+1
Impara<-Dataplay[Iselect,];Impara<-data.frame(Impara)
Impara$Belong<-factor(Impara$Belong,ordered=TRUE,levels=c(1:3),labels=c("Normale","Iper","Ipo"))
summary(Impara$Belong)
boxplot(Impara[,2:2],horizontal=FALSE,range=0,notch=T,col="springgreen",pars =list(boxwex=0.5,staplewex=0.5,outwex = 0.5))
boxplot(Impara[,3:3],horizontal=FALSE,range=0,notch=T,col="springgreen",pars =list(boxwex=0.5,staplewex=0.5,outwex = 0.5))
boxplot(Impara[,4:4],horizontal=FALSE,range=0,notch=T,col="springgreen",pars =list(boxwex=0.5,staplewex=0.5,outwex = 0.5))
boxplot(Impara[,5:5],horizontal=FALSE,range=0,notch=T,col="springgreen",pars =list(boxwex=0.5,staplewex=0.5,outwex = 0.5))
par(mfrow=c(1,1))
hist(Impara[,5:5],main="Istogramma dei valori osservati",ylab="Frequenze relative",xlab="Lambda diverso da 	1",breaks="scott",freq=F,right=T,col="lightgreen")
plot(density(Impara[,5:5]))
# Classificazione e regressione ad albero
library(rpart)
rpart.control(minsplit=4, cp=0.0001, 
              maxcompete=4, maxsurrogate=5, usesurrogate=2, xval=10,
              surrogatestyle=0, maxdepth=30)
Impara.tr <- rpart(Class~T3test+Tsth+Basal+Mad,method="class",parms=list(split="gini",prior=c(.60,.25,.15)),cost=c(1,5,1,5),data=Impara)
printcp(Impara.tr,digits=2)
plotcp(Impara.tr,minline=TRUE,lty=2,lwd=1,col="red",upper="size")
summary(Impara.tr)
plot(Impara.tr,branch=0.25,margin=0.05);text(Impara.tr,digits=2)
Impara.pru<-prune(Impara.tr,cp=0.032)
post(Impara.pru,file="",title=" Thyroid gland data",pretty=0,use.n=TRUE,digits=2,branch=0.5)
#
# Valutazione del metodo sul campione training
#
Impara.pred<-predict(Impara.pru, type="class")
Confus<-table(Impara.pred,Impara$Class)
summary(Confus)
Confus<-prop.table(Confus)
print(Confus,digits=3)
Crit<-sum(diag(Confus))
cat("Percentuale di successo nel campione training: ",round(Crit,digits=3),"\n")
#
# Valutazione del metodo sul campione test
#
Impara.pred<-predict(Impara.tr,Dataplay[Itotal[-Iselect],], type="prob")
New.Impara<-cbind(Impara.pred,Dataplay$Belong[Itotal[-Iselect]])
print(New.Impara)
Estim<-apply(New.Impara[,1:3],1,which.max)
Estim<-factor(Estim,ordered=TRUE,levels=c(1:3),labels=c("Normale","Iper","Ipo"))
Obser<-Dataplay$Belong[Itotal[-Iselect]]
Valid<-table(Estim,Obser)
Valid<-prop.table(Valid)
print(Valid)
Crit<-sum(diag(Valid))
cat("Percentuale di successo nel campione test: ",round(Crit,digits=3),"\n")