library(gbm)
library(caret)
library(dataiku)

# Load R Model
r_model <- dkuManagedFolderPath("qz0nSBEJ")
path <- paste(r_model, 'model.RData', sep="/")
load(path)
print(gbm.fit)

# Recipe inputs
df <- dkuReadDataset("test")

#-----------------------------------------------------------------
# Settings
#-----------------------------------------------------------------
target.variable <- 'Churn'

features.num <- c(
    'Account_Length', 'VMail_Message', 'Day_Mins', 'Day_Calls', 'Day_Charge', 'Eve_Mins', 
    'Eve_Calls', 'Eve_Charge', 'Night_Mins', 'Night_Calls', 'Night_Charge', 'Intl_Mins', 
    'Intl_Calls', 'Intl_Charge', 'CustServ_Calls'        
)

features.cat <- c(
    'State', 'Area_Code', 'Intl_Plan', 'VMail_Plan'
)

#-----------------------------------------------------------------
# Preprocessing
#-----------------------------------------------------------------
df[features.cat]    <- lapply(df[features.cat], as.factor)
df[features.num]    <- lapply(df[features.num], as.double)
df[target.variable] <- lapply(df[target.variable], as.factor)
test.ml <- df[c(features.cat, features.num, target.variable)]

#-----------------------------------------------------------------
# Prediction
#-----------------------------------------------------------------
o <- cbind(df, predict(gbm.fit, test.ml, type = "prob", na.action = na.pass))

# Recipe outputs
dkuWriteDataset(o, "test_scored_r")
