net.librec.eval.rating.RMSEEvaluator Maven / Gradle / Ivy
/**
* Copyright (C) 2016 LibRec
*
* This file is part of LibRec.
* LibRec is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LibRec is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LibRec. If not, see .
*/
package net.librec.eval.rating;
import net.librec.eval.AbstractRecommenderEvaluator;
import net.librec.math.structure.MatrixEntry;
import net.librec.math.structure.SparseMatrix;
import net.librec.recommender.item.RecommendedList;
import net.librec.recommender.item.UserItemRatingEntry;
import java.util.Iterator;
/**
* RMSE: root mean square error
*
* @author WangYuFeng, zhanghaidong and Keqiang Wang
*/
public class RMSEEvaluator extends AbstractRecommenderEvaluator {
public double evaluate(SparseMatrix testMatrix, RecommendedList recommendedList) {
if (testMatrix == null) {
return 0.0;
}
double rmse = 0.0;
int testSize = 0;
Iterator testMatrixIter = testMatrix.iterator();
Iterator recommendedEntryIter = recommendedList.entryIterator();
while (testMatrixIter.hasNext()) {
if (recommendedEntryIter.hasNext()) {
MatrixEntry testMatrixEntry = testMatrixIter.next();
UserItemRatingEntry userItemRatingEntry = recommendedEntryIter.next();
if (testMatrixEntry.row() == userItemRatingEntry.getUserIdx()
&& testMatrixEntry.column() == userItemRatingEntry.getItemIdx()) {
double realRating = testMatrixEntry.get();
double predictRating = userItemRatingEntry.getValue();
rmse += Math.pow(realRating - predictRating, 2);
testSize++;
} else {
throw new IndexOutOfBoundsException("index of recommendedList does not equal testMatrix index");
}
} else {
throw new IndexOutOfBoundsException("index size of recommendedList does not equal testMatrix index size");
}
}
return testSize > 0 ? Math.sqrt(rmse / testSize) : 0.0d;
}
}