Advertisement
Guest User

KNN chunk NBA

a guest
Jul 21st, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.38 KB | None | 0 0
  1. ```{r knnModel}
  2. library(pacman)
  3. p_load(caret, ggplot)
  4.  
  5. # knnTrain = train_final
  6.  
  7. # knnTest = test_final
  8.  
  9.  
  10. knnTest = testdec.iqr
  11. knnTrain = traindec.iqr
  12.  
  13. # Categoricals to factors
  14. for (i in c(8:10)){
  15.   knnTrain[,i] <- as.factor(knnTrain[,i])
  16.   knnTest[,i] <- as.factor(knnTest[,i])
  17. }
  18.  
  19. # Adding names to factors due to error when running train() "one of the class levels is not a valid R variable name"
  20. levels(knnTrain$LOCATION_HOME) = c("A", "H")
  21. levels(knnTrain$FGM) = c("miss", "made")
  22. levels(knnTrain$PTS_TYPE_2) = c("three", "two")
  23.  
  24. levels(knnTest$LOCATION_HOME) = c("A", "H")
  25. levels(knnTest$FGM) = c("miss", "made")
  26. levels(knnTest$PTS_TYPE_2) = c("three", "two")
  27.  
  28. # Setting parameters for tuning repetitions and cross-validation in model
  29. ctrl <- trainControl(
  30.   classProbs = TRUE,
  31.   method = "repeatedcv", # repeated cross-validation method
  32.   number = 5,    # number of folds
  33.   repeats = 10, # number of complete sets of folds
  34.   )
  35.  
  36. # Modeling with training set
  37. fgmknnModel <- train(FGM~., data = knnTrain, method = "knn", tuneGrid=expand.grid(k=200:220), trControl = ctrl)
  38. fgmknnModel
  39.  
  40. # Determining and plotting the variable importance
  41. fgmimpvar = varImp(fgmknnModel, scale = T)
  42. ggplot(fgmimpvar)
  43.  
  44. # Predicting shot outcome and establishing final accuracy using test set
  45. TestPred <- predict(fgmknnModel, knnTest)
  46. confusionMatrix(TestPred, knnTest$FGM)
  47.  
  48. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement