>RE::VISION CRM

R 데이터 분석

ANN Example

YONG_X 2015. 8. 13. 16:11


#---------


##====[ANN :: MTCARS Example with Standardization and Log Transformation ]


=========


#install.packages("neuralnet")

require(neuralnet)

require(ggplot2)


# Scale standardization and Log transformation


trainingdata <- mtcars

devider1 <- max(log(trainingdata$mpg))

trainingdata$mpg <- log(trainingdata$mpg)/devider1

trainingdata$wt <- trainingdata$wt/max(trainingdata$wt) 

trainingdata$hp <- trainingdata$hp/max(trainingdata$hp) 


#-------

#Train the neural network

#Going to have 2 hidden layers

#Threshold is a numeric value specifying the threshold for the partial

#derivatives of the error function as stopping criteria.


# net.sqrt <- neuralnet(mpg~wt+hp ,trainingdata, hidden=c(10,10), rep=100, 


threshold=0.01)


# net.sqrt <- neuralnet(mpg~wt+hp ,trainingdata, hidden=c(5,5), rep=1000, threshold=0.01)


net.sqrt <- neuralnet(mpg~wt+hp ,trainingdata, hidden=c(5,2),  rep=1000, threshold=0.01)


print(net.sqrt)

 


# Plot the neural network (takes a while  )

# plot(net.sqrt)

 

#Test the neural network on some training data

# testdata

# Works fine

net.results <-  compute(net.sqrt , trainingdata[,c("wt","hp")])


# detransform prediction score to the original scale


mtcars$nnpred <- exp(as.numeric(net.results$net.result) * devider1 )

plot(mtcars$nnpred, mtcars$mpg)


mean( abs(100*(mtcars$nnpred-mtcars$mpg)/mtcars$mpg)) 

# 9.049620312


#---- comparison

lm1 <- lm(mpg~wt+hp ,data=trainingdata)

mtcars$lmpred <- predict(lm1, mtcars)

mean( abs(100*(mtcars$lmpred-mtcars$mpg)/mtcars$mpg)) 

# 9.742982991