Uygulamalı Ekonometri

Spaceship Titanic Kaggle Competition

Alihan Çetinkaya

Kütüphanler Yükleniyor

# Veri analizi ve manipülasyon
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
## Model eğitimi ve değerlendirme
library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
## 
## The following object is masked from 'package:ggplot2':
## 
##     margin
## Görselleştirme için
library(ggplot2)
library(dplyr)
library(xgboost)
## 
## Attaching package: 'xgboost'
## 
## The following object is masked from 'package:dplyr':
## 
##     slice
library(caret)
## Zorunlu paket yükleniyor: lattice
## 
## Attaching package: 'caret'
## 
## The following object is masked from 'package:purrr':
## 
##     lift
library(DescTools)
## 
## Attaching package: 'DescTools'
## 
## The following objects are masked from 'package:caret':
## 
##     MAE, RMSE
library(ggcorrplot)
library(mice)
## 
## Attaching package: 'mice'
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following objects are masked from 'package:base':
## 
##     cbind, rbind
library(gridExtra)
## 
## Attaching package: 'gridExtra'
## 
## The following object is masked from 'package:randomForest':
## 
##     combine
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
library(gbm)
## Loaded gbm 2.1.8.1

Verisetinin Yüklenmesi

train <- read.csv("C:/Users/Ortak/Desktop/spaceship titanic/train.csv", as.is=FALSE)
test <- read.csv("C:/Users/Ortak/Desktop/spaceship titanic/test.csv",  as.is=FALSE)
test$Transported = NA
# test ve veri_seti veri çerçevelerini birleştir
birlesik_veri = rbind(train, test)
birlesik_veri %>% head(3)
##   PassengerId HomePlanet CryoSleep Cabin Destination Age   VIP RoomService
## 1     0001_01     Europa     False B/0/P TRAPPIST-1e  39 False           0
## 2     0002_01      Earth     False F/0/S TRAPPIST-1e  24 False         109
## 3     0003_01     Europa     False A/0/S TRAPPIST-1e  58  True          43
##   FoodCourt ShoppingMall  Spa VRDeck            Name Transported
## 1         0            0    0      0 Maham Ofracculy       False
## 2         9           25  549     44    Juanna Vines        True
## 3      3576            0 6715     49   Altark Susent       False

PassengerId “0013_01” şeklinde olduğu için karakter tipinde. İlk 4 karakterle, sonrasını ayırıp analize öyle dahil edeceğiz. “_” karakterinden kurtarmış olduk. Sonrasında ise integer veritipine dönüştüreceğiz.```

temp = birlesik_veri$PassengerId %>% str_split(pattern="_", simplify=TRUE)
birlesik_veri$IdGroup = temp[, 1] %>% as.integer()
birlesik_veri$IdNum = temp[, 2] %>% as.integer()

#"cabin" değişkeni 3 ayrı karakterden oluşuyor <chr> "G/3/S" bunu ayıralım.  Deck, Number and Side şeklinde 3 e ayıralım.
temp = birlesik_veri$Cabin %>% str_split(pattern="/", simplify=TRUE)
birlesik_veri$CabinDeck = temp[, 1] %>% as.factor()
birlesik_veri$CabinNum = temp[, 2] %>% as.integer()
#CabinSide" sütunundaki "P" karakterleri "Port" ile, "S" karakterleri "StarBoard" ile değiştirdik.
birlesik_veri$CabinSide = temp[, 3] %>% str_replace(pattern="P", replace="Port") %>% str_replace(pattern="S", replace="StarBoard") %>% as.factor()

# drop splitted columns
birlesik_veri = birlesik_veri[, !colnames(birlesik_veri) %in% c("PassengerId", "Cabin", "Name")]

# CryoSleep", "VIP", ve "Transported" sütunlarını içeren mantıksal (logical) değerleri integer (tam sayı) türüne dönüştürmek için aşağıdaki kodu kullandık. Bu kodun amacı, bu sütunlardaki "True" ve "False" değerlerini sırasıyla 1 ve 0'a dönüştürmektir.
birlesik_veri$CryoSleep = as.integer(birlesik_veri$CryoSleep == "True")
birlesik_veri$VIP = as.integer(birlesik_veri$VIP == "True")
birlesik_veri$Transported = as.integer(birlesik_veri$Transported == "True")
birlesik_veri %>% head(3)
##   HomePlanet CryoSleep Destination Age VIP RoomService FoodCourt ShoppingMall
## 1     Europa         0 TRAPPIST-1e  39   0           0         0            0
## 2      Earth         0 TRAPPIST-1e  24   0         109         9           25
## 3     Europa         0 TRAPPIST-1e  58   1          43      3576            0
##    Spa VRDeck Transported IdGroup IdNum CabinDeck CabinNum CabinSide
## 1    0      0           0       1     1         B        0      Port
## 2  549     44           1       2     1         F        0 StarBoard
## 3 6715     49           0       3     1         A        0 StarBoard

İyileştirme Çalışması

Harcama ile ilgili eksik veriler için, RoomService” harcamalarını, benzer yolcuların “Spa” ve “VRDeck” harcamalarına dayalı olarak tahmin etmek amacı ile aşağıdaki kodu denedim.. Kod, eksik veriye sahip yolcuların diğer harcama alanlarındaki davranışlarına bakarak tahminlerde bulunarak RoomService sütnundaki boşlukları dolduruyordu. Diğerleri içinde aynısını yaptım ama istediğim sonucu alamadım.

missing_rows <- birlesik_veri %>% filter(is.na(RoomService)) ##### similar_passengers <- birlesik_veri %>% ##### filter(!is.na(RoomService)) %>% ##### filter(Spa >= missing_rowsSpa - 2 & Spa <= missing_rows
Spa + 2) %>% ##### filter(VRDeck >= missing_rowsVRDeck - 2 & VRDeck <=
missing_rows VRDeck + 2)
Dolayısıyla aşağıdaki yöntemle boşlukları doldurdum. Bu kod, veri setindeki eksik değerleri olan, “RoomService”, “FoodCourt”, “ShoppingMall”, “Spa” ve “VRDeck” harcamalarını doldurıyor. İlk olarak, eksik değerlere sahip harcamalar sıfır olarak doldurulur. Ardından, sayısal olmayan ve eksik değer içeren sütunlara ait gösterge sütunları oluşturulur. Son olarak, eksik değer içeren sayısal olmayan sütunlardaki eksik değerler de sıfır ile değiştirilir.
# Eksik değerleri içeren sütunları belirle
birlesik_veri <- birlesik_veri %>%
  mutate(
    RoomService = ifelse(is.na(RoomService), 0, RoomService),
    FoodCourt = ifelse(is.na(FoodCourt), 0, FoodCourt),
    ShoppingMall = ifelse(is.na(ShoppingMall), 0, ShoppingMall),
    Spa = ifelse(is.na(Spa), 0, Spa),
    VRDeck = ifelse(is.na(VRDeck), 0, VRDeck),
    across(
      .cols = c(RoomService, FoodCourt, ShoppingMall, Spa, VRDeck),
      .fns = list(
        isna_indicator = ~as.numeric(is.na(.)),
        imputed_column = ~ifelse(is.na(.), 0, .)
      ),
      .names = "{.col}_{.fn}"
    )
  )
# Age değişkenindeki eksik değerleri ortalama ile doldurmak uygun geldi.
birlesik_veri$Age = birlesik_veri$Age %>% replace_na(mean(birlesik_veri$Age, na.rm=TRUE))
birlesik_veri$CabinNum = birlesik_veri$CabinNum %>% replace_na(-1)

# Aşağıdaki işlem sonucunda, "birlesik_veri" veri çerçevesi, "Deck ve Side" sütunları yerine bu sütunlara karşılık gelen yeni dummy değişkenler oluştu. Bu tür bir dönüşüm, kategorik verilerin makine öğrenimi modellerine girdi olarak verilmesi için yapılması gereken bir süreçtir.
encoder = dummyVars(~ HomePlanet + Destination + CabinDeck + CabinSide, data=birlesik_veri, sep="") 
birlesik_veri.dummy = predict(encoder, newdata=birlesik_veri)
colnames(birlesik_veri.dummy)[5:8] = c("Destination", "DestinationC", "DestinationP", "DestinationT")
#yeni oluşan dummy değişkenlerini görelim
head(birlesik_veri.dummy)
##   HomePlanet HomePlanetEarth HomePlanetEuropa HomePlanetMars Destination
## 1          0               0                1              0           0
## 2          0               1                0              0           0
## 3          0               0                1              0           0
## 4          0               0                1              0           0
## 5          0               1                0              0           0
## 6          0               1                0              0           0
##   DestinationC DestinationP DestinationT CabinDeck CabinDeckA CabinDeckB
## 1            0            0            1         0          0          1
## 2            0            0            1         0          0          0
## 3            0            0            1         0          1          0
## 4            0            0            1         0          1          0
## 5            0            0            1         0          0          0
## 6            0            1            0         0          0          0
##   CabinDeckC CabinDeckD CabinDeckE CabinDeckF CabinDeckG CabinDeckT CabinSide
## 1          0          0          0          0          0          0         0
## 2          0          0          0          1          0          0         0
## 3          0          0          0          0          0          0         0
## 4          0          0          0          0          0          0         0
## 5          0          0          0          1          0          0         0
## 6          0          0          0          1          0          0         0
##   CabinSidePort CabinSideStarBoard
## 1             1                  0
## 2             0                  1
## 3             0                  1
## 4             0                  1
## 5             0                  1
## 6             1                  0
# Bu adımda yapılan işlem, `birlesik_veri` veri çerçevesinden belirli kategorik değişkenleri (`"HomePlanet"`, `"Destination"`, `"CabinDeck"`, `"CabinSide"`) ayırarak yeni bir Data Frame olan `birlesik_veri.factor` oluşturduk. 
factors = c("HomePlanet", "Destination", "CabinDeck", "CabinSide")
birlesik_veri.factor = birlesik_veri[factors]
birlesik_veri = birlesik_veri[!colnames(birlesik_veri) %in% factors]

# dummy değişkenlerin tutulduğu veriseti ile ana verisetini birleştirelim
birlesik_veri = cbind(birlesik_veri, birlesik_veri.dummy)

#  dummy değişkenleri oluşturduğumuz sütunlara artık ihtiyaç kalmadı. Bunları silebiliriz
drop.cols = c("HomePlanet", "Destination", "CabinDeck", "CabinSide", "CabinSideStarBoard")
birlesik_veri = birlesik_veri[!colnames(birlesik_veri) %in% drop.cols]

head(birlesik_veri)
##   CryoSleep Age VIP RoomService FoodCourt ShoppingMall  Spa VRDeck Transported
## 1         0  39   0           0         0            0    0      0           0
## 2         0  24   0         109         9           25  549     44           1
## 3         0  58   1          43      3576            0 6715     49           0
## 4         0  33   0           0      1283          371 3329    193           0
## 5         0  16   0         303        70          151  565      2           1
## 6         0  44   0           0       483            0  291      0           1
##   IdGroup IdNum CabinNum RoomService_isna_indicator RoomService_imputed_column
## 1       1     1        0                          0                          0
## 2       2     1        0                          0                        109
## 3       3     1        0                          0                         43
## 4       3     2        0                          0                          0
## 5       4     1        1                          0                        303
## 6       5     1        0                          0                          0
##   FoodCourt_isna_indicator FoodCourt_imputed_column ShoppingMall_isna_indicator
## 1                        0                        0                           0
## 2                        0                        9                           0
## 3                        0                     3576                           0
## 4                        0                     1283                           0
## 5                        0                       70                           0
## 6                        0                      483                           0
##   ShoppingMall_imputed_column Spa_isna_indicator Spa_imputed_column
## 1                           0                  0                  0
## 2                          25                  0                549
## 3                           0                  0               6715
## 4                         371                  0               3329
## 5                         151                  0                565
## 6                           0                  0                291
##   VRDeck_isna_indicator VRDeck_imputed_column HomePlanetEarth HomePlanetEuropa
## 1                     0                     0               0                1
## 2                     0                    44               1                0
## 3                     0                    49               0                1
## 4                     0                   193               0                1
## 5                     0                     2               1                0
## 6                     0                     0               1                0
##   HomePlanetMars DestinationC DestinationP DestinationT CabinDeckA CabinDeckB
## 1              0            0            0            1          0          1
## 2              0            0            0            1          0          0
## 3              0            0            0            1          1          0
## 4              0            0            0            1          1          0
## 5              0            0            0            1          0          0
## 6              0            0            1            0          0          0
##   CabinDeckC CabinDeckD CabinDeckE CabinDeckF CabinDeckG CabinDeckT
## 1          0          0          0          0          0          0
## 2          0          0          0          1          0          0
## 3          0          0          0          0          0          0
## 4          0          0          0          0          0          0
## 5          0          0          0          1          0          0
## 6          0          0          0          1          0          0
##   CabinSidePort
## 1             1
## 2             0
## 3             0
## 4             0
## 5             0
## 6             1
# Veri setimizde eksik veri olup olmadığına bakalım. Sonucu Temp'e atalım 
train_na = apply(birlesik_veri[!is.na(birlesik_veri$Transported),], MARGIN=2, function(x){sum(is.na(x))})
test_na = apply(birlesik_veri[is.na(birlesik_veri$Transported),], MARGIN=2, function(x){sum(is.na(x))})
temp = matrix(c(train_na, test_na), nrow=length(train_na), dimnames=list(names(train_na)))
data.frame(Data=c("TRAIN", "TEST"), t(temp))
##    Data CryoSleep Age VIP RoomService FoodCourt ShoppingMall Spa VRDeck
## 1 TRAIN         0   0   0           0         0            0   0      0
## 2  TEST         0   0   0           0         0            0   0      0
##   Transported IdGroup IdNum CabinNum RoomService_isna_indicator
## 1           0       0     0        0                          0
## 2        4277       0     0        0                          0
##   RoomService_imputed_column FoodCourt_isna_indicator FoodCourt_imputed_column
## 1                          0                        0                        0
## 2                          0                        0                        0
##   ShoppingMall_isna_indicator ShoppingMall_imputed_column Spa_isna_indicator
## 1                           0                           0                  0
## 2                           0                           0                  0
##   Spa_imputed_column VRDeck_isna_indicator VRDeck_imputed_column
## 1                  0                     0                     0
## 2                  0                     0                     0
##   HomePlanetEarth HomePlanetEuropa HomePlanetMars DestinationC DestinationP
## 1               0                0              0            0            0
## 2               0                0              0            0            0
##   DestinationT CabinDeckA CabinDeckB CabinDeckC CabinDeckD CabinDeckE
## 1            0          0          0          0          0          0
## 2            0          0          0          0          0          0
##   CabinDeckF CabinDeckG CabinDeckT CabinSidePort
## 1          0          0          0             0
## 2          0          0          0             0
colSums(is.na(birlesik_veri))
##                   CryoSleep                         Age 
##                           0                           0 
##                         VIP                 RoomService 
##                           0                           0 
##                   FoodCourt                ShoppingMall 
##                           0                           0 
##                         Spa                      VRDeck 
##                           0                           0 
##                 Transported                     IdGroup 
##                        4277                           0 
##                       IdNum                    CabinNum 
##                           0                           0 
##  RoomService_isna_indicator  RoomService_imputed_column 
##                           0                           0 
##    FoodCourt_isna_indicator    FoodCourt_imputed_column 
##                           0                           0 
## ShoppingMall_isna_indicator ShoppingMall_imputed_column 
##                           0                           0 
##          Spa_isna_indicator          Spa_imputed_column 
##                           0                           0 
##       VRDeck_isna_indicator       VRDeck_imputed_column 
##                           0                           0 
##             HomePlanetEarth            HomePlanetEuropa 
##                           0                           0 
##              HomePlanetMars                DestinationC 
##                           0                           0 
##                DestinationP                DestinationT 
##                           0                           0 
##                  CabinDeckA                  CabinDeckB 
##                           0                           0 
##                  CabinDeckC                  CabinDeckD 
##                           0                           0 
##                  CabinDeckE                  CabinDeckF 
##                           0                           0 
##                  CabinDeckG                  CabinDeckT 
##                           0                           0 
##               CabinSidePort 
##                           0

Veri İşleme

Veri Setini eğitim ve test verisi olarak tekrar ayırma

set.seed(42)  # Rastgelelik kontrolü için seed ayarı
test_indices <- (nrow(birlesik_veri) - 4277 + 1):nrow(birlesik_veri)  
train_data <- birlesik_veri[-test_indices, ]
test_data <- birlesik_veri[test_indices, ]

Veri kümesini dört katlı bir çapraz doğrulama için uygun şekilde bölüp ve bu dizinleri cv.idx adlı bir liste içinde attık.

#8693 4 ün katı olmadığı için hata verdi onun için 1 satırı sildim
train_data <- train_data[1:(nrow(train_data) - 1), ]
nfold = 4
set.seed(0)
cv.idx = split(sample(1:nrow(train_data)), 1:nfold)
str(cv.idx)
## List of 4
##  $ 1: int [1:2173] 1017 4050 8229 7845 2900 3476 7289 1222 1069 5862 ...
##  $ 2: int [1:2173] 8004 1301 1129 5922 7075 1948 4633 2858 5522 6337 ...
##  $ 3: int [1:2173] 4775 8522 878 6526 4650 2580 6519 5400 8214 5491 ...
##  $ 4: int [1:2173] 8462 1799 8677 5071 2159 1530 4344 526 5838 7494 ...

Random Forest

Bu kod ile random forest accuracy düşük çıktı 0.8002761. Bu sebeple modeli geliştirerek bir sonraki Chunk’ta olan kodu yazdık. Burada eşik değerler ile oynayarak daha iyi sonuç elde ettik (0.80948)

# Eğitim verisi ve doğrulama verisi oluşturduk
#set.seed(0)  # Rastgelelik kontrolü
#cv.train_data = train_data[-cv.idx[[i]],]
#cv.valid = train_data[cv.idx[[i]],]

# Random Forest modelini eğittik
#rf_model <- randomForest(Transported ~ ., data = cv.train_data, ntree = 100)

# Tahminler yaptık
#rf_preds <- predict(rf_model, newdata = cv.valid, type = "response")

# Tahminleri sınıf etiketlerine dönüştürdük (örneğin, 0 ve 1)
#rf_pred_classes <- ifelse(rf_preds > 0.5, 1, 0)

# Doğruluk hesaplamak için confusion matrix oluşturduk
#confusion_matrix <- table(Actual = cv.valid$Transported, Predicted = rf_pred_classes)

# Doğruluk sonucunu hesapladık
#accuracy <- sum(diag(confusion_matrix)) / sum(confusion_matrix)

# En iyi doğruluk sonucunu yazdırdık
# cat("Random Forest Modeli Doğruluk:", accuracy, "\n")
accuracy = function(actual, pred){sum(actual == pred) / length(actual)}
pred = rep(0, nrow(train_data))
for (i in 1:nfold){
    cv.train_data = train_data[-cv.idx[[i]],]
    cv.valid = train_data[cv.idx[[i]],]
    model = randomForest(Transported~., data=cv.train_data)
    pred[cv.idx[[i]]] = predict(model, newdata=cv.valid, type="class")
}
## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?

## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?

## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?

## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?
best.t = 0
best.randomForest_accuracy = 0
for (t in seq(0.4, 0.6, 0.01)) {
    pred.t = as.integer(t < pred[cv.idx[[i]]]) # Eşik değeri hesaplamasını doğru veri kümesi üzerinde yapıldı
    acc.t = accuracy(pred.t, cv.valid$Transported) # Doğruluk hesaplama da doğru veri kümesi üzerinde yapıldı
    
    # Eksik değer kontrolü
    if (!is.na(acc.t) && !is.na(best.randomForest_accuracy)) {
        if (acc.t > best.randomForest_accuracy) {
            best.randomForest_accuracy = acc.t
            best.t = t
        }
    }
}
# En iyi eşik değeri ve doğruluk sonucunu yazdıralım
cat("En iyi esik degeri:", best.t, "\n")
## En iyi esik degeri: 0.5
cat("En iyi dogruluk:", best.randomForest_accuracy, "\n")
## En iyi dogruluk: 0.8062586
# Çalışmanın bu aşamasında, Random Forest modelini eğittik, özet bilgileri görüntüledik ve ardından test verileri üzerinde tahminler yaptık. Test verileri pred_random da saklanıyor
model = randomForest(Transported~., data=train_data)
## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?
summary(model)
##                 Length Class  Mode     
## call               3   -none- call     
## type               1   -none- character
## predicted       8692   -none- numeric  
## mse              500   -none- numeric  
## rsq              500   -none- numeric  
## oob.times       8692   -none- numeric  
## importance        36   -none- numeric  
## importanceSD       0   -none- NULL     
## localImportance    0   -none- NULL     
## proximity          0   -none- NULL     
## ntree              1   -none- numeric  
## mtry               1   -none- numeric  
## forest            11   -none- list     
## coefs              0   -none- NULL     
## y               8692   -none- numeric  
## test               0   -none- NULL     
## inbag              0   -none- NULL     
## terms              3   terms  call
pred_random = predict(model, newdata=test_data, type="response")
pred_random = as.integer(best.t < pred_random)

XGBoost Modeli

# Eğitim verisi ve doğrulama verisi oluşturduk
set.seed(0)  # Rastgelelik kontrolü
cv.train_data = train_data[-cv.idx[[i]],]
cv.valid = train_data[cv.idx[[i]],]

# Veri çerçevesini matrise dönüştürdük
train_matrix <- as.matrix(cv.train_data[, -which(names(cv.train_data) == "Transported")])
valid_matrix <- as.matrix(cv.valid[, -which(names(cv.valid) == "Transported")])

# Hedef değişkeni (label) ayarladık
train_label <- cv.train_data$Transported
valid_label <- cv.valid$Transported

# XGBoost modelini eğittik
xgb_model <- xgboost(data = train_matrix, label = train_label, nrounds = 100, objective = "binary:logistic")
## [1]  train-logloss:0.580314 
## [2]  train-logloss:0.512066 
## [3]  train-logloss:0.468866 
## [4]  train-logloss:0.440414 
## [5]  train-logloss:0.418367 
## [6]  train-logloss:0.399696 
## [7]  train-logloss:0.385442 
## [8]  train-logloss:0.373506 
## [9]  train-logloss:0.364343 
## [10] train-logloss:0.356462 
## [11] train-logloss:0.345811 
## [12] train-logloss:0.341659 
## [13] train-logloss:0.338385 
## [14] train-logloss:0.329918 
## [15] train-logloss:0.327644 
## [16] train-logloss:0.323474 
## [17] train-logloss:0.319983 
## [18] train-logloss:0.317349 
## [19] train-logloss:0.314144 
## [20] train-logloss:0.309620 
## [21] train-logloss:0.306482 
## [22] train-logloss:0.302967 
## [23] train-logloss:0.301482 
## [24] train-logloss:0.299665 
## [25] train-logloss:0.298343 
## [26] train-logloss:0.296814 
## [27] train-logloss:0.295295 
## [28] train-logloss:0.291850 
## [29] train-logloss:0.289451 
## [30] train-logloss:0.286194 
## [31] train-logloss:0.285266 
## [32] train-logloss:0.281502 
## [33] train-logloss:0.280408 
## [34] train-logloss:0.278375 
## [35] train-logloss:0.277703 
## [36] train-logloss:0.276637 
## [37] train-logloss:0.275073 
## [38] train-logloss:0.274186 
## [39] train-logloss:0.271111 
## [40] train-logloss:0.269895 
## [41] train-logloss:0.269381 
## [42] train-logloss:0.268465 
## [43] train-logloss:0.266353 
## [44] train-logloss:0.262359 
## [45] train-logloss:0.261253 
## [46] train-logloss:0.260809 
## [47] train-logloss:0.259607 
## [48] train-logloss:0.256218 
## [49] train-logloss:0.255670 
## [50] train-logloss:0.254596 
## [51] train-logloss:0.251763 
## [52] train-logloss:0.248913 
## [53] train-logloss:0.247754 
## [54] train-logloss:0.246142 
## [55] train-logloss:0.244522 
## [56] train-logloss:0.243656 
## [57] train-logloss:0.242644 
## [58] train-logloss:0.241203 
## [59] train-logloss:0.239524 
## [60] train-logloss:0.237980 
## [61] train-logloss:0.237391 
## [62] train-logloss:0.235594 
## [63] train-logloss:0.235343 
## [64] train-logloss:0.232372 
## [65] train-logloss:0.229736 
## [66] train-logloss:0.229184 
## [67] train-logloss:0.226170 
## [68] train-logloss:0.224534 
## [69] train-logloss:0.223425 
## [70] train-logloss:0.221783 
## [71] train-logloss:0.218493 
## [72] train-logloss:0.217850 
## [73] train-logloss:0.215693 
## [74] train-logloss:0.214796 
## [75] train-logloss:0.213757 
## [76] train-logloss:0.213226 
## [77] train-logloss:0.212034 
## [78] train-logloss:0.211572 
## [79] train-logloss:0.211338 
## [80] train-logloss:0.210569 
## [81] train-logloss:0.209673 
## [82] train-logloss:0.207026 
## [83] train-logloss:0.205782 
## [84] train-logloss:0.204401 
## [85] train-logloss:0.203490 
## [86] train-logloss:0.202521 
## [87] train-logloss:0.201210 
## [88] train-logloss:0.200564 
## [89] train-logloss:0.199008 
## [90] train-logloss:0.198120 
## [91] train-logloss:0.196181 
## [92] train-logloss:0.194656 
## [93] train-logloss:0.193014 
## [94] train-logloss:0.191374 
## [95] train-logloss:0.190379 
## [96] train-logloss:0.189462 
## [97] train-logloss:0.189156 
## [98] train-logloss:0.188503 
## [99] train-logloss:0.188260 
## [100]    train-logloss:0.187844
# Tahminler yaptık
xgb_preds <- predict(xgb_model, newdata = valid_matrix)

# Tahminleri sınıf etiketlerine dönüştürdük(örneğin, 0 ve 1)
xgb_pred_classes <- ifelse(xgb_preds > 0.5, 1, 0)

# Doğruluk hesabı için confusion matrix oluşturduk
confusion_matrix <- confusionMatrix(as.factor(xgb_pred_classes), as.factor(valid_label))

# Doğruluk sonucunu aldık
XGBoost_accuracy <- confusion_matrix$overall["Accuracy"]

# En iyi doğruluk sonucunu yazdırdık
cat("XGBoost Modeli Doğruluk:", XGBoost_accuracy, "\n")
## XGBoost Modeli Doğruluk: 0.8099402

Bu kodun amacı, eğitilen XGBoost modelini kullanarak test verileri üzerinden tahminler yapmaktır. Tahminler, xgb_pred_classes_test değişkeninde saklanır.

# XGBoost modelini eğitin
# Test verisi veya yeni veri ile tahminler yapmak için veriyi matrise dönüştürün
test_matrix <- as.matrix(test_data[, -which(names(test_data) == "Transported")])

# Tahminler yapın
xgb_preds_test <- predict(xgb_model, newdata = test_matrix)
# Test verisi veya yeni veri ile tahminler yapmak için veriyi matrise dönüştürün
test_matrix <- as.matrix(test_data[, -which(names(test_data) == "Transported")])

# Tahminleri sınıf etiketlerine dönüştürün (örneğin, 0 ve 1)
xgb_pred_classes_test <- ifelse(xgb_preds_test > 0.5, 1, 0)

# Tahmin sonuçlarını inceleyin veya başka işlemler yapın
head(xgb_pred_classes_test)
## [1] 0 0 1 1 1 0

GBM modeli

# Eğitim verisi ve doğrulama verisi oluşturun
set.seed(0)  # Rastgelelik kontrolü
cv.train_data = train_data[-cv.idx[[i]],]
cv.valid = train_data[cv.idx[[i]],]
# GBM modelini eğittik
gbm_model <- gbm(Transported ~ ., data = cv.train_data, distribution = "bernoulli", n.trees = 100, interaction.depth = 5)
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 12: RoomService_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 14: FoodCourt_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 16: ShoppingMall_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 18: Spa_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 20: VRDeck_isna_indicator has no variation.
# Tahminler yaptık
gbm_preds <- predict(gbm_model, newdata = cv.valid, n.trees = 100, type = "response")

# Tahminleri sınıf etiketlerine dönüştürdük (örneğin, 0 ve 1)
gbm_pred_classes <- ifelse(gbm_preds > 0.5, 1, 0)

# Doğruluk hesaplamak için confusion matrix oluşturduk
confusion_matrix <- table(Actual = cv.valid$Transported, Predicted = gbm_pred_classes)

# Doğruluk sonucunu hesapladık
GBM_accuracy <- sum(diag(confusion_matrix)) / sum(confusion_matrix)
# En iyi doğruluk sonucunu yazdırdık
cat("GBM Modeli Doğruluk:", GBM_accuracy, "\n")
## GBM Modeli Doğruluk: 0.8131615
cat("XGBoost Modeli Doğruluk:", XGBoost_accuracy, "\n")
## XGBoost Modeli Doğruluk: 0.8099402

doğruluk sonuçlarını ekrana yazdırık

cat("GBM Modeli Doğruluk.....:", GBM_accuracy, "\n")
## GBM Modeli Doğruluk.....: 0.8131615
cat("XGBoost Modeli Doğruluk.:", XGBoost_accuracy, "\n")
## XGBoost Modeli Doğruluk.: 0.8099402
cat("Random Forest Doğruluk..:", best.randomForest_accuracy, "\n")
## Random Forest Doğruluk..: 0.8062586

Overfitting Kontrolü

GBM modelinin doğruluk oranı en yüksek çıkan model oldu. Bu modeli eğitim ve doğrulama verileri üzerindeki doğruluklarını hesapladık. Overfitting belirtisi olup olmadığını değerlendirmek için eğitim ve doğrulama doğruluklarını aşağıdaki kod ile çıkartıp, karşılaştırdık. Eğitim ve doğrulama verileri birbirine yakın çıktığı için overfitting yoktur diyoruz.

# Rastgelelik kontrolü
set.seed(0)
# Verileri eğitim ve doğrulama olarak bölmek için indeksleri tanımlayın
cv.idx = split(sample(1:nrow(train_data)), 1:nfold)
# GBM modeli için parametreleri ayarlayın
gbm_params <- list(
  distribution = "bernoulli",
  n.trees = 100,
  interaction.depth = 5
)
# Doğruluk sonuçlarını saklamak için boş bir vektör oluşturun
train_accuracies <- numeric(nfold)
valid_accuracies <- numeric(nfold)
# Çapraz doğrulama döngüsü
for (i in 1:nfold) {
  # Eğitim ve doğrulama verilerini ayarlayın
  cv.train_data <- train_data[-cv.idx[[i]], ]
  cv.valid_data <- train_data[cv.idx[[i]], ]
  # GBM modelini eğitin
  gbm_model <- gbm(Transported ~ ., data = cv.train_data, distribution = "bernoulli", n.trees = 100, interaction.depth = 5)
  # Eğitim verileri üzerinde doğruluk hesaplayın
  train_preds <- predict(gbm_model, newdata = cv.train_data, n.trees = 100, type = "response")
  train_pred_classes <- ifelse(train_preds > 0.5, 1, 0)
  train_accuracies[i] <- mean(train_pred_classes == cv.train_data$Transported)
  # Doğrulama verileri üzerinde doğruluk hesaplayın
  valid_preds <- predict(gbm_model, newdata = cv.valid_data, n.trees = 100, type = "response")
  valid_pred_classes <- ifelse(valid_preds > 0.5, 1, 0)
  valid_accuracies[i] <- mean(valid_pred_classes == cv.valid_data$Transported)
}
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 12: RoomService_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 14: FoodCourt_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 16: ShoppingMall_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 18: Spa_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 20: VRDeck_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 12: RoomService_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 14: FoodCourt_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 16: ShoppingMall_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 18: Spa_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 20: VRDeck_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 12: RoomService_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 14: FoodCourt_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 16: ShoppingMall_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 18: Spa_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 20: VRDeck_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 12: RoomService_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 14: FoodCourt_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 16: ShoppingMall_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 18: Spa_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 20: VRDeck_isna_indicator has no variation.
# Eğitim ve doğrulama doğruluklarını yazdırdık
cat("Eğitim Doğrulukları:", train_accuracies, "\n")
## Eğitim Doğrulukları: 0.8255867 0.824513 0.8240528 0.8212916
cat("Doğrulama Doğrulukları:", valid_accuracies, "\n")
## Doğrulama Doğrulukları: 0.7910723 0.8108606 0.8011965 0.8140819
# Ortalama eğitim ve doğrulama doğruluklarını hesapladık
mean_train_accuracy <- mean(train_accuracies)
mean_valid_accuracy <- mean(valid_accuracies)
# Ortalama eğitim ve doğrulama doğruluklarını yazdırdık
cat("Ortalama Eğitim Doğruluğu:", mean_train_accuracy, "\n")
## Ortalama Eğitim Doğruluğu: 0.823861
cat("Ortalama Doğrulama Doğruluğu:", mean_valid_accuracy, "\n")
## Ortalama Doğrulama Doğruluğu: 0.8043028
# GBM modelini eğittik (Varsayılan olarak GBM modeli kullanıldı)

gbm_model <- gbm(Transported ~ ., data = train_data, distribution = "bernoulli", n.trees = 100)
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 12: RoomService_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 14: FoodCourt_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 16: ShoppingMall_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 18: Spa_isna_indicator has no variation.
## Warning in gbm.fit(x = x, y = y, offset = offset, distribution = distribution,
## : variable 20: VRDeck_isna_indicator has no variation.
# Yeni verileri bir veri çerçevesine dönüştürün
test_data_frame <- data.frame(test_data)

# Tahminler yapmak için veri çerçevesini kullandık
gbm_preds_test <- predict(gbm_model, newdata = test_data_frame, type = "response")
## Using 100 trees...
# Tahminleri sınıf etiketlerine dönüştürdük (örneğin, 0 ve 1)
gbm_pred_classes_test <- ifelse(gbm_preds_test > 0.5, 1, 0)

# Tahmin sonuçlarını inceledik
head(gbm_pred_classes_test)
## [1] 1 0 1 1 0 0