# You can write R code here and then click "Run" to run it on our platform

library(readr)
library(caret)
library(randomForest)

# The competition datafiles are in the directory ../input
# Read competition data files:
input <- read_csv("../input/train.csv")
test <- read_csv("../input/test.csv")

train <- createDataPartition(y=input$label, p=0.5,times=1, list=FALSE)
numTrain <- input[train,]

varNames <- names(numTrain)

up_pix <- paste("pixel", c(0:83), sep="") #83
down_pix <- paste("pixel", c(700:783), sep="") #700

left_pix <- character(0)
right_pix <- character(0)
for(i in 3:24){ #3:24
	left_pix <- c(left_pix, paste("pixel", i*28, sep=""))
	left_pix <- c(left_pix, paste("pixel", i*28+1, sep=""))
	left_pix <- c(left_pix, paste("pixel", i*28+2, sep=""))

	right_pix <- c(right_pix, paste("pixel", i*28+25, sep=""))
	right_pix <- c(right_pix, paste("pixel", i*28+26, sep=""))
	right_pix <- c(right_pix, paste("pixel", i*28+27, sep=""))
}

varNames2 <- varNames[!varNames %in% c("label", up_pix, down_pix, left_pix, right_pix)]
varNames2 <- paste(varNames2, collapse = "+")
labels <- as.factor(numTrain$label)
form2 <- as.formula(paste("labels", varNames2, sep = " ~ "))

thres <- 20
thres_func <- function(x) { if(x[1]<thres){0}else{255} }
thresTrain <- as.data.frame(lapply(numTrain[, 2:785], FUN = function(x) {sapply(x, FUN = thres_func)}))
thresTest <- as.data.frame(lapply(test[, 1:784], FUN = function(x) {sapply(x, FUN = thres_func)}))

rf3 <- randomForest(form2, data=thresTrain, ntree=50)
prediction3 <- predict(rf3, type="class", newdata=thresTest)

predictions3 <- data.frame(ImageId=1:nrow(test), Label=prediction3)

write_csv(predictions3, "sol3.csv")



