A fundamental understanding of logistic regression models is assumed, please seek resources to improve understanding and use this tutorial as a computational example.
More information can be found in the Data Import and Export tutorial notebook.
train = read.csv("train.csv")
test = read.csv("test.csv")
LogLossBinary = function(actual, predicted, eps = 1e-15) {
predicted = pmin(pmax(predicted, eps), 1-eps)
- (sum(actual * log(predicted) + (1 - actual) * log(1 - predicted))) / length(actual)
}
Fit a single predictor logistic regression model and inspect its coefficients.
model = glm(Response ~ Var1, data = train, family = "binomial")
coef(model)
summary(model)
Make predictions with the single predictor model on the training data.
trainingPredictions = predict(model, type = "response")
LogLossBinary(train$Response, trainingPredictions)
Create another model that predicts every observation as the mean of the training set's response variable. Compare its log loss to the first model's log loss.
responseMean = rep(mean(train$Response), nrow(train))
LogLossBinary(train$Response, responseMean)
LogLossBinary(train$Response, trainingPredictions)
Fit another logistic regression model with more predictors and inspect results.
multipleModel = glm(Response ~ Var1 + Var2 + NVVar1, data = train, family = "binomial")
coef(multipleModel)
summary(multipleModel)
multiplePredictions = predict(multipleModel, type = "response")
Compare the log loss of all 3 models fit.
print(paste(LogLossBinary(train$Response, responseMean), "Log loss of response mean model"))
print(paste(LogLossBinary(train$Response, trainingPredictions), "Log loss of single predictor model"))
print(paste(LogLossBinary(train$Response, multiplePredictions), "Log loss of multiple predictor model"))
As expected, the single predictor logistic regression model has a lower log loss than the response mean model, and the multiple predictor logistic regression model has a lower log loss than both.
Create predictions on the test set using our three predictor model. These predictions are scored as the 'GLM Benchmark' on the competition leaderboard.
testPredictions = predict(multipleModel, newdata = test, type = "response")
outputDataSet = data.frame("RowID" = test$RowID,
"ProbabilityOfResponse" = testPredictions)
write.csv(outputDataSet, "glmBenchmarkSubmission.csv", row.names = FALSE)