##Spacship Titanik 2912 yılına hoş geldiniz ve uzay gemisi Titanik’in kozmik bir gizemi çözmek için veri bilimi becerilerine ihtiyaç duyulmaktadır. Dört ışık yılı öteden alınan bir sinyal, geminin kavurucu 55 Cancri E gezegenine gitmek üzere yola çıktığı yolculuğunda Alpha Centauri’nin dönüşünde bir uzay-zaman anormalliğiyle karşılaştığını ve yolcuların neredeyse yarısının alternatif bir boyuta taşındığını ortaya koymaktadır.

Aşağıda, eğitim verisi olan “train.csv” ve tahmin yapmanız gereken test verisi olan “test.csv” dosyalarının içeriği ve veri alanlarının açıklamaları bulunmaktadır:

train.csv - Kişisel kayıtlar, eğitim verisi olarak kullanılacak olan yaklaşık üçte ikisi (~8700) yolcunun bilgilerini içerir.

PassengerId: Her yolcu için benzersiz bir kimlik. Her kimlik “gggg_pp” biçimindedir, burada “gggg” yolcunun seyahat ettiği grubu gösterir ve “pp” ise gruptaki sıralarını belirtir.

HomePlanet: Yolcunun ayrıldığı gezegen, genellikle kalıcı ikamet gezegenidir.

CryoSleep: Yolcunun yolculuğun süresince dondurulmuş animasyona geçip geçmeyeceğini gösterir. Cryosleep’teki yolcular kabinlerine kapatılır.

Cabin: Yolcunun konakladığı kabin numarası. “deck/num/side” biçimindedir ve “side” P (Port) veya S (Starboard) olabilir.

Destination: Yolcunun iniş yapacağı gezegen.

Age: Yolcunun yaşı.

VIP: Yolcunun yolculuk sırasında ö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 ne kadar harcama yaptığını gösterir.

Name: Yolcunun adı ve soyadı

Transported: Yolcunun başka bir boyuta taşınıp taşınmadığını belirtir. Bu, tahmin etmeye çalıştığınız sütundur.

test.csv - Geri kalan üçte birlik (~4300) yolcunun kişisel kayıtlarını içerir, test verisi olarak kullanılacaktır.

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

(Diğer alanlar): Aynı şekilde eğitim verisi ile benzer şekilde bilgiler içerir.

Göreviniz, test setindeki yolcuların “Transported” değerini tahmin etmektir.

“Transported” sütununda her bir yolcu için True veya False tahmin yapmalısınız.

Ayrıca, “sample_submission.csv” dosyası, doğru formatta bir gönderim dosyasıdır ve bu formata uygun tahminlerinizi yapmalısınız. ## Download Data (Data Paketini Yüklemek)

library(readr): Bu satır, readr paketine yükler ve R’de veri okuma işlemleri için kullanıyoruz. train tablosu ‘read’

Dataset Description (Veri Kümesi Açıklaması)

Bu yarışma, Uzay Gemisi Titanik’in uzay-zaman anomalisi sırasında bir yolcunun alternatif bir boyuta taşınıp taşınmadığını öngörmekle ilgili. Bu öngörüleri yapabilmek için, geminin hasarlı bilgisayar sisteminden kurtarılan bir dizi kişisel kayıt sunulmuş durumda. Yani, geminin çarpışması sırasında yaşanan olayları ve yolcuların durumlarını anlamak ve bu kapsamda bir tahmin modeli oluşturmak amacıyla veri seti sağlanmış bulunuyor.

kaggle !den aldığım verileri yükledim

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.
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.

#####library(tidyverse) komutu, R programlama dilindeki birçok kullanışlı paketi tek bir adı altında yüklemeyi sağlar. “Tidyverse” dediğimiz şey, veri analizi ve görselleştirme için kullanılan bir grup paketi içerir.

Bu komutu kullanarak, bir kerede birçok kullanışlı aracı etkinleştirmiş olursunuz. Örneğin, “dplyr” paketi veri manipülasyonu için, “ggplot2” paketi grafik oluşturmak için ve “tidyr” paketi veri temizleme işlemleri için sıkça kullanılır.

train <- read_csv(“train.csv”): Bu satır “train.csv” CSV dosyasını okur ve verileri “train” adlı bir veri çerçevesinde saklar. Read_csv işlevi, readr paketinin bir parçasıdır ve CSV dosyalarını okumak için kullanılır.

Analiz ve işleme için hazır olan “test” adlı veri çerçevesi, şu anda analizler yapmak, veriyi keşfetmek, ön işleme adımlarını uygulamak veya makine öğrenimi modelleri için veriyi hazırlamak amacıyla kullanılabilir. Bu aşamada, veri setini daha derinlemesine anlamak, eksik veya aykırı değerlere müdahale etmek, özellik mühendisliği yapmak ve modelleme sürecine geçmek için gerekli adımları uygulamak mümkündür.

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

Bu sayede, veri analizi ve görselleştirmenin yanı sıra diğer birçok işlemi daha kolay bir şekilde gerçekleştirebilirsiniz. Örneğin, veri setlerinizi düzenleme, temizleme, filtreleme ve grafik oluşturma gibi işlemleri daha hızlı ve etkili bir şekilde yapabilirsiniz.

explore

bu paket veri keşfi işlemleri için bir interaktif araç sağlar.

library(explore)

“train” adlı veri çerçevesini incelemek ve tanımlayıcı istatistikler elde etmek için %>% operatörünü kullanarak, “psych” paketinde bulunan describe_all() işlevine yönlendiriyoruz. Bu işlev, veri kümesindeki tüm değişkenler için geniş kapsamlı tanımlayıcı istatistikleri sağlar. Bu istatistikler arasında ortalama, standart sapma, çarpıklık, basıklık ve çeşitli yüzdelikler gibi ölçümler bulunmaktadır. Yani, bu kod parçası, “train” veri çerçevesindeki değişkenlere ilişkin detaylı bir istatistiksel özet elde etmek için kullanılır.

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
train[c('ailenum', 'ailesira')] <- str_split_fixed(train$PassengerId, "_", 2)

Bu kod parçası, “train” adlı veri çerçevesindeki “PassengerId” sütununu kullanarak iki yeni sütun olan “ailenum” ve “ailesira”yı oluşturmayı hedeflemektedir. Bu işlem, “PassengerId” sütunundaki değerleri “_” (alt çizgi) karakterine göre böler ve elde edilen parçaları yeni sütunlara ekler.

Yani, her “PassengerId” değeri “_” karakterine göre iki parçaya ayrılır. Bu parçalardan biri “ailenum” sütununa, diğeri ise “ailesira” sütununa atanır. Bu sayede, “ailenum” sütunu aile numaralarını, “ailesira” sütunu ise aile içindeki sıraları temsil eder. Bu yeni sütunlar, “PassengerId” sütunundan elde edilen bilgilerle aile yapıları hakkında daha ayrıntılı bilgi sağlamak amacıyla kullanılabilir.

test[c('ailenum', 'ailesira')] <- str_split_fixed(test$PassengerId, "_", 2)

Bu R kodu, “test” veri çerçevesindeki “PassengerId” değişkenini kullanarak iki yeni değişken olan “ailenum” ve “ailesira”yı oluşturur. “PassengerId” içindeki değerleri “_” karakterine göre bölerek, elde edilen parçaları “ailenum” ve “ailesira” değişkenlerine atar. Bu sayede “PassengerId” içindeki grup bilgilerini “ailenum”de, sıra numaralarını ise “ailesira”da sakla

train[c('deck', 'num', 'side')] <- str_split_fixed(train$Cabin, '/', 3)

Bu R kodu, “train” veri çerçevesindeki “Cabin” değişkenini kullanarak üç yeni değişken oluşturur: “deck”, “num”, ve “side”. “Cabin” içindeki değerleri “/” karakterine göre bölerek, elde edilen parçaları sırasıyla “deck”, “num”, ve “side” değişkenlerine atar. Bu işlem, “Cabin” değişkenindeki kabin numarasının içindeki bilgileri ayrıştırarak, bu bilgileri ayrı değişkenlerde saklar.

test[c('deck', 'num', 'side')] <- str_split_fixed(test$Cabin, '/', 3)

Bu R kodu, “test” veri çerçevesindeki “Cabin” değişkenini üç parçaya ayırarak yeni üç değişken oluşturur: “deck”, “num”, ve “side”.

train[train == ''] <- NA
test[test == ''] <- NA

Bu R kodu, “train” ve “test” veri çerçevelerindeki boş değerleri (empty strings) NA (Not Available - Mevcut Değil) ile değiştirir. Yani, eğer bir hücrede boş bir değer varsa, o hücreye NA değeri atanır. Bu, veri setindeki boş değerleri standartlaştırmak ve işlemek için yaygın bir yöntemdir.

library(DataExplorer)
create_report(train)
## 
## 
## processing file: report.rmd
## 
  |                                           
  |                                     |   0%
  |                                           
  |.                                    |   2%                                 
  |                                           
  |..                                   |   5% [global_options]                
  |                                           
  |...                                  |   7%                                 
  |                                           
  |....                                 |  10% [introduce]                     
  |                                           
  |....                                 |  12%                                 
  |                                           
  |.....                                |  14% [plot_intro]                    
  |                                           
  |......                               |  17%                                 
  |                                           
  |.......                              |  19% [data_structure]                
  |                                           
  |........                             |  21%                                 
  |                                           
  |.........                            |  24% [missing_profile]               
  |                                           
  |..........                           |  26%                                 
  |                                           
  |...........                          |  29% [univariate_distribution_header]
  |                                           
  |...........                          |  31%                                 
  |                                           
  |............                         |  33% [plot_histogram]                
  |                                           
  |.............                        |  36%                                 
  |                                           
  |..............                       |  38% [plot_density]                  
  |                                           
  |...............                      |  40%                                 
  |                                           
  |................                     |  43% [plot_frequency_bar]            
  |                                           
  |.................                    |  45%                                 
  |                                           
  |..................                   |  48% [plot_response_bar]             
  |                                           
  |..................                   |  50%                                 
  |                                           
  |...................                  |  52% [plot_with_bar]                 
  |                                           
  |....................                 |  55%                                 
  |                                           
  |.....................                |  57% [plot_normal_qq]                
  |                                           
  |......................               |  60%                                 
  |                                           
  |.......................              |  62% [plot_response_qq]              
  |                                           
  |........................             |  64%                                 
  |                                           
  |.........................            |  67% [plot_by_qq]                    
  |                                           
  |..........................           |  69%                                 
  |                                           
  |..........................           |  71% [correlation_analysis]          
  |                                           
  |...........................          |  74%                                 
  |                                           
  |............................         |  76% [principal_component_analysis]  
  |                                           
  |.............................        |  79%                                 
  |                                           
  |..............................       |  81% [bivariate_distribution_header] 
  |                                           
  |...............................      |  83%                                 
  |                                           
  |................................     |  86% [plot_response_boxplot]         
  |                                           
  |.................................    |  88%                                 
  |                                           
  |.................................    |  90% [plot_by_boxplot]               
  |                                           
  |..................................   |  93%                                 
  |                                           
  |...................................  |  95% [plot_response_scatterplot]     
  |                                           
  |.................................... |  98%                                 
  |                                           
  |.....................................| 100% [plot_by_scatterplot]           
## output file: /cloud/project/report.knit.md
## /usr/lib/rstudio-server/bin/quarto/bin/tools/pandoc +RTS -K512m -RTS /cloud/project/report.knit.md --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash --output /cloud/project/report.html --lua-filter /cloud/lib/x86_64-pc-linux-gnu-library/4.3/rmarkdown/rmarkdown/lua/pagebreak.lua --lua-filter /cloud/lib/x86_64-pc-linux-gnu-library/4.3/rmarkdown/rmarkdown/lua/latex-div.lua --embed-resources --standalone --variable bs3=TRUE --section-divs --table-of-contents --toc-depth 6 --template /cloud/lib/x86_64-pc-linux-gnu-library/4.3/rmarkdown/rmd/h/default.html --no-highlight --variable highlightjs=1 --variable theme=yeti --mathjax --variable 'mathjax-url=https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' --include-in-header /tmp/RtmpszmTbX/rmarkdown-str1b431e9f29f5.html
## 
## Output created: report.html

####Percentages

####Histogram

train %>% describe_all()
## # A tibble: 19 × 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
## 15 ailenum      chr       0    0     6217    NA  NA       NA
## 16 ailesira     chr       0    0        8    NA  NA       NA
## 17 deck         chr     199    2.3      9    NA  NA       NA
## 18 num          chr     199    2.3   1818    NA  NA       NA
## 19 side         chr     199    2.3      3    NA  NA       NA

Bar Chart (with frequency) ## 5 columns ignored with more than 50 categories. ## PassengerId: 8693 categories ## Cabin: 6561 categories ## Name: 8474 categories ## ailenum: 6217 categories ## num: 1818 categories

Principal Component Analysis ## 5 features with more than 50 categories ignored! ## PassengerId: 6606 categories ## Cabin: 5305 categories ## Name: 6590 categories ## ailenum: 5015 categories ## num: 1734 categories

Bu R kodu, “train” veri çerçevesinden “Cabin” değişkenini çıkararak aynı “train” veri çerçevesini günceller.

train <- train %>% select(-Cabin)

Bu R kodu, “train” veri çerçevesinden “Cabin” değişkenini çıkararak aynı “train” veri çerçevesini günceller.

test <- test %>% select(-Cabin)

Bu R kodu, “test” veri çerçevesinden “Cabin” değişkenini çıkararak aynı “test” veri çerçevesini günceller.

unique(train$HomePlanet)
## [1] "Europa" "Earth"  "Mars"   NA

Bu R kodu, “train” veri çerçevesindeki tüm değişkenlerin özet istatistiklerini görmek için kullanılır.

levels(train$HomePlanet)
## NULL
train$HomePlanet <- addNA(train$HomePlanet)

Bu R kodu, “train” veri çerçevesindeki “HomePlanet” değişkeninin faktör (factor) türündeki seviyelerini (levels) listeleyerek, bu değişkenin alabileceği benzersiz kategorik değerleri gösterir. Yani, “HomePlanet” değişkenindeki farklı kategori seviyelerini elde eder.

test$HomePlanet <- addNA(test$HomePlanet)

Bu R kodu, “train” veri çerçevesindeki “HomePlanet” değişkenindeki eksik değerleri (NA) işaretler.

levels(train$HomePlanet)
## [1] "Earth"  "Europa" "Mars"   NA

Bu R kodu, “test” veri çerçevesindeki “HomePlanet” değişkenindeki eksik değerleri (NA) işaretler.

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
train <- train %>%
  group_by(HomePlanet) %>%
  mutate_at(vars(Age), ~replace_na(., mean(., na.rm = TRUE)))
test <- test %>%
  group_by(HomePlanet) %>%
  mutate_at(vars(Age), ~replace_na(., mean(., na.rm = TRUE)))
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       0    0       84     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
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       84     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"
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       84     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         fct       0    0        3    NA  NA       NA
train$VIP <- addNA(train$VIP)
test$VIP <- addNA(test$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)))
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       84     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 %>% 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       84     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     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
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 %>% 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       84     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 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
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       84     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       84     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       83     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)
head(train[, c("PassengerId", "ailenum", "ailesira", "aile")], 20)
## # A tibble: 20 × 4
##    PassengerId ailenum ailesira  aile
##    <chr>       <chr>   <chr>    <dbl>
##  1 0001_01     0001    01           0
##  2 0002_01     0002    01           0
##  3 0003_01     0003    01           1
##  4 0003_02     0003    02           1
##  5 0004_01     0004    01           0
##  6 0005_01     0005    01           0
##  7 0006_01     0006    01           1
##  8 0006_02     0006    02           1
##  9 0007_01     0007    01           0
## 10 0008_01     0008    01           1
## 11 0008_02     0008    02           1
## 12 0008_03     0008    03           1
## 13 0009_01     0009    01           0
## 14 0010_01     0010    01           0
## 15 0011_01     0011    01           0
## 16 0012_01     0012    01           0
## 17 0014_01     0014    01           0
## 18 0015_01     0015    01           0
## 19 0016_01     0016    01           0
## 20 0017_01     0017    01           1
train <- train %>% select(-c(ailenum, ailesira, num))
test <- test %>% select(-c(ailenum, ailesira, num))
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     84     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

Logistic Regresyon

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)

Naive Bayes

library(e1071)
fit_nb <- naiveBayes(Transported ~ ., data =training_set)

preds <- predict(fit_nb, newdata = testing_set[-11], type = "raw") %>%
  data.frame()
y_pred = ifelse(preds$TRUE. > 0.5, 1, 0)
cm = table(y_true, y_pred )
cm
##       y_pred
## y_true    0    1
##      0  510  569
##      1   78 1016
(510+1016)/(510+1016+78+569)
## [1] 0.7022549
nb_son = naiveBayes(Transported ~ ., data = train_set)
preds <- predict(nb_son, newdata = test_set, type = "raw") %>%
  data.frame()
y_pred = ifelse(preds$TRUE. > 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)
sample_submission$Transported <- str_to_title(sample_submission$Transported)
write.csv(sample_submission, "sub_nb_logistic.csv", row.names = FALSE, 
quote = FALSE)

SVM

library(e1071)
fit_svm <- svm(Transported ~ ., data = training_set,
               type= 'C-classification',
               kernel = 'linear')

preds <- predict(fit_svm, newdata = testing_set, type = "raw") %>%
  data.frame()
y_pred = ifelse(preds$. == TRUE, 1, 0)
cm = table(y_true, y_pred)
cm
##       y_pred
## y_true   0   1
##      0 831 248
##      1 171 923
(830+923)/(830+923+171+249)
## [1] 0.8067188
svm_son = svm(Transported ~ ., data = train_set,
              type = 'C-classification',
              kernel = 'linear')
preds <- predict(svm_son, newdata = test_set, type = "raw") %>%
  data.frame()
y_pred = preds$.
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_svm.csv", row.names = FALSE, 
quote = FALSE)

SVM radial (kernel)

svm_ker_son = svm(Transported ~ ., data =train_set,
                  type = 'C-classification',
                  kernel = 'radial')
preds <- predict(svm_ker_son, newdata = test_set, type = "raw") %>%
  data.frame()
y_pred = preds$.
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_kernelsvm.csv", row.names = FALSE, 
quote = FALSE)

Decision Trees

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)
## Loading required package: 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 = 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.0160692 0.01247582
## 2 0.03574372      1 0.5698393 0.5698393 0.01123791
## 3 0.01000000      4 0.4626082 0.4697157 0.01055054
## 
## 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 = test_set, type = "class")
y_pred = ifelse(preds == TRUE, TRUE, FALSE)