
dpl=TRUE
source("notes-funs.R")
library(MASS) ## a library of example datasets
library(kknn)
############################################################
if(1) { cat("###get data\n")
data(fgl) ## loads the data into R; see help(fgl)
n=nrow(fgl)
y = rep(3,n)
y[fgl$type=="WinF"]=1
y[fgl$type=="WinNF"]=2
y = as.factor(y)
levels(y) = c("WinF","WinNF","Other")
print(table(y,fgl$type))
x = cbind(fgl$RI,fgl$Al,fgl$Na)
scf = function(x) {return((x-min(x))/(max(x)-min(x)))}
x = apply(x,2,scf)
colnames(x) = c("RI","Al","Na")
ddf = data.frame(type=y,x)
names(ddf) =c("type","RI","Al","Na")
printfl(summary(ddf),dpl,"forensic-ddf.rtxt")
}
######################################################################
if(1) { cat("###fit kNN\n")
near = kknn(type~.,ddf,ddf,k=10,kernel = "rectangular")
knnfit = near$fitted
printfl(table(knnfit,ddf$type),dpl,"glass_y-yhat_table.rtxt")

printfl(near$fitted[1:50],dpl,"nearfit1to50.rtxt")

printfl(near$prob[1:5,],dpl,"nearfitprob1to5.rtxt")

fitdf = data.frame(type=ddf$type,near$prob)
names(fitdf)[2:4] = c("ProbWinF","ProbWinNF","ProbOther")

if(dpl) pdf(file="glass_plot-phat.pdf",height=5,width=16)
par(mfrow=c(1,3))
par(mai=c(1,1,.5,.5))
plot(ProbWinF~type,fitdf,col=c(grey(.5),2:3),cex.lab=2.4,cex.axis=2.4)
plot(ProbWinNF~type,fitdf,col=c(grey(.5),2:3),cex.lab=2.4,cex.axis=2.4)
plot(ProbOther~type,fitdf,col=c(grey(.5),2:3),cex.lab=2.4,cex.axis=2.4)
if(dpl) dev.off()
}
######################################################################
if(1) { cat("###fit multinom\n")
library(nnet)

mlogf = multinom(type~.,ddf)
logitfit = predict(mlogf,ddf)
printfl(table(logitfit,ddf$type),dpl,"glass_y-yhat_table-multi.rtxt")

}
######################################################################
if(dpl) rm(list=ls())

