Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 10 - Model Selection And Boosting/XGBoost/xgboost.R
1341 views
1
# XGBoost
2
3
# Importing the dataset
4
dataset = read.csv('Churn_Modelling.csv')
5
dataset = dataset[4:14]
6
7
# Encoding the categorical variables as factors
8
dataset$Geography = as.numeric(factor(dataset$Geography,
9
levels = c('France', 'Spain', 'Germany'),
10
labels = c(1, 2, 3)))
11
dataset$Gender = as.numeric(factor(dataset$Gender,
12
levels = c('Female', 'Male'),
13
labels = c(1, 2)))
14
15
# Splitting the dataset into the Training set and Test set
16
# install.packages('caTools')
17
library(caTools)
18
set.seed(123)
19
split = sample.split(dataset$Exited, SplitRatio = 0.8)
20
training_set = subset(dataset, split == TRUE)
21
test_set = subset(dataset, split == FALSE)
22
23
# Fitting XGBoost to the Training set
24
# install.packages('xgboost')
25
library(xgboost)
26
classifier = xgboost(data = as.matrix(training_set[-11]), label = training_set$Exited, nrounds = 10)
27
28
# Predicting the Test set results
29
y_pred = predict(classifier, newdata = as.matrix(test_set[-11]))
30
y_pred = (y_pred >= 0.5)
31
32
# Making the Confusion Matrix
33
cm = table(test_set[, 11], y_pred)
34
35
# Applying k-Fold Cross Validation
36
# install.packages('caret')
37
library(caret)
38
folds = createFolds(training_set$Exited, k = 10)
39
cv = lapply(folds, function(x) {
40
training_fold = training_set[-x, ]
41
test_fold = training_set[x, ]
42
classifier = xgboost(data = as.matrix(training_set[-11]), label = training_set$Exited, nrounds = 10)
43
y_pred = predict(classifier, newdata = as.matrix(test_fold[-11]))
44
y_pred = (y_pred >= 0.5)
45
cm = table(test_fold[, 11], y_pred)
46
accuracy = (cm[1,1] + cm[2,2]) / (cm[1,1] + cm[2,2] + cm[1,2] + cm[2,1])
47
return(accuracy)
48
})
49
accuracy = mean(as.numeric(cv))
50