Advertisement
Guest User

KNN chunk NBA

a guest
Jul 23rd, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.51 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. # Sample for faster performance
  20. set.seed(7)
  21. sample1 = sample(1:84616, 1000)
  22.  
  23. # Adding names to factors due to error when running train() "one of the class levels is not a valid R variable name"
  24. levels(knnTrain$LOCATION_HOME) = c("A", "H")
  25. levels(knnTrain$FGM) = c("miss", "made")
  26. levels(knnTrain$PTS_TYPE_2) = c("three", "two")
  27.  
  28. levels(knnTest$LOCATION_HOME) = c("A", "H")
  29. levels(knnTest$FGM) = c("miss", "made")
  30. levels(knnTest$PTS_TYPE_2) = c("three", "two")
  31.  
  32. # Setting parameters for tuning repetitions and cross-validation in model
  33. ctrl <- trainControl(
  34.   classProbs = TRUE,
  35.   method = "cv", # cross-validation method
  36.   number = 5,    # number of folds
  37.   )
  38.  
  39. # Modeling with training set
  40. fgmknnModel <- train(FGM~., data = knnTrain, method = "knn", tuneGrid=expand.grid(k = c(200, 300)), trControl = ctrl)
  41. fgmknnModel
  42. summary(fgmknnModel)
  43. # Determining and plotting the variable importance
  44. fgmimpvar = varImp(fgmknnModel, scale = T)
  45. ggplot(fgmimpvar)
  46.  
  47. # Predicting shot outcome and establishing final accuracy using test set
  48. TestPred <- predict(fgmknnModel, knnTest)
  49.  
  50. # Creating the confusion matrix using the predicted and test values for FGM
  51. confusionMatrix(TestPred, knnTest$FGM, positive = "made")
  52.  
  53. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement