Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Created September 2, 2014 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasdarimont/4f272fccdd92d29e384d to your computer and use it in GitHub Desktop.
Save thomasdarimont/4f272fccdd92d29e384d to your computer and use it in GitHub Desktop.
require(stringr)
require(pmml)
require(RODBC)
channel <- odbcConnect("PostgreSQL35W32")
#for(houseId in 0:39){
houseId <- "*"
cat(paste('Create regression model for house_id: ', houseId, '\n'))
results <- sqlQuery(channel, paste("SELECT * FROM smartgird_load_regression_win15min_by_h_fake",houseId))
pmmlParentXml <- "<PMML version=\"4.2\" xmlns=\"http://www.dmg.org/PMML-4_2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.dmg.org/PMML-4_2 http://www.dmg.org/v4-2/pmml-4-2.xsd\">
<Header copyright=\"Copyright (c) 2014 tom\" description=\"Linear Regression Model\">
<Extension name=\"user\" value=\"tom\" extender=\"Rattle/PMML\"/>
<Application name=\"Rattle/PMML\" version=\"1.4\"/>
<Timestamp>2014-09-01 19:48:16</Timestamp>
</Header>
<DataDictionary numberOfFields=\"2\">
<DataField name=\"y\" optype=\"continuous\" dataType=\"double\"/>
<DataField name=\"x\" optype=\"continuous\" dataType=\"double\"/>
</DataDictionary>
</PMML>
"
parentDoc <<- xmlTreeParse(pmmlParentXml)
parentDocRootElement <<- xmlRoot(parentDoc)
#sink('d:\\temp\\pmml_output_test_house4_sep8.pmml.xml')
computeModel <- function(rec){
house_id <- rec[1]$house_id
win15minhour <- rec[6]$win15minhour
load_dm1 <- rec[9]$load_dm1
load_dm2 <- rec[10]$load_dm2
load_dm3 <- rec[11]$load_dm3
load_dm4 <- rec[12]$load_dm4
if(is.na(load_dm1) | load_dm1 == 0){
return
}
days <- c(4,3,2,1)
loads <- c(load_dm4, load_dm3, load_dm2, load_dm1)
df <- data.frame(x=days, y=loads)
tryCatch({
model <- lm(formula=y ~ x, data=df)
#cat(paste('<!-- Model for house_id: ', house_id, ' win15minhour: ', win15minhour, '-->\n',sep=""))
#cat(toString(pmml.lm(model, model.name=paste('load_prediction_h_', house_id,'_win15minhour_',win15minhour, sep=""))))
pmmlStr <- toString(pmml.lm(model, model.name=paste('load_prediction_h_', house_id,'_win15minhour_',win15minhour, sep="")))
parentDocRootElement <<- addChildren(parentDocRootElement, xmlRoot(xmlTreeParse(pmmlStr))[[3]])
#cat('\n\n')
}, error = function(e) {
cat(paste(e,'\n\n'))
}, finally = {
})
}
by(results, 1:nrow(results), computeModel)
#sink()
saveXML(parentDocRootElement, file=paste("D:\\development\\projects\\xd-keynote\\models\\smartgrid_loadprediction_combined_linregr.pmml.xml", sep=""))
#}
cat("Done!\n")
#parentDocRootElement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment