In [ ]:
#  Module: Anomaly detection
#  Version 1.1
#  Topic : Piecewise regression
#  Example source:
#####################################################################
#  For support or questions, contact Sri Krishnamurthy at
#  sri@quantuniversity.com
#  Copyright 2016 QuantUniversity LLC.
#####################################################################


### R package
#install.packages("segmented")
library(segmented)
In [ ]:
### Creating dataset
set.seed(1234) 
z<-runif(100) 
y<-rnorm(100,exp(2+1.8*pmax(z-.5,0))) 
data <- data.frame(z,y)
data
plot(z,y)
In [ ]:
### Fitting model
Model <-glm(y~z,family=gaussian) 
Model.seg <-segmented(Model,seg.Z=~z)
summary(Model.seg)
plot(z,y, pch=17, ylim=c(5,20),col="red")
plot(Model.seg, add=T)
In [ ]:
### Fitted values, residuals and outliers
res <- Model.seg$residuals
plot(z,res,main="residuals plot")
data1 <- data.frame(z,res)
data1 <- data1[order(z),]
data1 <- data1[data1[,1] < 0.5,]
mean.res <- mean(data1[,2])
sd.res <- sd(data1[,2])
UL <- mean.res + 1.5*sd.res
LL <- mean.res -1.5*sd.res
outliers <- data1[(data1[,2]<= LL)|(data1[,2] >= UL),]
outliers
In [ ]: