My rows are mismatched in my SVM scripting code for Kaggle

杀马特。学长 韩版系。学妹 提交于 2019-12-25 09:06:06

问题


I am reviewing my e1071 code for SVM for the Kaggle Titanic data. Last I knew, this part of it was working, but now I'm getting a rather strange error. When I try to build my data.frame so I can submit to kaggle, it seems my prediction is the size of my training set instead of the test set.

Problem

Error in data.frame(PassengerId = test$passengerid, Survived = prediction) : arguments imply differing number of rows: 418, 714

Obviously, they should both be 418 and I do not understand what is going wrong?

Details

Here is my script:

setwd("Path\\To\Data")
train <- read.csv("train.csv")
test <- read.csv("test.csv")

library("e1071")
bestModel = svm(Survived ~ Pclass + Sex + Age + Sex * Pclass, data = train, kernel = "linear", cost = 1)

prediction <- predict(bestModel, newData=test, type="response")
prediction[prediction >= 0.5] <- 1
prediction[prediction != 1] <- 0
prediction[is.na(prediction)] <- 0

This is the line that gives me the error:

predictionSubmit <- data.frame(PassengerId = test$passengerid, Survived = prediction)

Attempts

I have used names(train) and names(test) to verify my column variable names are the same. You can find the data here. I know my prediction code can be optimized into one line, but that isn't the issue here. I would appreciate a second pair of eyes on this issue. I am thinking about using the kernlab library, but was wondering if there was a syntatical sugar issue I was neglecting here. Thanks for your suggestions and clues.


回答1:


#10 items in training set
y <- sample(0:1, 10, T)
x <- rnorm(10)
bestModel <- svm(y~x,kernel = "linear", cost = 1)

#Six in test set
prediction <- predict(bestModel, newdata=rnorm(6), type="response")

#Output has 10 values (unexpected)
prediction
#           1          2          3          4          5          6       <NA>       <NA> 
#  0.05163974 0.58048905 0.49524846 0.13524885 0.12592718 0.06082822 0.55393256 1.08488424 
#        <NA>       <NA> 
#  0.94836026 0.47679646 

#For correct output, remove names with <NA>
prediction[na.omit(names(prediction))]
#         1          2          3          4          5          6 
#0.05163974 0.58048905 0.49524846 0.13524885 0.12592718 0.06082822 


来源:https://stackoverflow.com/questions/38546899/my-rows-are-mismatched-in-my-svm-scripting-code-for-kaggle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!