net.librec.eval.rating.MAEEvaluator Maven / Gradle / Ivy
Show all versions of librec-core Show documentation
/**
* 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.recommender.item.ContextKeyValueEntry;
import net.librec.recommender.item.RecommendedList;
import java.util.Iterator;
/**
* MAE: mean absolute error
*
* @author Keqiang Wang
*/
public class MAEEvaluator extends AbstractRecommenderEvaluator {
public double evaluate(RecommendedList groundTruthList, RecommendedList recommendedList) {
if(groundTruthList.size()==0){
return 0.0;
}
double mae = 0.0;
int testSize = 0;
Iterator groundTruthIter = groundTruthList.iterator();
Iterator recommendedEntryIter = recommendedList.iterator();
while (groundTruthIter.hasNext()) {
if (recommendedEntryIter.hasNext()) {
ContextKeyValueEntry groundEntry = groundTruthIter.next();
ContextKeyValueEntry recommendedEntry = recommendedEntryIter.next();
if (groundEntry.getContextIdx() == recommendedEntry.getContextIdx()
&& groundEntry.getKey() == recommendedEntry.getKey()) {
double realRating = groundEntry.getValue();
double predictRating = recommendedEntry.getValue();
mae += Math.abs(realRating - predictRating);
testSize++;
} else {
throw new IndexOutOfBoundsException("index of recommendedList does not equal testMatrix index");
}
} else {
throw new IndexOutOfBoundsException("index cardinality of recommendedList does not equal testMatrix index cardinality");
}
}
return testSize > 0 ? mae / testSize : 0.0d;
}
}