简体   繁体   中英

SVM classification - normalization in R

I want to work with SVM classification. How is it possible to normalize (or scale) the features per column in my dataset before i use the SVM model?

train <- read.csv("train.csv")
test <- read.csv("test.csv")

svm.fit=svm(as.factor(type)~ ., data=train, core="libsvm",kernel="linear",cross=10, probability=TRUE)

You can use the scale function in an sapply :

scaleddf <- as.data.frame(sapply(train, function(i) if(is.numeric(i)) scale(i) else i))

If your data contains variables with NaN values or with 0 variance, you could first process and subset the original dataset before using the function above.

# get a vector of variables to drop
dropVars <- sapply(train, function(i) {
              if((is.numeric(i) & !any(is.nan(i)) & sd(i) > 0) | is.factor(i) | is.character(i)) TRUE
              else FALSE
              }
# subset test dropping columns that don't fit the criteria
smallerdf <- test[, dropVars]

Then apply the original sapply function above to smallerdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM