forked from BruceJillis/Titanic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glm.r
76 lines (64 loc) · 1.77 KB
/
glm.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
library(Hmisc)
clc <- function() cat(rep("\n",100))
clc()
set.seed(42)
read.data <- function(file) {
# read training data
data <- read.csv(file, sep=',', na.strings=c(''), stringsAsFactors=FALSE)
# drop some columns
data <- subset(data, select = -c(Name, Fare, Ticket))
# correct some column types
#data$Survived <- as.factor(data$Survived)
data$Sex <- as.factor(data$Sex)
data$Embarked <- as.factor(data$Embarked)
data$Pclass <- as.factor(data$Pclass)
if('Survived' %in% colnames(data)) {
data$Survived <- as.factor(data$Survived)
}
return (data)
}
train <- read.data('data/train.csv')
test <- read.data('data/test.csv')
# massage and impute missing data
cabin_to_deck <- function(data) {
data = as.character(data)
for(i in seq(along=data)) {
if (is.na(data[i]))
next
data[i] <- substr(data[i], 1, 1)
}
return (as.factor(data))
}
# Cabin
train$Cabin <- impute(cabin_to_deck(train$Cabin), 'random')
test$Cabin <- impute(cabin_to_deck(test$Cabin), 'random')
# Age
train$Age <- impute(train$Age, mean)
test$Age <- impute(test$Age, mean)
# Embarked
train$Embarked <- impute(train$Embarked, mean)
test$Embarked <- impute(test$Embarked, mean)
model <- glm(
Survived ~ Pclass + Sex + Age + Cabin + SibSp + Parch +
Pclass : Sex +
Pclass : Age +
Pclass : Cabin +
Sex : SibSp +
Sex : Parch +
Sex : Age +
Sex : Cabin +
Age : Cabin,
data=train,
family="binomial",
control=list(maxit = 150)
)
summary(model)
anova(model, test="Chisq")
if(T){
head(test)
test$Survived <- predict(model, newdata=test, type="response")
test$Survived <- round(test$Survived)
head(test)
summary(test)
write.csv(test[,c("PassengerId", "Survived")], file="predictions.csv", row.names=FALSE, quote=FALSE)
}