## Spaceship Titanic

Hoş geldiniz 2912 yılına, burada veri bilimi becerileriniz, kozmik bir gizemi çözmek için gerekiyor. Dört ışık yılı uzaklıktan bir ileti aldık ve durum pek iç açıcı görünmüyor.

Bir ay önce fırlatılan Uzay Gemisi Titanic, yaklaşık 13,000 yolcuyla donatılmış yıldızlar arası bir yolcu gemisiydi. Gemi, güneş sistemimizden göçmenleri taşıyarak üç yeni yerleşilebilir ekzoplanete doğru ilk seyahatine çıktı. Ancak, Alpha Centauri’yi dönerken, ilk hedefi olan sıcak 55 Cancri E’ye doğru yol alırken, dikkatsiz Spaceship Titanic, bir toz bulutu içinde gizlenmiş bir uzay-zaman anomaliyle çarpıştı. Ne yazık ki, gemi, adını aldığı isim kardeşi gibi benzer bir kaderle karşılaştı. Gemisi sağlam kalsa da, neredeyse yolcuların yarısı alternatif bir boyuta taşındı!

Yorum: Bu öykü, uzak bir gelecekte geçen bilim kurgu ve macera temasına sahip. Veri bilimi becerileri, gizemli bir olayı çözmek için kullanılacak gibi görünüyor. Geminin çarpışması ve yolcuların alternatif bir boyuta taşınması, olaylara heyecan ve dramatizm katıyor.

train.csv - Eğitim verisi olarak kullanılacak yaklaşık üçte ikisi (~8700) yolcunun kişisel kayıtları. PassengerId - Her yolcu için benzersiz bir kimlik. Her kimlik, gggg_pp biçiminde olup, gggg, yolcu ile seyahat eden grubu gösterir ve pp grup içindeki sıralarını belirtir. Bir gruptaki insanlar genellikle aile üyeleri olabilir, ancak her zaman değil.

HomePlanet - Yolcunun hareket ettiği gezegen, genellikle kalıcı ikamet gezegenidir.

CryoSleep - Yolcunun seyahat süresince süspansiyon animasyonuna girmeyi seçip seçmediğini belirtir. CryoSleep’teki yolcular kabinlerine kapatılır.

Cabin - Yolcunun konakladığı kabin numarası. deck/num/side biçiminde olup, side Port için P veya Starboard için S olabilir.

Destination - Yolcunun iniş yapacağı gezegen.

Age - Yolcunun yaşı.

VIP - Yolcunun seyahat süresince özel VIP hizmeti için ödeme yapıp yapmadığını belirtir.

RoomService, FoodCourt, ShoppingMall, Spa, VRDeck - Yolcunun Spaceship Titanic’in birçok lüks olanaklarında her birinde ne kadar harcama yaptığını belirtir.

Name - Yolcunun adı ve soyadı.

Transported - Yolcunun başka bir boyuta taşınıp taşınmadığını belirten hedef, tahmin etmeye çalıştığınız sütun.

test.csv - Test verisi olarak kullanılacak geri kalan üçte biri (~4300) yolcunun kişisel kayıtları. Göreviniz, bu setteki yolcuların Transported değerini tahmin etmektir.

sample_submission.csv - Doğru formatta bir gönderi dosyası.

PassengerId - Test setindeki her yolcu için bir kimlik.

Transported - Hedef. Her yolcu için True veya False tahmin.

library(readr)
test <- read_csv("test.csv")
## Rows: 4277 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): PassengerId, HomePlanet, Cabin, Destination, Name
## dbl (6): Age, RoomService, FoodCourt, ShoppingMall, Spa, VRDeck
## lgl (2): CryoSleep, VIP
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
View(test)
View(test)
library(readr)
train <- read_csv("train.csv")
## Rows: 8693 Columns: 14
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): PassengerId, HomePlanet, Cabin, Destination, Name
## dbl (6): Age, RoomService, FoodCourt, ShoppingMall, Spa, VRDeck
## lgl (3): CryoSleep, VIP, Transported
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
View(train)
View(train)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ purrr     1.0.2
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ── 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
library(explore)
train %>% describe_all()
## # A tibble: 14 × 8
##    variable     type     na na_pct unique   min   mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl>  <dbl> <dbl>
##  1 PassengerId  chr       0    0     8693    NA  NA       NA
##  2 HomePlanet   chr     201    2.3      4    NA  NA       NA
##  3 CryoSleep    lgl     217    2.5      3     0   0.36     1
##  4 Cabin        chr     199    2.3   6561    NA  NA       NA
##  5 Destination  chr     182    2.1      4    NA  NA       NA
##  6 Age          dbl     179    2.1     81     0  28.8     79
##  7 VIP          lgl     203    2.3      3     0   0.02     1
##  8 RoomService  dbl     181    2.1   1274     0 225.   14327
##  9 FoodCourt    dbl     183    2.1   1508     0 458.   29813
## 10 ShoppingMall dbl     208    2.4   1116     0 174.   23492
## 11 Spa          dbl     183    2.1   1328     0 311.   22408
## 12 VRDeck       dbl     188    2.2   1307     0 305.   24133
## 13 Name         chr     200    2.3   8474    NA  NA       NA
## 14 Transported  lgl       0    0        2     0   0.5      1

Bu ifade, “train” adlı bir veri çerçevesi veya veri seti üzerinde işlem yapmayı amaçlamaktadır. describe_all() fonksiyonu, bir veri çerçevesinin tüm değişkenlerinin özet istatistiklerini oluşturan bir fonksiyondur.

Düzenlemeleri yapmak için kodları giriyoruz

test[c('ailenum', 'ailesira')] <- str_split_fixed(test$PassengerId, "_", 2)
train[c('ailenum', 'ailesira')] <- str_split_fixed(train$PassengerId, "_", 2)
train[c('deck', 'num', 'side')] <- str_split_fixed(train$Cabin, '/', 3)
test[c('deck', 'num', 'side')] <- str_split_fixed(test$Cabin, '/', 3)
train[train == ''] <- NA
test[test == ''] <- NA

Boşluklara NA demesini söyledik

train <- train %>% select(-Cabin)
test  <- test %>% select(-Cabin)
unique(train$HomePlanet)
## [1] "Europa" "Earth"  "Mars"   NA

NA yı biz ekledik

train$HomePlanet <- addNA(train$HomePlanet)
test$HomePlanet <- addNA(test$HomePlanet)
levels(train$HomePlanet)
## [1] "Earth"  "Europa" "Mars"   NA
levels(train$HomePlanet)[is.na(levels(train$HomePlanet))] <- "NA"
levels(test$HomePlanet)[is.na(levels(test$HomePlanet))] <- "NA"
levels(train$HomePlanet)
## [1] "Earth"  "Europa" "Mars"   "NA"
train %>% describe_all()
## # A tibble: 18 × 8
##    variable     type     na na_pct unique   min   mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl>  <dbl> <dbl>
##  1 PassengerId  chr       0    0     8693    NA  NA       NA
##  2 HomePlanet   fct       0    0        4    NA  NA       NA
##  3 CryoSleep    lgl     217    2.5      3     0   0.36     1
##  4 Destination  chr     182    2.1      4    NA  NA       NA
##  5 Age          dbl     179    2.1     81     0  28.8     79
##  6 VIP          lgl     203    2.3      3     0   0.02     1
##  7 RoomService  dbl     181    2.1   1274     0 225.   14327
##  8 FoodCourt    dbl     183    2.1   1508     0 458.   29813
##  9 ShoppingMall dbl     208    2.4   1116     0 174.   23492
## 10 Spa          dbl     183    2.1   1328     0 311.   22408
## 11 VRDeck       dbl     188    2.2   1307     0 305.   24133
## 12 Name         chr     200    2.3   8474    NA  NA       NA
## 13 Transported  lgl       0    0        2     0   0.5      1
## 14 ailenum      chr       0    0     6217    NA  NA       NA
## 15 ailesira     chr       0    0        8    NA  NA       NA
## 16 deck         chr     199    2.3      9    NA  NA       NA
## 17 num          chr     199    2.3   1818    NA  NA       NA
## 18 side         chr     199    2.3      3    NA  NA       NA

NA larda oynama yapacağız

train <- train %>%
  group_by(HomePlanet,Destination) %>%
  mutate_at(vars(Age), ~replace_na(., mean(., na.rm = TRUE)))
test <- test %>%
  group_by(HomePlanet,Destination) %>%
  mutate_at(vars(Age), ~replace_na(., mean(., na.rm = TRUE)))
train$CryoSleep <- addNA(train$CryoSleep)
test$CryoSleep <- addNA(test$CryoSleep)
levels(train$CryoSleep)[is.na(levels(train$CryoSleep))] <- "NA"
levels(test$CryoSleep)[is.na(levels(test$CryoSleep))] <- "NA"
train %>% describe_all()
## # A tibble: 18 × 8
##    variable     type     na na_pct unique   min   mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl>  <dbl> <dbl>
##  1 PassengerId  chr       0    0     8693    NA  NA       NA
##  2 HomePlanet   fct       0    0        4    NA  NA       NA
##  3 CryoSleep    fct       0    0        3    NA  NA       NA
##  4 Destination  chr     182    2.1      4    NA  NA       NA
##  5 Age          dbl       0    0       91     0  28.8     79
##  6 VIP          lgl     203    2.3      3     0   0.02     1
##  7 RoomService  dbl     181    2.1   1274     0 225.   14327
##  8 FoodCourt    dbl     183    2.1   1508     0 458.   29813
##  9 ShoppingMall dbl     208    2.4   1116     0 174.   23492
## 10 Spa          dbl     183    2.1   1328     0 311.   22408
## 11 VRDeck       dbl     188    2.2   1307     0 305.   24133
## 12 Name         chr     200    2.3   8474    NA  NA       NA
## 13 Transported  lgl       0    0        2     0   0.5      1
## 14 ailenum      chr       0    0     6217    NA  NA       NA
## 15 ailesira     chr       0    0        8    NA  NA       NA
## 16 deck         chr     199    2.3      9    NA  NA       NA
## 17 num          chr     199    2.3   1818    NA  NA       NA
## 18 side         chr     199    2.3      3    NA  NA       NA
unique(train$Destination)
## [1] "TRAPPIST-1e"   "PSO J318.5-22" "55 Cancri e"   NA
train$Destination <- addNA(train$Destination)
test$Destination <- addNA(test$Destination)
levels(train$Destination)[is.na(levels(train$Destination))] <- "NA"
levels(test$Destination)[is.na(levels(test$Destination))] <- "NA"
train$side <- addNA(train$side)
test$side <- addNA(test$side)
levels(train$side)[is.na(levels(train$side))] <- "NA"
levels(test$side)[is.na(levels(test$side))] <- "NA"
test$VIP <- addNA(test$VIP)
train$VIP <- addNA(train$VIP)
levels(train$VIP)[is.na(levels(train$VIP))] <- "NA"
levels(test$VIP)[is.na(levels(test$VIP))] <- "NA"
train <- train %>%
  group_by(Destination) %>%
  mutate_at(vars(RoomService), ~replace_na(.,mean(.,na.rm = TRUE)))
test <- test %>%
  group_by(Destination) %>%
  mutate_at(vars(RoomService), ~replace_na(.,mean(.,na.rm = TRUE)))

replace_na() ve mean() fonksiyonları kullanılarak eksik değerleri değiştirme işlemi gerçekleştirilmektedir.

train %>% describe_all()
## # A tibble: 18 × 8
##    variable     type     na na_pct unique   min  mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl> <dbl> <dbl>
##  1 PassengerId  chr       0    0     8693    NA  NA      NA
##  2 HomePlanet   fct       0    0        4    NA  NA      NA
##  3 CryoSleep    fct       0    0        3    NA  NA      NA
##  4 Destination  fct       0    0        4    NA  NA      NA
##  5 Age          dbl       0    0       91     0  28.8    79
##  6 VIP          fct       0    0        3    NA  NA      NA
##  7 RoomService  dbl       0    0     1277     0 225.  14327
##  8 FoodCourt    dbl     183    2.1   1508     0 458.  29813
##  9 ShoppingMall dbl     208    2.4   1116     0 174.  23492
## 10 Spa          dbl     183    2.1   1328     0 311.  22408
## 11 VRDeck       dbl     188    2.2   1307     0 305.  24133
## 12 Name         chr     200    2.3   8474    NA  NA      NA
## 13 Transported  lgl       0    0        2     0   0.5     1
## 14 ailenum      chr       0    0     6217    NA  NA      NA
## 15 ailesira     chr       0    0        8    NA  NA      NA
## 16 deck         chr     199    2.3      9    NA  NA      NA
## 17 num          chr     199    2.3   1818    NA  NA      NA
## 18 side         fct       0    0        3    NA  NA      NA
hist(train$FoodCourt)

train <- train %>% mutate(FoodCourt = coalesce(FoodCourt, 0))
test <- test %>% mutate(FoodCourt = coalesce(FoodCourt, 0))
train <- train %>% mutate(ShoppingMall = coalesce(ShoppingMall, 0),
                         Spa = coalesce(Spa, 0),
                          VRDeck = coalesce(VRDeck, 0))
test <- test %>% mutate(ShoppingMall = coalesce(ShoppingMall, 0),
                         Spa = coalesce(Spa, 0),
                          VRDeck = coalesce(VRDeck, 0))
train <- train %>% select(-Name)
test <- test %>% select(-Name)
train %>% describe_all()
## # A tibble: 17 × 8
##    variable     type     na na_pct unique   min  mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl> <dbl> <dbl>
##  1 PassengerId  chr       0    0     8693    NA  NA      NA
##  2 HomePlanet   fct       0    0        4    NA  NA      NA
##  3 CryoSleep    fct       0    0        3    NA  NA      NA
##  4 Destination  fct       0    0        4    NA  NA      NA
##  5 Age          dbl       0    0       91     0  28.8    79
##  6 VIP          fct       0    0        3    NA  NA      NA
##  7 RoomService  dbl       0    0     1277     0 225.  14327
##  8 FoodCourt    dbl       0    0     1507     0 448.  29813
##  9 ShoppingMall dbl       0    0     1115     0 170.  23492
## 10 Spa          dbl       0    0     1327     0 305.  22408
## 11 VRDeck       dbl       0    0     1306     0 298.  24133
## 12 Transported  lgl       0    0        2     0   0.5     1
## 13 ailenum      chr       0    0     6217    NA  NA      NA
## 14 ailesira     chr       0    0        8    NA  NA      NA
## 15 deck         chr     199    2.3      9    NA  NA      NA
## 16 num          chr     199    2.3   1818    NA  NA      NA
## 17 side         fct       0    0        3    NA  NA      NA
train$deck <- addNA(train$deck)
test$deck <- addNA(test$deck)
levels(train$deck)[is.na(levels(train$deck))] <- "na"
levels(test$deck)[is.na(levels(test$deck))] <- "na"
train %>% describe_all()
## # A tibble: 17 × 8
##    variable     type     na na_pct unique   min  mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl> <dbl> <dbl>
##  1 PassengerId  chr       0    0     8693    NA  NA      NA
##  2 HomePlanet   fct       0    0        4    NA  NA      NA
##  3 CryoSleep    fct       0    0        3    NA  NA      NA
##  4 Destination  fct       0    0        4    NA  NA      NA
##  5 Age          dbl       0    0       91     0  28.8    79
##  6 VIP          fct       0    0        3    NA  NA      NA
##  7 RoomService  dbl       0    0     1277     0 225.  14327
##  8 FoodCourt    dbl       0    0     1507     0 448.  29813
##  9 ShoppingMall dbl       0    0     1115     0 170.  23492
## 10 Spa          dbl       0    0     1327     0 305.  22408
## 11 VRDeck       dbl       0    0     1306     0 298.  24133
## 12 Transported  lgl       0    0        2     0   0.5     1
## 13 ailenum      chr       0    0     6217    NA  NA      NA
## 14 ailesira     chr       0    0        8    NA  NA      NA
## 15 deck         fct       0    0        9    NA  NA      NA
## 16 num          chr     199    2.3   1818    NA  NA      NA
## 17 side         fct       0    0        3    NA  NA      NA
test%>% describe_all()
## # A tibble: 16 × 8
##    variable     type     na na_pct unique   min  mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl> <dbl> <dbl>
##  1 PassengerId  chr       0    0     4277    NA  NA      NA
##  2 HomePlanet   fct       0    0        4    NA  NA      NA
##  3 CryoSleep    fct       0    0        3    NA  NA      NA
##  4 Destination  fct       0    0        4    NA  NA      NA
##  5 Age          dbl       0    0       91     0  28.7    79
##  6 VIP          fct       0    0        3    NA  NA      NA
##  7 RoomService  dbl       0    0      846     0 219.  11567
##  8 FoodCourt    dbl       0    0      902     0 429.  25273
##  9 ShoppingMall dbl       0    0      715     0 173.   8292
## 10 Spa          dbl       0    0      833     0 296.  19844
## 11 VRDeck       dbl       0    0      796     0 305.  22272
## 12 ailenum      chr       0    0     3063    NA  NA      NA
## 13 ailesira     chr       0    0        8    NA  NA      NA
## 14 deck         fct       0    0        9    NA  NA      NA
## 15 num          chr     100    2.3   1506    NA  NA      NA
## 16 side         fct       0    0        3    NA  NA      NA
train$aile <- ifelse(duplicated(train$ailenum) | duplicated(train$ailenum,fromLast = TRUE), 1, 0)
test$aile <- ifelse(duplicated(test$ailenum) | duplicated(test$ailenum,fromLast = TRUE), 1, 0)

Bu R kodu, “train” ve “test” veri çerçevelerine yeni bir “aile” adlı sütun eklemeyi amaçlar. Bu yeni sütun, her bir gözlem için “ailenum” değişkenindeki değerin daha önce görülüp görülmediğini kontrol eder ve buna göre 1 veya 0 değerini atar.

train <- train %>% select(-c(ailenum, ailesira, num))
test<- test %>% select(-c(ailenum, ailesira, num))

Bu R kodu, “test” veri çerçevesinden “ailenum”, “ailesira” ve “num” sütunlarını çıkarmayı amaçlar. Bu tür bir işlem, belirli sütunları veri çerçevesinden kaldırmak ve veri setini temizlemek için kullanılır Burada işimize yaramadığımız için sildik.

train %>% describe_all()
## # A tibble: 15 × 8
##    variable     type     na na_pct unique   min   mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl>  <dbl> <dbl>
##  1 PassengerId  chr       0      0   8693    NA  NA       NA
##  2 HomePlanet   fct       0      0      4    NA  NA       NA
##  3 CryoSleep    fct       0      0      3    NA  NA       NA
##  4 Destination  fct       0      0      4    NA  NA       NA
##  5 Age          dbl       0      0     91     0  28.8     79
##  6 VIP          fct       0      0      3    NA  NA       NA
##  7 RoomService  dbl       0      0   1277     0 225.   14327
##  8 FoodCourt    dbl       0      0   1507     0 448.   29813
##  9 ShoppingMall dbl       0      0   1115     0 170.   23492
## 10 Spa          dbl       0      0   1327     0 305.   22408
## 11 VRDeck       dbl       0      0   1306     0 298.   24133
## 12 Transported  lgl       0      0      2     0   0.5      1
## 13 deck         fct       0      0      9    NA  NA       NA
## 14 side         fct       0      0      3    NA  NA       NA
## 15 aile         dbl       0      0      2     0   0.45     1
test %>% describe_all()
## # A tibble: 14 × 8
##    variable     type     na na_pct unique   min   mean   max
##    <chr>        <chr> <int>  <dbl>  <int> <dbl>  <dbl> <dbl>
##  1 PassengerId  chr       0      0   4277    NA  NA       NA
##  2 HomePlanet   fct       0      0      4    NA  NA       NA
##  3 CryoSleep    fct       0      0      3    NA  NA       NA
##  4 Destination  fct       0      0      4    NA  NA       NA
##  5 Age          dbl       0      0     91     0  28.7     79
##  6 VIP          fct       0      0      3    NA  NA       NA
##  7 RoomService  dbl       0      0    846     0 219.   11567
##  8 FoodCourt    dbl       0      0    902     0 429.   25273
##  9 ShoppingMall dbl       0      0    715     0 173.    8292
## 10 Spa          dbl       0      0    833     0 296.   19844
## 11 VRDeck       dbl       0      0    796     0 305.   22272
## 12 deck         fct       0      0      9    NA  NA       NA
## 13 side         fct       0      0      3    NA  NA       NA
## 14 aile         dbl       0      0      2     0   0.45     1

Tahminlerim

Logistik Regresyon

Logistik regresyon, sınıflandırma problemlerinde kullanılan bir istatistiksel modelleme tekniğidir. Genellikle iki kategorili (binary) bağımlı değişkenlerle çalışır ve bir olayın olasılığını tahmin etmek için kullanılır. Örneğin, bir öğrencinin bir sınavı geçip geçmemesi, bir e-postanın spam olup olmaması gibi durumlar logistik regresyon ile modellelenebilir.

Logistik regresyon, doğrusal regresyonun genelleştirilmiş bir formudur ve log-odds (logaritma oran) fonksiyonu üzerine kurulmuştur.

train_set <- train[2:15]
test_set <- test[2:14]
library(caTools)
set.seed(123)
split = sample.split(train_set$Transported, SplitRatio = 0.75)
training_set = subset(train_set, split == TRUE)
testing_set = subset(train_set, split == FALSE)
logistic = glm(formula = Transported ~ .,
               family = binomial,
               data = training_set)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
prob_pred = predict(logistic, type = 'response', newdata = testing_set[-11])
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type = if (type == :
## prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases
y_pred = ifelse(prob_pred > 0.5, 1, 0)
y_true <- ifelse(testing_set[11] == TRUE, 1, 0)
cm = table(y_true, y_pred)
cm
##       y_pred
## y_true   0   1
##      0 819 260
##      1 189 905
(819+905)/(819+905+260+189)
## [1] 0.7933732
logistic_son = glm(formula = Transported ~ .,
                   family = binomial,
                   data = train_set)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
prob_pred = predict(logistic_son, type = 'response', newdata = test_set)
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type = if (type == :
## prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases
y_pred = ifelse(prob_pred > 0.5, TRUE, FALSE)
Transported <- as.character(y_pred)
PassengerId <- test$PassengerId
Transported <-as.vector(Transported)
sample_submission <- cbind(PassengerId, Transported)
sample_submission <- as.data.frame(sample_submission)
library(stringr)
sample_submission$Transported <- str_to_title(sample_submission$Transported)
write.csv(sample_submission, "sub_logistic.csv", row.names = FALSE, 
quote = FALSE)

Decision Trees

Decision Trees (Karar Ağaçları), sınıflandırma ve regresyon problemleri için kullanılan bir makine öğrenimi algoritmasıdır. Bu algoritma, bir dizi karar aşamasından oluşur ve veri kümesini küçük alt kümelerine bölerek bir tahmin yapmaya çalışır.

Karar ağaçları, bir ağaç yapısında temsil edilir, her bir düğüm (node) bir karar noktasını, her bir dal (branch) bir kararın çıkışını ve her bir yaprak (leaf) düğümü de bir tahmini temsil eder. Ağacın tepesinde (kök düğümü), veri kümesini en iyi şekilde bölmek için en önemli özellik (feature) seçilir.

library(rpart)
library(rpart.plot)
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
library(caret)
## Zorunlu paket yükleniyor: lattice
## 
## Attaching package: 'caret'
## The following object is masked from 'package:purrr':
## 
##     lift
training_set$Transported <- as.factor(training_set$Transported)
testing_set$Transported <- as.factor(testing_set$Transported)
train_set$Transported <- as.factor(train_set$Transported)
fit_tree <- rpart(Transported ~ ., data = training_set)
summary(fit_tree)
## Call:
## rpart(formula = Transported ~ ., data = training_set)
##   n= 6520 
## 
##           CP nsplit rel error    xerror       xstd
## 1 0.43016069      0 1.0000000 1.0000000 0.01247595
## 2 0.03574372      1 0.5698393 0.5698393 0.01123791
## 3 0.01000000      4 0.4626082 0.4663164 0.01052385
## 
## Variable importance
##    CryoSleep          Spa       VRDeck  RoomService    FoodCourt ShoppingMall 
##           43           16           15           12            7            4 
##   HomePlanet         deck 
##            2            1 
## 
## Node number 1: 6520 observations,    complexity param=0.4301607
##   predicted class=TRUE   expected loss=0.496319  P(node) =1
##     class counts:  3236  3284
##    probabilities: 0.496 0.504 
##   left son=2 (4240 obs) right son=3 (2280 obs)
##   Primary splits:
##       CryoSleep    splits as  LRL,        improve=683.0583, (0 missing)
##       RoomService  < 0.5    to the right, improve=412.4664, (0 missing)
##       Spa          < 0.5    to the right, improve=372.3306, (0 missing)
##       VRDeck       < 0.5    to the right, improve=353.3889, (0 missing)
##       ShoppingMall < 0.5    to the right, improve=228.9794, (0 missing)
##   Surrogate splits:
##       Spa          < 0.5    to the right, agree=0.716, adj=0.188, (0 split)
##       FoodCourt    < 0.5    to the right, agree=0.702, adj=0.148, (0 split)
##       VRDeck       < 0.5    to the right, agree=0.700, adj=0.141, (0 split)
##       RoomService  < 0.5    to the right, agree=0.696, adj=0.130, (0 split)
##       ShoppingMall < 0.5    to the right, agree=0.686, adj=0.101, (0 split)
## 
## Node number 2: 4240 observations,    complexity param=0.03574372
##   predicted class=FALSE  expected loss=0.3358491  P(node) =0.6503067
##     class counts:  2816  1424
##    probabilities: 0.664 0.336 
##   left son=4 (1087 obs) right son=5 (3153 obs)
##   Primary splits:
##       RoomService < 343    to the right, improve=104.04900, (0 missing)
##       Age         < 12.5   to the right, improve= 87.14388, (0 missing)
##       Spa         < 241.5  to the right, improve= 84.79330, (0 missing)
##       FoodCourt   < 2168   to the left,  improve= 67.12339, (0 missing)
##       VRDeck      < 420.5  to the right, improve= 58.17805, (0 missing)
##   Surrogate splits:
##       HomePlanet splits as  RRLR,       agree=0.788, adj=0.175, (0 split)
##       deck       splits as  RRRLRRRRR,  agree=0.748, adj=0.016, (0 split)
##       Age        < 78.5   to the right, agree=0.744, adj=0.002, (0 split)
## 
## Node number 3: 2280 observations
##   predicted class=TRUE   expected loss=0.1842105  P(node) =0.3496933
##     class counts:   420  1860
##    probabilities: 0.184 0.816 
## 
## Node number 4: 1087 observations
##   predicted class=FALSE  expected loss=0.1471941  P(node) =0.1667178
##     class counts:   927   160
##    probabilities: 0.853 0.147 
## 
## Node number 5: 3153 observations,    complexity param=0.03574372
##   predicted class=FALSE  expected loss=0.400888  P(node) =0.483589
##     class counts:  1889  1264
##    probabilities: 0.599 0.401 
##   left son=10 (1034 obs) right son=11 (2119 obs)
##   Primary splits:
##       Spa          < 205    to the right, improve=131.21170, (0 missing)
##       VRDeck       < 135.5  to the right, improve=103.53150, (0 missing)
##       Age          < 12.5   to the right, improve= 60.28573, (0 missing)
##       ShoppingMall < 790.5  to the left,  improve= 45.61195, (0 missing)
##       FoodCourt    < 2200.5 to the left,  improve= 45.01959, (0 missing)
##   Surrogate splits:
##       HomePlanet splits as  RLRR,       agree=0.699, adj=0.081, (0 split)
##       deck       splits as  LRLRRRRLR,  agree=0.687, adj=0.044, (0 split)
##       VRDeck     < 2794.5 to the right, agree=0.676, adj=0.014, (0 split)
##       FoodCourt  < 3197.5 to the right, agree=0.676, adj=0.012, (0 split)
##       Age        < 59.5   to the right, agree=0.673, adj=0.002, (0 split)
## 
## Node number 10: 1034 observations
##   predicted class=FALSE  expected loss=0.1943907  P(node) =0.158589
##     class counts:   833   201
##    probabilities: 0.806 0.194 
## 
## Node number 11: 2119 observations,    complexity param=0.03574372
##   predicted class=TRUE   expected loss=0.4983483  P(node) =0.325
##     class counts:  1056  1063
##    probabilities: 0.498 0.502 
##   left son=22 (604 obs) right son=23 (1515 obs)
##   Primary splits:
##       VRDeck       < 363.5  to the right, improve=135.42270, (0 missing)
##       FoodCourt    < 2071   to the left,  improve= 50.37469, (0 missing)
##       HomePlanet   splits as  LRRL,       improve= 40.97469, (0 missing)
##       ShoppingMall < 1540.5 to the left,  improve= 31.65683, (0 missing)
##       Age          < 10.5   to the right, improve= 29.32195, (0 missing)
##   Surrogate splits:
##       FoodCourt < 7197.5 to the right, agree=0.717, adj=0.008, (0 split)
##       deck      splits as  RRLRRRRRR,  agree=0.716, adj=0.003, (0 split)
##       Age       < 68.5   to the right, agree=0.715, adj=0.002, (0 split)
## 
## Node number 22: 604 observations
##   predicted class=FALSE  expected loss=0.218543  P(node) =0.09263804
##     class counts:   472   132
##    probabilities: 0.781 0.219 
## 
## Node number 23: 1515 observations
##   predicted class=TRUE   expected loss=0.3854785  P(node) =0.232362
##     class counts:   584   931
##    probabilities: 0.385 0.615
rpart.plot(fit_tree)

preds = predict(fit_tree, newdata = testing_set[-11], type = "class")
y_pred = ifelse(preds == TRUE, 1, 0)
cm = table(y_true, y_pred)
cm
##       y_pred
## y_true   0   1
##      0 735 344
##      1 170 924
(735 + 924)/2173
## [1] 0.7634607
fit_tree <- rpart(Transported ~ ., data = train_set)
summary(fit_tree)
## Call:
## rpart(formula = Transported ~ ., data = train_set)
##   n= 8693 
## 
##           CP nsplit rel error    xerror        xstd
## 1 0.43244496      0 1.0000000 1.0000000 0.010803454
## 2 0.03406721      1 0.5675550 0.5675550 0.009719864
## 3 0.01000000      4 0.4653534 0.4690614 0.009132086
## 
## Variable importance
##    CryoSleep          Spa       VRDeck  RoomService    FoodCourt ShoppingMall 
##           45           17           15           11            7            4 
##   HomePlanet 
##            1 
## 
## Node number 1: 8693 observations,    complexity param=0.432445
##   predicted class=TRUE   expected loss=0.4963764  P(node) =1
##     class counts:  4315  4378
##    probabilities: 0.496 0.504 
##   left son=2 (5656 obs) right son=3 (3037 obs)
##   Primary splits:
##       CryoSleep    splits as  LRL,         improve=920.2004, (0 missing)
##       RoomService  < 0.5     to the right, improve=523.3930, (0 missing)
##       Spa          < 0.5     to the right, improve=514.4709, (0 missing)
##       VRDeck       < 0.5     to the right, improve=479.5694, (0 missing)
##       ShoppingMall < 0.5     to the right, improve=302.4414, (0 missing)
##   Surrogate splits:
##       Spa          < 0.5     to the right, agree=0.716, adj=0.187, (0 split)
##       FoodCourt    < 0.5     to the right, agree=0.701, adj=0.143, (0 split)
##       VRDeck       < 0.5     to the right, agree=0.696, adj=0.129, (0 split)
##       RoomService  < 0.5     to the right, agree=0.692, adj=0.119, (0 split)
##       ShoppingMall < 0.5     to the right, agree=0.683, adj=0.092, (0 split)
## 
## Node number 2: 5656 observations,    complexity param=0.03406721
##   predicted class=FALSE  expected loss=0.3350424  P(node) =0.6506384
##     class counts:  3761  1895
##    probabilities: 0.665 0.335 
##   left son=4 (1432 obs) right son=5 (4224 obs)
##   Primary splits:
##       RoomService < 346.5   to the right, improve=121.39640, (0 missing)
##       Spa         < 266.5   to the right, improve=113.99320, (0 missing)
##       Age         < 12.5    to the right, improve=109.40550, (0 missing)
##       FoodCourt   < 1331    to the left,  improve= 98.11980, (0 missing)
##       VRDeck      < 417.5   to the right, improve= 75.47684, (0 missing)
##   Surrogate splits:
##       HomePlanet splits as  RRLR,        agree=0.785, adj=0.151, (0 split)
##       deck       splits as  RRRLRRRRR,   agree=0.749, adj=0.007, (0 split)
##       Age        < 78.5    to the right, agree=0.747, adj=0.001, (0 split)
## 
## Node number 3: 3037 observations
##   predicted class=TRUE   expected loss=0.1824169  P(node) =0.3493616
##     class counts:   554  2483
##    probabilities: 0.182 0.818 
## 
## Node number 4: 1432 observations
##   predicted class=FALSE  expected loss=0.1571229  P(node) =0.1647302
##     class counts:  1207   225
##    probabilities: 0.843 0.157 
## 
## Node number 5: 4224 observations,    complexity param=0.03406721
##   predicted class=FALSE  expected loss=0.3953598  P(node) =0.4859082
##     class counts:  2554  1670
##    probabilities: 0.605 0.395 
##   left son=10 (1391 obs) right son=11 (2833 obs)
##   Primary splits:
##       Spa          < 205     to the right, improve=168.00700, (0 missing)
##       VRDeck       < 135.5   to the right, improve=129.77700, (0 missing)
##       Age          < 12.5    to the right, improve= 76.46367, (0 missing)
##       FoodCourt    < 2507.5  to the left,  improve= 63.32833, (0 missing)
##       ShoppingMall < 627     to the left,  improve= 59.33765, (0 missing)
##   Surrogate splits:
##       HomePlanet splits as  RLRR,        agree=0.695, adj=0.073, (0 split)
##       deck       splits as  LRLRRRRLR,   agree=0.684, adj=0.042, (0 split)
##       FoodCourt  < 3197.5  to the right, agree=0.676, adj=0.017, (0 split)
##       VRDeck     < 2052    to the right, agree=0.673, adj=0.006, (0 split)
##       Age        < 75.5    to the right, agree=0.672, adj=0.003, (0 split)
## 
## Node number 10: 1391 observations
##   predicted class=FALSE  expected loss=0.194105  P(node) =0.1600138
##     class counts:  1121   270
##    probabilities: 0.806 0.194 
## 
## Node number 11: 2833 observations,    complexity param=0.03406721
##   predicted class=FALSE  expected loss=0.4941758  P(node) =0.3258944
##     class counts:  1433  1400
##    probabilities: 0.506 0.494 
##   left son=22 (814 obs) right son=23 (2019 obs)
##   Primary splits:
##       VRDeck       < 355     to the right, improve=185.97790, (0 missing)
##       FoodCourt    < 2069.5  to the left,  improve= 64.45210, (0 missing)
##       HomePlanet   splits as  LRRL,        improve= 46.60726, (0 missing)
##       ShoppingMall < 1540.5  to the left,  improve= 38.47446, (0 missing)
##       Age          < 7.5     to the right, improve= 36.46439, (0 missing)
##   Surrogate splits:
##       FoodCourt   < 10134.5 to the right, agree=0.715, adj=0.007, (0 split)
##       Age         < 68.5    to the right, agree=0.714, adj=0.004, (0 split)
##       deck        splits as  RRLRRRRRR,   agree=0.714, adj=0.004, (0 split)
##       RoomService < 343     to the right, agree=0.713, adj=0.001, (0 split)
## 
## Node number 22: 814 observations
##   predicted class=FALSE  expected loss=0.2088452  P(node) =0.09363856
##     class counts:   644   170
##    probabilities: 0.791 0.209 
## 
## Node number 23: 2019 observations
##   predicted class=TRUE   expected loss=0.3907875  P(node) =0.2322558
##     class counts:   789  1230
##    probabilities: 0.391 0.609
rpart.plot(fit_tree)

preds = predict(fit_tree, newdata = test_set, type = "class")
y_pred = ifelse(preds == TRUE, TRUE, FALSE)
Transported <- as.character(y_pred)
PassengerId <- test$PassengerId
Transported <- as.vector(Transported)
sample_submission <- cbind(PassengerId, Transported)
sample_submission <- as.data.frame(sample_submission)
sample_submission$Transported <- str_to_title(sample_submission$Transported)
write.csv(sample_submission, "sample_submission_dt.csv", row.names = FALSE, quote = FALSE)