Advertisement
Guest User

Untitled

a guest
Feb 25th, 2018
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.01 KB | None | 0 0
  1. ratings.train = read.csv("/Users/fay_kong/Desktop/SML_SPRING/FILM/movies_matchup.csv", head = TRUE)
  2. ratings.test = read.csv("/Users/fay_kong/Desktop/SML_SPRING/FILM/test_matchup.csv", head = TRUE)
  3.  
  4. user.ids = sort(unique(ratings.train$userId))  #count user NO.
  5. movie.ids = sort(unique(ratings.train$movieId)) #count movie NO.
  6.  
  7. totalmean = mean(ratings.train[,5])
  8.  
  9.  
  10. # # # user.bia---------------------------------------------
  11.  
  12. user.bias = matrix(NA,671,2)
  13. user.bias[,1] = c(1:671)
  14.  
  15. for(i in 1:671){
  16.  
  17.   users = ratings.train[which(ratings.train[,1]==i),]
  18.  
  19.   user.mean = mean(users[,5])
  20.  
  21.   user.bias[i,2] = user.mean - totalmean
  22. }
  23.  
  24.  
  25. # # # movie.bias-------------------------------------------
  26.  
  27. movie.bias = matrix(NA,8090,3)
  28. movie.bias[,1] = c(1:8090)
  29. movie.bias[,2] = unique(ratings.train$movieId)
  30.  
  31. for(i in 1:8090){
  32.  
  33.   movies = ratings.train[which(ratings.train[,2]==movie.bias[i,2]),]
  34.  
  35.   movie.mean = mean(movies[,5])
  36.  
  37.   movie.bias[i,3] = movie.mean - totalmean
  38. }
  39.  
  40.  
  41. # # # predictions------------------------------------------
  42.  
  43. ratings.test$prediction = 0
  44.  
  45. for(i in 1:24720){
  46.   userid = ratings.test[i,1]
  47.  
  48.   movieid = ratings.test[i,2]
  49.  
  50.   ubias = user.bias[userid,2]
  51.  
  52.   movie.row = movie.bias[which(movie.bias[,2]==movieid)]
  53.  
  54.   if(length(movie.row) == 0){
  55.     mbias = 0
  56.   }else{
  57.     mbias = movie.bias[movie.row,3]
  58.   }
  59.  
  60.   ratings.test[i,5] = totalmean + ubias +mbias
  61. }
  62.  
  63. RoundToZeroFive = function(x){
  64.   decimal = x - trunc(x)
  65.   roundx = matrix(NA,length(x),1)
  66.   for(i in 1:length(x)){
  67.     if(decimal[i] < 0.25){
  68.       roundx[i] = trunc(x[i])
  69.     }
  70.     else{
  71.       if(decimal[i] > 0.75){
  72.         roundx[i] = trunc(x[i])+1
  73.       }
  74.       else{
  75.         roundx[i] = trunc(x[i])+0.5
  76.       }
  77.     }
  78.   }
  79.   roundx
  80. }
  81.  
  82. predictions = RoundToZeroFive(ratings.test[,5])
  83. predictions[which(predictions==0)] = 0.5
  84. predictions[which(predictions > 5)] = 5
  85.  
  86. write.csv(predictions,file = "/Users/fay_kong/Desktop/SML_SPRING/FILM/Baselinepredictions.csv",row.names = FALSE)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement