


#Data sets benchmarks from A Comparative Evaluation of Unsupervised Anomaly Detection Algorithms for Multivariate Data

      ########################################################


#Read dataset breast-cancer


da=read.table("breast-cancer-unsupervised-ad.tab" ,sep='\t',header=F) 
#the data set and dimensions should be changed. Data sets are available at https://doi.org/10.7910/DVN/OPQMVF


library(archetypes)
source("LstepArchetypesMod.R")


#This dataset has 30 dimensions
#1 if it is an outlier, 0 if it is not an outlier
label=da[,31]=='o' 
label[label==TRUE]='1'
label[label==FALSE]='0'
label=as.factor(label)

################################
#AA +k-NN
###############################

#min-max normalization or standardization (Step 1)

library(caret)

pp=preProcess(da[,1:30], method = "range")
#pp=preProcess(da[,1:30], method = c("center", "scale"))


#X is the normalized matrix
X= predict(pp, da[,1:30])


#Find archetypes and screeplot (Step 2)
library(DDoutlier)
library(AUC)
nada=10 #15 #it is P
norep=20
set.seed(1234)
ai=LstepArchetypesMod(X, 1:nada, nrep=norep)

#Draw the RSS graph in order to find the elbow (number of initial archetypes)
screeplot(ai)

#Choose the number of initial archetypes
e=4 #2,3,5

vi=10 #5
vf=50 #15
#AA+ k-NN (Step 3)
auci=c()

for (i in vi:vf)
{
pei=rep(0,dim(X)[1])
for (j in e:nada){

a=bestModel(ai[[j]])

pei=pei+KNN_SUM(a$alphas, k=i) 

}
auci=c(auci,auc(roc(pei, label)))

}


#Mean and standard desviation of AUC 
summary(auci) 
sd(auci)


#####Converting into binary labels: 
vi=10 #5
vf=50 #15
h=1
pii=matrix(0,nrow=(vf-vi+1),ncol=dim(X)[1])
for (i in vi:vf){

pei=rep(0,dim(X)[1])
for (j in e:nada){

a=bestModel(ai[[j]])

pei=pei+KNN_SUM(a$alphas, k=i) 

}
b=boxplot(pei)
pii[h,]=as.integer(is.element(pei,b$out))
h=h+1
}

#voting: It will be an outlier if it is voted more than 50%
#Draw a table with the number of outliers 
table(Predictions = as.integer(apply(pii,2,sum)>(((vf-vi+1))*0.5)), TrueLabels = label)

####################################

############
#RDOS
############


vi=10 #5
vf=50 #15
auci=c()

for (i in vi:vf)
{
pei=RDOS(X, k=i) 

auci=c(auci,auc(roc(pei, label)))

}


#Mean and standard desviation of AUC 
summary(auci) 
sd(auci)
