R language Access Menu

Title Text Both  

Creating predictive models

The package caret provides easy functions for creating predictive models: 


    > library(caret)
    > model = train(sformula, mydf, method=smethod, linout=slineout, trace = FALSE)

The model can then be used for prediction from new data: 


   > predict(nn, testdf) 

> nn_iris = function(sm='nnet'){
    mod = nn_caret(Species~., iris, method=smethod)
    pp = predict(mod, iris[-5])
    print(table(pp, iris[,5]))

For example, we can randomly select 120 rows (out of total 150 rows) of iris dataset as training rows to create a model while the remaining 30 rows act as the test rows for testing of the model created: 


> trainRows = sample(1:150, 120) 

> trainIris = iris[trainRows,]
> testIris = iris[-trainRows,]

> library(caret)
> mod = train(Species~., trainIris, method='nnet', trace=F)  # using neural net method

Now we can use the model to predict Species from test part of iris dataset: 

> pp = predict(mod, testIris[-5])
> table(pp, testIris[,5])
pp           setosa versicolor virginica
  setosa         12          0         0
  versicolor      0          9         0
  virginica       0          0         9    

It shows that the model predicted the species in the test set with 100% accuracy. 

Several methods (in addition to 'nnet') can be used to create such predictive models with caret package. These include 'lm', 'logreg', 'glm', 'knn', 'nnet', 'kknn', 'pcaNNet', 'gamLoess', 'avNNet', 'treebag', 'rf', 'rvmRadial', 'lda', 'lda2', 'mda', 'svmLinear', 'svmPoly', 'svmRadial', 'svmRadialCost', 'neuralnet', 'multinom', 'brnn' and several others. 

Max Kuhn. Contributions from Jed Wing, Steve Weston, Andre Williams, Chris Keefer, Allan Engelhardt, Tony Cooper, Zachary Mayer, Brenton Kenkel, the R Core Team, Michael Benesty, Reynald Lescarbeau, Andrew Ziem and Luca Scrucca. (2015). caret: Classification and Regression
Training. R package version 6.0-52. http://CRAN.R-project.org/package=caret

    Comments & Feedback