10/07/2016

Computing2

Today, I practiced the Computing part of Chapter 4. They were about Basic Model Building in R and Determination of Tuning Parameters.

1.
#knn function in MASS
#ipredknn function in ipred
#knn3 function in caret
#formula interface: modelFunction(price ~ numBedrooms+numBaths+acres, data=housingData)
#non-formula interface: modelFunction(x=housePredictors, y=price)
library(caret)
trainpredictors=as.matrix(trainpredictors)
trainpredictors
knnfit=knn3(x=trainpredictors, y=trainclasses, k=5)
knnfit
#predict new samples
testpredictions=predict(knnfit, newdata = testpredictors, type = "class")
head(testpredictions)

2.
#e1071package contains the tune function
#errorest function in the ipred package
#the train function in the caret package
library(caret)
library(AppliedPredictiveModeling)
data("GermanCredit")
set.seed(100)
inTrain=createDataPartition(GermanCredit$Class, p = 0.8)[[1]]
GermanCreditTrain=GermanCredit[ inTrain, ]
GermanCreditTest=GermanCredit[-inTrain, ]
head(GermanCreditTrain)
head(GermanCreditTest)
set.seed(1056)
svmfit=train(Class~ .,data=GermanCreditTrain, method="svmRadial", preProc=c("center", "scale"), 
             tuneLength=10, 
             trControl=trainControl(method="repeatedcv", repeats=5, classProbs=TRUE))
plot(svmfit, scales=list(x=list(log=2)))
predictedclasses=predict(svmfit, GermanCreditTest)
str(predictedclasses)
predictedprobs=predict(svmfit, newdata=GermanCreditTest, type="prob")
head(predictedprobs)

Next week, I will continue to practice Computing.

No comments:

Post a Comment