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