Example usage for weka.core Instances add

List of usage examples for weka.core Instances add

Introduction

In this page you can find the example usage for weka.core Instances add.

Prototype

@Override
public boolean add(Instance instance) 

Source Link

Document

Adds one instance to the end of the set.

Usage

From source file:mulan.classifier.transformation.TwoStageClassifierChainArchitecture.java

License:Open Source License

@Override
protected void buildInternal(MultiLabelInstances trainingSet) throws Exception {
    // Virtual label models
    debug("Building calibration label models");
    virtualLabelModels = new BinaryRelevance(getBaseClassifier());
    virtualLabelModels.setDebug(getDebug());
    virtualLabelModels.build(trainingSet);

    //Generate the chain: Test the same dataset
    MultiLabelInstances tempTrainingSet = GenerateChain(trainingSet);

    labelIndices = tempTrainingSet.getLabelIndices();
    featureIndices = tempTrainingSet.getFeatureIndices();

    // One-vs-one models
    numModels = ((numLabels) * (numLabels - 1)) / 2;
    oneVsOneModels = AbstractClassifier.makeCopies(getBaseClassifier(), numModels);
    nodata = new boolean[numModels];
    metaDataTest = new Instances[numModels];

    Instances trainingData = tempTrainingSet.getDataSet();

    int counter = 0;
    // Creation of one-vs-one models
    for (int label1 = 0; label1 < numLabels - 1; label1++) {
        // Attribute of label 1
        Attribute attrLabel1 = trainingData.attribute(labelIndices[label1]);
        for (int label2 = label1 + 1; label2 < numLabels; label2++) {
            debug("Building one-vs-one model " + (counter + 1) + "/" + numModels);
            // Attribute of label 2
            Attribute attrLabel2 = trainingData.attribute(labelIndices[label2]);

            // initialize training set
            Instances dataOneVsOne = new Instances(trainingData, 0);
            // filter out examples with no preference
            for (int i = 0; i < trainingData.numInstances(); i++) {
                Instance tempInstance;//from  w  w w .  j  a v  a  2s  .  c  om
                if (trainingData.instance(i) instanceof SparseInstance) {
                    tempInstance = new SparseInstance(trainingData.instance(i));
                } else {
                    tempInstance = new DenseInstance(trainingData.instance(i));
                }

                int nominalValueIndex;
                nominalValueIndex = (int) tempInstance.value(labelIndices[label1]);
                String value1 = attrLabel1.value(nominalValueIndex);
                nominalValueIndex = (int) tempInstance.value(labelIndices[label2]);
                String value2 = attrLabel2.value(nominalValueIndex);

                if (!value1.equals(value2)) {
                    tempInstance.setValue(attrLabel1, value1);
                    dataOneVsOne.add(tempInstance);
                }
            }

            // remove all labels apart from label1 and place it at the end
            Reorder filter = new Reorder();
            int numPredictors = trainingData.numAttributes() - numLabels;
            int[] reorderedIndices = new int[numPredictors + 1];

            System.arraycopy(featureIndices, 0, reorderedIndices, 0, numPredictors);
            reorderedIndices[numPredictors] = labelIndices[label1];
            filter.setAttributeIndicesArray(reorderedIndices);
            filter.setInputFormat(dataOneVsOne);
            dataOneVsOne = Filter.useFilter(dataOneVsOne, filter);
            //System.out.println(dataOneVsOne.toString());
            dataOneVsOne.setClassIndex(numPredictors);

            // build model label1 vs label2
            if (dataOneVsOne.size() > 0) {
                oneVsOneModels[counter].buildClassifier(dataOneVsOne);
            } else {
                nodata[counter] = true;
            }
            dataOneVsOne.delete();
            metaDataTest[counter] = dataOneVsOne;
            counter++;
        }
    }
}

From source file:mulan.classifier.transformation.TwoStagePrunedClassifierChainArchitecture.java

License:Open Source License

@Override
protected void buildInternal(MultiLabelInstances trainingSet) throws Exception {
    // Virtual label models
    debug("Building calibration label models");
    virtualLabelModels = new BinaryRelevance(getBaseClassifier());
    virtualLabelModels.setDebug(getDebug());
    virtualLabelModels.build(trainingSet);

    // One-vs-one models
    numModels = ((numLabels) * (numLabels - 1)) / 2;
    oneVsOneModels = AbstractClassifier.makeCopies(getBaseClassifier(), numModels);
    nodata = new boolean[numModels];
    metaDataTest = new Instances[numModels];

    ArrayList<MultiLabelOutput> predictions;
    predictions = predictLabels(trainingSet);

    int counter = 0;
    // Creation of one-vs-one models
    for (int label1 = 0; label1 < numLabels - 1; label1++) {
        for (int label2 = label1 + 1; label2 < numLabels; label2++) {
            //Generate the chain: Test the same dataset
            MultiLabelInstances tempTrainingSet = GenerateChain(trainingSet, label1, label2, predictions);

            Instances trainingData = tempTrainingSet.getDataSet();

            labelIndices = tempTrainingSet.getLabelIndices();
            featureIndices = tempTrainingSet.getFeatureIndices();

            // Attribute of label 1
            Attribute attrLabel1 = trainingData.attribute(labelIndices[label1]);

            debug("Building one-vs-one model " + (counter + 1) + "/" + numModels);
            // Attribute of label 2
            Attribute attrLabel2 = trainingData.attribute(labelIndices[label2]);

            // initialize training set
            Instances dataOneVsOne = new Instances(trainingData, 0);
            // filter out examples with no preference
            for (int i = 0; i < trainingData.numInstances(); i++) {
                Instance tempInstance;//w  ww.  ja v  a  2  s.  co  m
                if (trainingData.instance(i) instanceof SparseInstance) {
                    tempInstance = new SparseInstance(trainingData.instance(i));
                } else {
                    tempInstance = new DenseInstance(trainingData.instance(i));
                }

                int nominalValueIndex;
                nominalValueIndex = (int) tempInstance.value(labelIndices[label1]);
                String value1 = attrLabel1.value(nominalValueIndex);
                nominalValueIndex = (int) tempInstance.value(labelIndices[label2]);
                String value2 = attrLabel2.value(nominalValueIndex);

                if (!value1.equals(value2)) {
                    tempInstance.setValue(attrLabel1, value1);
                    dataOneVsOne.add(tempInstance);
                }
            }

            // remove all labels apart from label1 and place it at the end
            Reorder filter = new Reorder();
            int numPredictors = trainingData.numAttributes() - numLabels;
            int[] reorderedIndices = new int[numPredictors + 1];
            System.arraycopy(featureIndices, 0, reorderedIndices, 0, numPredictors);
            reorderedIndices[numPredictors] = labelIndices[label1];
            filter.setAttributeIndicesArray(reorderedIndices);
            filter.setInputFormat(dataOneVsOne);
            dataOneVsOne = Filter.useFilter(dataOneVsOne, filter);
            //System.out.println(dataOneVsOne.toString());
            dataOneVsOne.setClassIndex(numPredictors);

            // build model label1 vs label2
            if (dataOneVsOne.size() > 0) {
                oneVsOneModels[counter].buildClassifier(dataOneVsOne);
            } else {
                nodata[counter] = true;
            }
            dataOneVsOne.delete();
            metaDataTest[counter] = dataOneVsOne;
            counter++;
        }
    }
}

From source file:mulan.data.ConverterCLUS.java

License:Open Source License

/**
 * Converts the original dataset to mulan compatible dataset.
 *
 * @param sourceFilename the source file name
 * @param arffFilename the converted arff name
 * @param xmlFilename the xml name/* www  . j a  v a  2  s . co m*/
 * @throws java.lang.Exception
 */
public static void convert(String sourceFilename, String arffFilename, String xmlFilename) throws Exception {
    String line;
    try {
        BufferedReader brInput = new BufferedReader(new FileReader(sourceFilename));

        String relationName = null;
        ArrayList<Attribute> attInfo = new ArrayList<Attribute>();
        Instances data = null;
        int numAttributes = 0;
        String[] labelNames = null;
        while ((line = brInput.readLine()) != null) {
            if (line.startsWith("@RELATION")) {
                relationName = line.replace("@RELATION ", "").replaceAll("'", "").trim();
                continue;
            }
            if (line.startsWith("@ATTRIBUTE ")) {
                String tokens[] = line.split("\\s+");
                Attribute att;
                if (line.startsWith("@ATTRIBUTE class")) {
                    labelNames = tokens[3].split(",");
                    for (int i = 0; i < labelNames.length; i++) {
                        ArrayList<String> labelValues = new ArrayList<String>();
                        labelValues.add("0");
                        labelValues.add("1");
                        att = new Attribute(labelNames[i], labelValues);
                        attInfo.add(att);
                    }
                } else {
                    numAttributes++;
                    if (tokens[2].equals("numeric")) {
                        att = new Attribute(tokens[1]);
                    } else {
                        ArrayList<String> nominalValues = new ArrayList<String>();
                        tokens[2].substring(1, tokens[2].length() - 1);
                        String[] nominalTokens = tokens[2].substring(1, tokens[2].length() - 1).split(",");
                        for (int i = 0; i < nominalTokens.length; i++) {
                            nominalValues.add(nominalTokens[i]);
                        }
                        att = new Attribute(tokens[1], nominalValues);
                    }
                    attInfo.add(att);
                }
                continue;
            }
            if (line.toLowerCase().startsWith("@data")) {
                data = new Instances(relationName, attInfo, 0);
                while ((line = brInput.readLine()) != null) {
                    // fill data
                    String[] tokens = line.split(",");
                    double[] values = new double[attInfo.size()];
                    for (int i = 0; i < numAttributes; i++) {
                        Attribute att = (Attribute) attInfo.get(i);
                        if (att.isNumeric()) {
                            values[i] = Double.parseDouble(tokens[i]);
                        } else {
                            values[i] = att.indexOfValue(tokens[i]);
                        }
                    }
                    String[] labels = tokens[numAttributes].split("@");
                    // fill class values
                    for (int j = 0; j < labels.length; j++) {
                        String[] splitedLabels = labels[j].split("/");
                        String attrName = splitedLabels[0];
                        Attribute att = data.attribute(attrName);
                        values[attInfo.indexOf(att)] = 1;
                        for (int k = 1; k < splitedLabels.length; k++) {
                            attrName = attrName + "/" + splitedLabels[k];
                            att = data.attribute(attrName);
                            values[attInfo.indexOf(att)] = 1;
                        }
                    }
                    Instance instance = new DenseInstance(1, values);
                    data.add(instance);
                }
            }
        }
        BufferedWriter writer;
        writer = new BufferedWriter(new FileWriter(arffFilename));
        writer.write(data.toString());
        writer.close();

        // write xml file
        writer = new BufferedWriter(new FileWriter(xmlFilename));
        writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
        writer.write("<labels xmlns=\"http://mulan.sourceforge.net/labels\">\n");
        writer.write("<label name=\"" + labelNames[0] + "\">");
        int depth = 0;
        for (int i = 1; i < labelNames.length; i++) {
            int difSlashes = countSlashes(labelNames[i]) - countSlashes(labelNames[i - 1]);
            // child
            if (difSlashes == 1) {
                depth++;
                writer.write("\n");
                for (int j = 0; j < depth; j++) {
                    writer.write("\t");
                }
                writer.write("<label name=\"" + labelNames[i] + "\">");
            }
            // sibling
            if (difSlashes == 0) {
                writer.write("</label>\n");
                for (int j = 0; j < depth; j++) {
                    writer.write("\t");
                }
                writer.write("<label name=\"" + labelNames[i] + "\">");
            }
            // ancestor
            if (difSlashes < 0) {
                writer.write("</label>\n");
                for (int j = 0; j < Math.abs(difSlashes); j++) {
                    depth--;
                    for (int k = 0; k < depth; k++) {
                        writer.write("\t");
                    }
                    writer.write("</label>\n");
                }
                for (int j = 0; j < depth; j++) {
                    writer.write("\t");
                }
                writer.write("<label name=\"" + labelNames[i] + "\">");
            }
        }
        writer.write("</label>\n");
        while (depth > 0) {
            for (int k = 0; k < depth; k++) {
                writer.write("\t");
            }
            writer.write("</label>\n");
            depth--;
        }
        writer.write("</labels>");
        writer.close();

    } catch (IOException ioEx) {
        ioEx.printStackTrace();
    }
}

From source file:mulan.data.IterativeStratification.java

License:Open Source License

private Instances[] takeTheInstancesOfTheLabel(Instances workingSet, int numLabels, int[] labelIndices,
        int[] desiredLabel) {

    // In the returnedInstance in the [0] index is the filtered instances for the desired label 
    // while on the [1] index is the remaining workingSet returned
    Instances[] returnedInstances = new Instances[2];

    Instances filteredInstancesOfLabel = new Instances(workingSet, 0);
    int numInstances = workingSet.numInstances();
    boolean[] trueLabels = new boolean[numLabels];
    int[] removedIndexes = new int[desiredLabel[1]];

    int count = 0;
    // Firstly I filter the instances that are annotated with the label
    // desiredLabel[0] and I keep the indexes of the filtered instances
    for (int instanceIndex = 0; instanceIndex < numInstances; instanceIndex++) {
        Instance instance = workingSet.instance(instanceIndex);
        trueLabels = getTrueLabels(instance, numLabels, labelIndices);
        if (trueLabels[desiredLabel[0]] == true) {
            filteredInstancesOfLabel.add(instance);
            removedIndexes[count] = instanceIndex;
            count++;// w  ww  . j a va  2 s  .  co m
        }
    }

    // Using the indexes of the filtered instances i remove them from the
    // working set. CAUTION: I count in inverse order to make the removal in
    // the proper way
    for (int k = count - 1; k >= 0; k--) {
        workingSet.delete(removedIndexes[k]);
    }

    returnedInstances[0] = filteredInstancesOfLabel;
    returnedInstances[1] = workingSet;
    return returnedInstances;

}

From source file:mulan.data.LabelPowersetStratification.java

License:Open Source License

public MultiLabelInstances[] stratify(MultiLabelInstances data, int folds) {
    try {//from  w w w.  ja v a 2 s.c om
        MultiLabelInstances[] segments = new MultiLabelInstances[folds];
        LabelPowersetTransformation transformation = new LabelPowersetTransformation();
        Instances transformed;

        // transform to single-label
        transformed = transformation.transformInstances(data);

        // add id 
        Add add = new Add();
        add.setAttributeIndex("first");
        add.setAttributeName("instanceID");
        add.setInputFormat(transformed);
        transformed = Filter.useFilter(transformed, add);
        for (int i = 0; i < transformed.numInstances(); i++) {
            transformed.instance(i).setValue(0, i);
        }
        transformed.setClassIndex(transformed.numAttributes() - 1);

        // stratify
        transformed.randomize(new Random(seed));
        transformed.stratify(folds);

        for (int i = 0; i < folds; i++) {
            //System.out.println("Fold " + (i + 1) + "/" + folds);
            Instances temp = transformed.testCV(folds, i);
            Instances test = new Instances(data.getDataSet(), 0);
            for (int j = 0; j < temp.numInstances(); j++) {
                test.add(data.getDataSet().instance((int) temp.instance(j).value(0)));
            }
            segments[i] = new MultiLabelInstances(test, data.getLabelsMetaData());
        }
        return segments;
    } catch (Exception ex) {
        Logger.getLogger(LabelPowersetStratification.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:mulan.transformations.IncludeLabelsTransformation.java

License:Open Source License

/**
 *
 * @param mlData multi-label data/*from  w  w  w . j  a  v a 2  s .  co  m*/
 * @return transformed instances
 * @throws Exception Potential exception thrown. To be handled in an upper level.
 */
public Instances transformInstances(MultiLabelInstances mlData) throws Exception {
    int numLabels = mlData.getNumLabels();
    labelIndices = mlData.getLabelIndices();

    // remove all labels
    Instances transformed = RemoveAllLabels.transformInstances(mlData);

    // add at the end an attribute with values the label names
    ArrayList<String> labelNames = new ArrayList<String>(numLabels);
    for (int counter = 0; counter < numLabels; counter++) {
        labelNames.add(mlData.getDataSet().attribute(labelIndices[counter]).name());
    }
    Attribute attrLabel = new Attribute("Label", labelNames);
    transformed.insertAttributeAt(attrLabel, transformed.numAttributes());

    // and at the end a binary attribute
    ArrayList<String> binaryValues = new ArrayList<String>(2);
    binaryValues.add("0");
    binaryValues.add("1");
    Attribute classAttr = new Attribute("Class", binaryValues);
    transformed.insertAttributeAt(classAttr, transformed.numAttributes());

    // add instances
    transformed = new Instances(transformed, 0);
    transformed.setClassIndex(transformed.numAttributes() - 1);
    Instances data = mlData.getDataSet();
    for (int instanceIndex = 0; instanceIndex < data.numInstances(); instanceIndex++) {
        for (int labelCounter = 0; labelCounter < numLabels; labelCounter++) {
            Instance temp;
            temp = RemoveAllLabels.transformInstance(data.instance(instanceIndex), labelIndices);
            temp.setDataset(null);
            temp.insertAttributeAt(temp.numAttributes());
            temp.insertAttributeAt(temp.numAttributes());
            temp.setDataset(transformed);
            temp.setValue(temp.numAttributes() - 2, (String) labelNames.get(labelCounter));
            if (data.attribute(labelIndices[labelCounter])
                    .value((int) data.instance(instanceIndex).value(labelIndices[labelCounter])).equals("1")) {
                temp.setValue(temp.numAttributes() - 1, "1");
            } else {
                temp.setValue(temp.numAttributes() - 1, "0");
            }
            transformed.add(temp);
        }
    }

    return transformed;
}

From source file:mulan.transformations.multiclass.MultiClassTransformationBase.java

License:Open Source License

public Instances transformInstances(MultiLabelInstances mlData) throws Exception {
    labelIndices = mlData.getLabelIndices();
    numOfLabels = mlData.getNumLabels();
    Instances data = mlData.getDataSet();

    Instances transformed = new Instances(mlData.getDataSet(), 0);

    // delete all labels
    transformed = RemoveAllLabels.transformInstances(transformed, labelIndices);

    // add single label attribute
    ArrayList<String> classValues = new ArrayList<String>(numOfLabels);
    for (int x = 0; x < numOfLabels; x++) {
        classValues.add("Class" + (x + 1));
    }//  ww w .j  a  va2s  .c o m
    Attribute newClass = new Attribute("Class", classValues);
    transformed.insertAttributeAt(newClass, transformed.numAttributes());
    transformed.setClassIndex(transformed.numAttributes() - 1);

    for (int instanceIndex = 0; instanceIndex < data.numInstances(); instanceIndex++) {
        //System.out.println(data.instance(instanceIndex).toString());
        List<Instance> result = transformInstance(data.instance(instanceIndex));
        for (Instance instance : result) {
            //System.out.println(instance.toString());
            transformed.add(instance);
            //System.out.println(transformed.instance(transformed.numInstances()-1));
        }
    }
    return transformed;
}

From source file:mulan.transformations.PairwiseTransformation.java

License:Open Source License

/**
 * Prepares the training data for two labels. 
 *
 * @param label1 first label//from w  ww  .j  ava  2 s .c  o  m
 * @param label2 second label
 * @return transformed Instances object
 */
public Instances transformInstances(int label1, int label2) {
    Instances transformed = new Instances(shell, 0);
    int[] labelIndices = data.getLabelIndices();

    int indexOfTrueLabel1;
    if (data.getDataSet().attribute(labelIndices[label1]).value(0).equals("1")) {
        indexOfTrueLabel1 = 0;
    } else {
        indexOfTrueLabel1 = 1;
    }
    int indexOfTrueLabel2;
    if (data.getDataSet().attribute(labelIndices[label2]).value(0).equals("1")) {
        indexOfTrueLabel2 = 0;
    } else {
        indexOfTrueLabel2 = 1;
    }

    for (int j = 0; j < shell.numInstances(); j++) {
        boolean value1 = ((int) data.getDataSet().instance(j).value(labelIndices[label1]) == indexOfTrueLabel1);
        boolean value2 = ((int) data.getDataSet().instance(j).value(labelIndices[label2]) == indexOfTrueLabel2);
        if (value1 != value2) {
            Instance tempInstance;
            if (shell.instance(j) instanceof SparseInstance) {
                tempInstance = new SparseInstance(shell.instance(j));
            } else {
                tempInstance = new DenseInstance(shell.instance(j));
            }
            tempInstance.setDataset(transformed);
            if (value1 == true) {
                tempInstance.setClassValue(1);
            } else {
                tempInstance.setClassValue(0);
            }
            transformed.add(tempInstance);
        }
    }
    return transformed;
}

From source file:mulan.transformations.PT6Transformation.java

License:Open Source License

public Instances transformInstances(MultiLabelInstances mlData) throws Exception {
    int numLabels = mlData.getNumLabels();
    labelIndices = mlData.getLabelIndices();

    // remove all labels
    Instances transformed = RemoveAllLabels.transformInstances(mlData);

    // add at the end an attribute with values the label names
    ArrayList<String> labelNames = new ArrayList<String>(numLabels);
    for (int counter = 0; counter < numLabels; counter++) {
        labelNames.add(mlData.getDataSet().attribute(labelIndices[counter]).name());
    }//  www . ja  va2s . co m
    Attribute attrLabel = new Attribute("Label", labelNames);
    transformed.insertAttributeAt(attrLabel, transformed.numAttributes());

    // and at the end a binary attribute
    ArrayList<String> binaryValues = new ArrayList<String>(2);
    binaryValues.add("0");
    binaryValues.add("1");
    Attribute classAttr = new Attribute("Class", binaryValues);
    transformed.insertAttributeAt(classAttr, transformed.numAttributes());

    // add instances
    transformed = new Instances(transformed, 0);
    transformed.setClassIndex(transformed.numAttributes() - 1);
    Instances data = mlData.getDataSet();
    for (int instanceIndex = 0; instanceIndex < data.numInstances(); instanceIndex++) {
        for (int labelCounter = 0; labelCounter < numLabels; labelCounter++) {
            Instance temp;
            temp = RemoveAllLabels.transformInstance(data.instance(instanceIndex), labelIndices);
            temp.setDataset(null);
            temp.insertAttributeAt(temp.numAttributes());
            temp.insertAttributeAt(temp.numAttributes());
            temp.setDataset(transformed);
            temp.setValue(temp.numAttributes() - 2, (String) labelNames.get(labelCounter));
            if (data.attribute(labelIndices[labelCounter])
                    .value((int) data.instance(instanceIndex).value(labelIndices[labelCounter])).equals("1")) {
                temp.setValue(temp.numAttributes() - 1, "1");
            } else {
                temp.setValue(temp.numAttributes() - 1, "0");
            }
            transformed.add(temp);
        }
    }

    return transformed;
}

From source file:mx.itesm.arch.mvc.MvcAnalyzer.java

License:Open Source License

/**
 * Classify each class in the specified List into one of the layers of the
 * MVC pattern.//from  w w w.ja  v a 2 s. co m
 * 
 * @param dependencies
 *            List containing the dependencies for each class to classify.
 * @param internalPackages
 *            Project's internal packages.
 * @return Map containing the classification layer for each class.
 * @throws Exception
 *             If an Exception occurs during classification.
 */
private static Map<String, Layer> classifyClasses(final List<ClassDependencies> dependencies,
        final Map<String, Set<String>> internalPackages) throws Exception {
    int viewCount;
    int modelCount;
    int instanceLayer;
    Instance instance;
    boolean valueFound;
    int controllerCount;
    Instances instances;
    String instanceType;
    String[] typeValues;
    Layer componentLayer;
    String[] suffixValues;
    Layer dependencyLayer;
    FastVector attributes;
    String[] externalApiValues;
    Map<String, Layer> returnValue;
    Set<String> currentPackageContent;
    Map<String, Layer> packagesClassification;
    Map<String, String[]> externalApiPackages;

    // Model variables
    attributes = new FastVector();
    for (Variable variable : Variable.values()) {
        attributes.addElement(variable.getAttribute());
    }

    // Layer variable
    attributes.addElement(Layer.attribute);

    // Set the test instances, the Layer variable is unknown
    instances = new Instances("mvc", attributes, 0);
    instances.setClassIndex(Variable.values().length);

    // Valid suffixes to look for in the class names
    suffixValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.Suffix.getVariableName());

    // Valid file types to look for in the component names
    typeValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.Type.getVariableName());

    // Valid external api packages to look for in the classes dependencies
    externalApiValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.ExternalAPI.getVariableName());
    externalApiPackages = new HashMap<String, String[]>(externalApiValues.length);
    for (int i = 0; i < externalApiValues.length; i++) {
        if (!externalApiValues[i].equals("none")) {
            externalApiPackages.put(externalApiValues[i],
                    MvcAnalyzer.getPropertyValues("externalApi." + externalApiValues[i] + ".packages"));
        }
    }

    returnValue = new HashMap<String, Layer>(dependencies.size());
    for (ClassDependencies classDependencies : dependencies) {
        // Variables + Layer
        instance = new Instance(Variable.values().length + 1);

        // Type
        instanceType = "java";
        for (String validType : typeValues) {
            if (classDependencies.getClassName().endsWith("." + validType)) {
                instanceType = validType;
                break;
            }
        }
        instance.setValue(Variable.Type.getAttribute(), instanceType);

        // ExternalAPI
        valueFound = false;
        externalApi: for (String externalApi : externalApiValues) {
            if (externalApi.equals("none")) {
                continue;
            }

            // Check if any of the class' external dependencies match with
            // one of the key external dependencies
            if (classDependencies.getExternalDependencies() != null) {
                for (String externalDependency : classDependencies.getExternalDependencies()) {
                    for (String externalPackage : externalApiPackages.get(externalApi)) {
                        if (externalDependency.toLowerCase().startsWith(externalPackage)) {
                            valueFound = true;
                            instance.setValue(Variable.ExternalAPI.getAttribute(), externalApi);
                            break externalApi;
                        }
                    }
                }
            }
        }

        // No key external dependency found
        if (!valueFound) {
            instance.setValue(Variable.ExternalAPI.getAttribute(), "none");
        }

        // Suffix
        valueFound = false;
        for (String suffix : suffixValues) {
            if (classDependencies.getClassName().toLowerCase().endsWith(suffix)) {
                valueFound = true;
                instance.setValue(Variable.Suffix.getAttribute(), suffix);
                break;
            }
        }

        // No key suffix found
        if (!valueFound) {
            instance.setValue(Variable.Suffix.getAttribute(), "none");
        }

        // Layer, the unknown variable
        instance.setMissing(Layer.attribute);
        instances.add(instance);
        instance.setDataset(instances);

        try {
            instanceLayer = (int) MvcAnalyzer.classifier.classifyInstance(instance);
        } catch (Exception e) {
            // Default value
            instanceLayer = 0;
            logger.severe("Unable to classify: " + instance);
        }

        returnValue.put(classDependencies.getClassName(), Layer.values()[instanceLayer]);
        logger.info(
                classDependencies.getClassName() + " : " + returnValue.get(classDependencies.getClassName()));
    }

    // Check for any invalid relation
    packagesClassification = new HashMap<String, Layer>(internalPackages.size());
    for (String currentPackage : internalPackages.keySet()) {
        modelCount = viewCount = controllerCount = 0;
        currentPackageContent = internalPackages.get(currentPackage);

        for (String component : currentPackageContent) {
            componentLayer = returnValue.get(component);
            if (componentLayer == Layer.Model) {
                modelCount++;
            } else if (componentLayer == Layer.View) {
                viewCount++;
            } else if (componentLayer == Layer.Controller) {
                controllerCount++;
            }
        }

        if ((modelCount > viewCount) && (modelCount > controllerCount)) {
            packagesClassification.put(currentPackage, Layer.Model);
        } else if ((viewCount > modelCount) && (viewCount > controllerCount)) {
            packagesClassification.put(currentPackage, Layer.View);
        } else if ((controllerCount > viewCount) && (controllerCount > modelCount)) {
            packagesClassification.put(currentPackage, Layer.Controller);
        } else {
            packagesClassification.put(currentPackage, null);
        }
    }

    for (ClassDependencies classDependencies : dependencies) {
        // Code relations
        valueFound = false;
        componentLayer = returnValue.get(classDependencies.getClassName());
        if (classDependencies.getInternalDependencies() != null) {
            for (String internalDependency : classDependencies.getInternalDependencies()) {
                dependencyLayer = returnValue.get(internalDependency);

                if (!componentLayer.isValidRelation(dependencyLayer)) {
                    valueFound = true;
                    returnValue.put(classDependencies.getClassName(),
                            Layer.valueOf("Invalid" + componentLayer));
                    logger.info("Invalid relation detected between: " + classDependencies.getClassName()
                            + " and " + internalDependency);
                }
            }
        }

        // Package relations
        if (!valueFound) {
            dependencyLayer = packagesClassification.get(classDependencies.getPackageName());

            if ((dependencyLayer != null) && (componentLayer != dependencyLayer)) {
                returnValue.put(classDependencies.getClassName(), Layer.valueOf("Invalid" + componentLayer));
            }
        }
    }

    return returnValue;
}