001package es.ucm.fdi.gaia.jcolibri.method.reuse.classification;
002
003
004import java.util.Collection;
005import java.util.HashMap;
006import java.util.Map;
007
008import es.ucm.fdi.gaia.jcolibri.extensions.classification.ClassificationSolution;
009import es.ucm.fdi.gaia.jcolibri.method.retrieve.RetrievalResult;
010
011/**
012 * Provides the ability to classify a query by predicting its
013 * solution from supplied cases. Classification is done by 
014 * similarity weighted voting, where each vote is based on 
015 * the similarity of the case to the query. The class with the
016 * highest overall value is the predicted class.
017 * 
018 * @author Derek Bridge
019 * @author Lisa Cummins
020 * 16/05/07
021 */
022public class SimilarityWeightedVotingMethod extends AbstractKNNClassificationMethod
023{
024    /**
025     * Predicts the class that has the highest value vote
026     * among the k most similar cases, where votes are based on
027     * similarity to the query.
028     * If several classes receive the same highest vote, the class that
029     * has the lowest hash code is taken as the prediction. 
030     * @param cases
031     *            an ordered list of cases along with similarity scores.
032     * @return Returns the predicted solution.
033     */
034    @Override
035    public ClassificationSolution getPredictedSolution(Collection<RetrievalResult> cases)
036    {
037        Map<Object, Double> votes = new HashMap<>();
038        Map<Object, ClassificationSolution> values = new HashMap<Object, ClassificationSolution>();
039        
040        for(RetrievalResult result: cases)
041        {   
042            ClassificationSolution solution = (ClassificationSolution)result.get_case().getSolution();
043           
044            Object solnAttVal = solution.getClassification();
045             
046            double eval = result.getEval();
047            if (votes.containsKey(solnAttVal))
048            {   votes.put(solnAttVal, votes.get(solnAttVal) + eval);
049            }
050            else
051            {   votes.put(solnAttVal, eval);
052                values.put(solnAttVal, solution);
053            }
054        }
055        double highestVoteSoFar = 0.0;
056        Object predictedClassVal = null;
057        for (Map.Entry<Object, Double> e : votes.entrySet())
058        {   if (e.getValue() >= highestVoteSoFar)
059            {   highestVoteSoFar = e.getValue();
060                predictedClassVal = e.getKey();
061            }
062        }
063        return values.get(predictedClassVal);
064    }
065
066}