| 109 | # using neighbors, calculate train and test MSE |
| 110 | |
| 111 | def predict(i, m): |
| 112 | # calculate the weighted sum of deviations |
| 113 | numerator = 0 |
| 114 | denominator = 0 |
| 115 | for neg_w, j in neighbors[i]: |
| 116 | # remember, the weight is stored as its negative |
| 117 | # so the negative of the negative weight is the positive weight |
| 118 | try: |
| 119 | numerator += -neg_w * deviations[j][m] |
| 120 | denominator += abs(neg_w) |
| 121 | except KeyError: |
| 122 | # neighbor may not have rated the same movie |
| 123 | # don't want to do dictionary lookup twice |
| 124 | # so just throw exception |
| 125 | pass |
| 126 | |
| 127 | if denominator == 0: |
| 128 | prediction = averages[i] |
| 129 | else: |
| 130 | prediction = numerator / denominator + averages[i] |
| 131 | prediction = min(5, prediction) |
| 132 | prediction = max(0.5, prediction) # min rating is 0.5 |
| 133 | return prediction |
| 134 | |
| 135 | |
| 136 | train_predictions = [] |