'Iterate once over rating data and adjust corresponding factors (stochastic gradient descent)'

def _train(self, rating_indices, update_user, update_item):

    err_total = 0.0
    for (user_idx, item_idx) in rating_indices:
        p = self._predict(user_idx, item_idx, False)
        err = (self.model.index[(user_idx, item_idx)] - p)
        err_total += (err ** 2.0)
        u_f = self.user_factors[user_idx]
        i_f = self.item_factors[item_idx]
        delta_u = ((err * i_f) - (self.regularization * u_f))
        delta_i = ((err * u_f) - (self.regularization * i_f))
        if update_user:
            self.user_factors[user_idx] += (self.learning_rate * delta_u)
        if update_item:
            self.item_factors[item_idx] += (self.learning_rate * delta_i)
    return err_total
