index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/util/TimeSeriesUtil.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception.TimeSeriesLengthException; /** * Utility class for time series operations. */ public class TimeSeriesUtil { private TimeSeriesUtil() { /* avoid instantiation */ } /** * Checks, whether given INDArray are valid time series. * * @param array * @return True, if the all arrays are valid time series. */ public static boolean isTimeSeries(final INDArray... array) { for (INDArray a : array) { if (a.rank() != 1) { return false; } } return true; } /** * Checks, whether given INDArrays are valid time series with a given length. * * @param array * @param length * @return True, if the array is a valid time series of the given length. False, * otherwise. */ public static boolean isTimeSeries(final int length, final INDArray... array) { for (INDArray a : array) { if (a.rank() != 1 && a.length() == length) { return false; } } return true; } /** * Checks, whether given array are valid time series with a given length. * * @param array * @param length * @return True, if the array is a valid time series of the given length. False, * otherwise. */ public static boolean isTimeSeries(final int length, final double[]... array) { for (double[] a : array) { if (a.length != length) { return false; } } return true; } /** * Checks, whether given INDArrays are valid time series. Throws an exception * otherwise. * * @param array * @throws IllegalArgumentException */ public static void isTimeSeriesOrException(final INDArray... array) { for (INDArray a : array) { if (!isTimeSeries(array)) { String message = String.format("The given INDArray is no time series. It should have rank 1, but has a rank of %d.", a.rank()); throw new IllegalArgumentException(message); } } } /** * Checks, whether given INDArrays are valid time series with a given length. * Throws an exception otherwise. * * @param array * @param length * @throws IllegalArgumentException */ public static void isTimeSeriesOrException(final int length, final INDArray... array) { for (INDArray a : array) { if (!isTimeSeries(array)) { String message = String.format("The given INDArray is no time series. It should have rank 1, but has a rank of %d.", a.rank()); throw new IllegalArgumentException(message); } if (!isTimeSeries(length, a)) { String message = String.format("The given time series should length 7, but has a length of %d.", a.length()); throw new IllegalArgumentException(message); } } } /** * Checks, whether given INDArrays are valid time series with a given length. * Throws an exception otherwise. * * @param array * @param length * @throws IllegalArgumentException */ public static void isTimeSeriesOrException(final int length, final double[]... array) { for (double[] a : array) { if (!isTimeSeries(length, a)) { String message = String.format("The given time series should length 7, but has a length of %d.", a.length); throw new IllegalArgumentException(message); } } } /** * Checks whether multiple arrays have the same length. * * @param timeSeries1 * @param timeSeries2 * @return True if the arrays have the same length. False, otherwise. */ public static boolean isSameLength(final INDArray timeSeries1, final INDArray... timeSeries) { for (INDArray t : timeSeries) { if (timeSeries1.length() != t.length()) { return false; } } return true; } /** * Checks whether multiple arrays have the same length. * * @param timeSeries1 * @param timeSeries2 * @return True if the arrays have the same length. False, otherwise. */ public static boolean isSameLength(final double[] timeSeries1, final double[]... timeSeries) { for (double[] t : timeSeries) { if (timeSeries1.length != t.length) { return false; } } return true; } /** * Checks whether multiple arrays have the same length. Throws an exception * otherwise. * * @param timeSeries1 * @param timeSeries2 * @throws TimeSeriesLengthException */ public static void isSameLengthOrException(final INDArray timeSeries1, final INDArray... timeSeries) { for (INDArray t : timeSeries) { if (!isSameLength(timeSeries1, t)) { String message = String.format("Length of the given time series are not equal: Length first time series: (%d). Length of seconds time series: (%d)", timeSeries1.length(), t.length()); throw new TimeSeriesLengthException(message); } } } /** * Checks whether multiple arrays have the same length. Throws an exception * otherwise. * * @param timeSeries1 * @param timeSeries2 * @throws TimeSeriesLengthException */ public static void isSameLengthOrException(final double[] timeSeries1, final double[]... timeSeries) { for (double[] t : timeSeries) { if (!isSameLength(timeSeries1, t)) { String message = String.format("Length of the given time series are not equal: Length first time series: (%d). Length of seconds time series: (%d)", timeSeries1.length, t.length); throw new TimeSeriesLengthException(message); } } } /** * Creates equidistant timestamps for a time series. * * @param timeSeries Time series to generate timestamps for. Let n be its * length. * @return Equidistant timestamp, i.e. {0, 1, .., n-1}. */ public static INDArray createEquidistantTimestamps(final INDArray timeSeries) { int n = (int) timeSeries.length(); double[] timestamps = IntStream.range(0, n).mapToDouble(t -> (double) t).toArray(); int[] shape = { n }; return Nd4j.create(timestamps, shape); } /** * Creates equidistant timestamps for a time series. * * @param timeSeries Time series to generate timestamps for. Let n be its * length. * @return Equidistant timestamp, i.e. {0, 1, .., n-1}. */ public static double[] createEquidistantTimestamps(final double[] timeSeries) { int n = timeSeries.length; return IntStream.range(0, n).mapToDouble(t -> (double) t).toArray(); } /** * Function extracting the interval [start, end (exclusive)] out of the given * <code>timeSeries</code> vector. * * @param timeSeries Time series vector source * @param start Start of the interval * @param end End index of the interval (exclusive) * @return Returns the specified interval as a double array */ public static double[] getInterval(final double[] timeSeries, final int start, final int end) { if (end <= start) { throw new IllegalArgumentException("The end index must be greater than the start index."); } final double[] result = new double[end - start]; for (int j = 0; j < end - start; j++) { result[j] = timeSeries[j + start]; } return result; } /** * Normalizes an INDArray vector object. * * @param array INDArray row vector with single shape dimension * @param inplace Indication whether the normalization should be performed in * place or on a new array copy * @return Returns the view on the transformed INDArray (if inplace) or a * normalized copy of the input array (if not inplace) */ public static INDArray normalizeINDArray(final INDArray array, final boolean inplace) { if (array.shape().length > 2 && array.shape()[0] != 1) { throw new IllegalArgumentException(String.format("Input INDArray object must be a vector with shape size 1. Actual shape: (%s)", Arrays.toString(array.shape()))); } final double mean = array.mean(1).getDouble(0); final double std = array.std(1).getDouble(0); INDArray result; if (inplace) { result = array.subi(mean); } else { result = array.sub(mean); } return result.addi(Nd4j.EPS_THRESHOLD).divi(std); } /** * Returns the mode of the given <code>array</code>. If there are multiple * values with the same frequency, the lower value will be taken. * * @param array The array which mode should be returned * @return Returns the mode, i. e. the most frequently occurring int value */ public static int getMode(final int[] array) { HashMap<Integer, Integer> statistics = new HashMap<>(); for (int i = 0; i < array.length; i++) { if (!statistics.containsKey(array[i])) { statistics.put(array[i], 1); } else { statistics.replace(array[i], statistics.get(array[i]) + 1); } } return getMaximumKeyByValue(statistics) != null ? getMaximumKeyByValue(statistics) : -1; } /** * Returns the key with the maximum integer value. If there are multiple values * with the same value, the lower key with regard to its type will be taken. * * @param map The map storing the keys with its corresponding integer values * @return Returns the key of type <T> storing the maximum integer value */ public static <T> T getMaximumKeyByValue(final Map<T, Integer> map) { T maxKey = null; int maxCount = 0; for (Entry<T, Integer> entry : map.entrySet()) { T key = entry.getKey(); int val = entry.getValue(); if (val > maxCount) { maxCount = val; maxKey = key; } } return maxKey; } /** * Z-normalizes a given <code>dataVector</code>. Uses Bessel's correction * (1/(n-1) in the calculation of the standard deviation) if set. * * @param dataVector Vector to be z-normalized * @param besselsCorrection Indicator whether the std dev correction using n-1 * instead of n should be applied * @return Z-normalized vector */ public static double[] zNormalize(final double[] dataVector, final boolean besselsCorrection) { int n = dataVector.length - (besselsCorrection ? 1 : 0); double mean = 0; for (int i = 0; i < dataVector.length; i++) { mean += dataVector[i]; } mean /= dataVector.length; // Use Bessel's correction to get the sample stddev double stddev = 0; for (int i = 0; i < dataVector.length; i++) { stddev += Math.pow(dataVector[i] - mean, 2); } stddev /= n; stddev = Math.sqrt(stddev); double[] result = new double[dataVector.length]; if (stddev == 0.0) { return result; } for (int i = 0; i < result.length; i++) { result[i] = (dataVector[i] - mean) / stddev; } return result; } /** * Sorts the indices of the given <code>vector</code> based on the the vector's * values (argsort). * * @param vector Vector where the values are extracted from * @param ascending Indicator whether the indices should be sorted ascending * @return Returns the list of indices which are sorting based on the vector's * values */ public static List<Integer> sortIndexes(final double[] vector, final boolean ascending) { Integer[] indexes = new Integer[vector.length]; for (int i = 0; i < indexes.length; i++) { indexes[i] = i; } Arrays.sort(indexes, (i1, i2) -> (ascending ? 1 : -1) * Double.compare(Math.abs(vector[i1]), Math.abs(vector[i2]))); return Arrays.asList(indexes); } /** * Counts the number of unique classes occurring in the given * <code>dataset</code>. * * @param dataset Dataset to be evaluated * @return Returns the number of unique classes occurring in target matrix of * the given <code>dataset</code> */ public static int getNumberOfClasses(final TimeSeriesDataset2 dataset) { if (dataset == null || dataset.getTargets() == null) { throw new IllegalArgumentException("Given parameter 'dataset' must not be null and must contain a target matrix!"); } return getClassesInDataset(dataset).size(); } /** * Returns a list storing the unique Integer class values in the given * <code>dataset</code>. * * @param dataset Dataset to be evaluated * @return Returns a {@link java.util.List} object storing the unique Integer * class values of the dataset */ public static List<Integer> getClassesInDataset(final TimeSeriesDataset2 dataset) { if (dataset == null || dataset.getTargets() == null) { throw new IllegalArgumentException("Given parameter 'dataset' must not be null and must contain a target matrix!"); } return IntStream.of(dataset.getTargets()).boxed().collect(Collectors.toSet()).stream().collect(Collectors.toList()); } /** * Shuffles the given {@link TimeSeriesDataset2} object using the given * <code>seed</code>. * * @param dataset The dataset to be shuffled * @param seed The seed used within the randomized shuffling */ public static void shuffleTimeSeriesDataset(final TimeSeriesDataset2 dataset, final int seed) { List<Integer> indices = IntStream.range(0, dataset.getNumberOfInstances()).boxed().collect(Collectors.toList()); Collections.shuffle(indices, new Random(seed)); List<double[][]> valueMatrices = dataset.getValueMatrices(); List<double[][]> timestampMatrices = dataset.getTimestampMatrices(); int[] targets = dataset.getTargets(); if (valueMatrices != null) { List<double[][]> targetValueMatrices = new ArrayList<>(); for (int i = 0; i < valueMatrices.size(); i++) { targetValueMatrices.add(shuffleMatrix(valueMatrices.get(i), indices)); } dataset.setValueMatrices(targetValueMatrices); } if (timestampMatrices != null) { List<double[][]> targetTimestampMatrices = new ArrayList<>(); for (int i = 0; i < timestampMatrices.size(); i++) { targetTimestampMatrices.add(shuffleMatrix(timestampMatrices.get(i), indices)); } dataset.setTimestampMatrices(targetTimestampMatrices); } if (targets != null) { dataset.setTargets(shuffleMatrix(targets, indices)); } } /** * Shuffles the given <code>srcMatrix</code> using a list of Integer * <code>indices</code>. It copies the values into a new result array sharing * the dimensionality of <code>srcMatrix</code>. * * @param srcMatrix The source matrix to be shuffled * @param indices The Integer indices representing the new shuffled order * @return Returns the matrix copied from the given source matrix and the * indices */ private static double[][] shuffleMatrix(final double[][] srcMatrix, final List<Integer> indices) { if (srcMatrix == null || srcMatrix.length < 1) { throw new IllegalArgumentException("Parameter 'srcMatrix' must not be null or empty!"); } if (indices == null || indices.size() != srcMatrix.length) { throw new IllegalArgumentException("Parameter 'indices' must not be null and must have the same length as the number of instances in the source matrix!"); } final double[][] result = new double[srcMatrix.length][srcMatrix[0].length]; for (int i = 0; i < indices.size(); i++) { result[i] = srcMatrix[indices.get(i)]; } return result; } /** * Shuffles the given <code>srcMatrix</code> using a list of Integer * <code>indices</code>. It copies the values into a new result array sharing * the dimensionality of <code>srcMatrix</code>. * * @param srcMatrix The source matrix to be shuffled * @param indices The Integer indices representing the new shuffled order * @return Returns the matrix copied from the given source matrix and the * indices */ private static int[] shuffleMatrix(final int[] srcMatrix, final List<Integer> indices) { if (srcMatrix == null || srcMatrix.length < 1) { throw new IllegalArgumentException("Parameter 'srcMatrix' must not be null or empty!"); } if (indices == null || indices.size() != srcMatrix.length) { throw new IllegalArgumentException("Parameter 'indices' must not be null and must have the same length as the number of instances in the source matrix!"); } final int[] result = new int[srcMatrix.length]; for (int i = 0; i < indices.size(); i++) { result[i] = srcMatrix[indices.get(i)]; } return result; } /** * Functions creating two {@link TimeSeriesDataset2} objects representing the * training and test split for the given <code>fold</code> of a cross validation * with <code>numFolds</code> many folds. Data is extracted (and copied) from * the given <code>srcValueMatrix</code> and <code>srcTargetMatrix</code>. The * function uses the two functions * {@link TimeSeriesUtil#selectTrainingDataForFold(int, int, int, int, double[][], int[])} * and * {@link TimeSeriesUtil#selectTestDataForFold(int, int, int, int, double[][], int[])}. * * @param fold The current fold for which the datasets should be * prepared * @param numFolds Number of total folds using within the performed cross * validation * @param srcValueMatrix Source dataset from which the instances are copied * @param srcTargetMatrix Source targets from which the targets are copied * @return Returns a pair consisting of the training and test dataset */ public static Pair<TimeSeriesDataset2, TimeSeriesDataset2> getTrainingAndTestDataForFold(final int fold, final int numFolds, final double[][] srcValueMatrix, final int[] srcTargetMatrix) { return new Pair<>(selectTrainingDataForFold(fold, numFolds, srcValueMatrix, srcTargetMatrix), selectTestDataForFold(fold, numFolds, srcValueMatrix, srcTargetMatrix)); } /** * Generates the training dataset for a fold. See * {@link TimeSeriesUtil#getTrainingAndTestDataForFold(int, int, int, int, double[][], int[]) * for further details. * * @param fold The current fold for which the datasets should be * prepared * @param numFolds Number of total folds using within the performed cross * validation * @param srcValueMatrix Source dataset from which the instances are copied * @param srcTargetMatrix Source targets from which the targets are copied * @return Returns a pair consisting of the training and test dataset */ private static TimeSeriesDataset2 selectTrainingDataForFold(final int fold, final int numFolds, final double[][] srcValueMatrix, final int[] srcTargetMatrix) { int numTestInstsPerFold = (int) ((double) srcValueMatrix.length / (double) numFolds); double[][] destValueMatrix = new double[(numFolds - 1) * numTestInstsPerFold][srcValueMatrix[0].length]; int[] destTargetMatrix = new int[(numFolds - 1) * numTestInstsPerFold]; if (fold == 0) { // First fold System.arraycopy(srcValueMatrix, numTestInstsPerFold, destValueMatrix, 0, (numFolds - 1) * numTestInstsPerFold); System.arraycopy(srcTargetMatrix, numTestInstsPerFold, destTargetMatrix, 0, (numFolds - 1) * numTestInstsPerFold); } else if (fold == (numFolds - 1)) { // Last fold System.arraycopy(srcValueMatrix, 0, destValueMatrix, 0, (numFolds - 1) * numTestInstsPerFold); System.arraycopy(srcTargetMatrix, 0, destTargetMatrix, 0, (numFolds - 1) * numTestInstsPerFold); } else { // Inner folds System.arraycopy(srcValueMatrix, 0, destValueMatrix, 0, fold * numTestInstsPerFold); System.arraycopy(srcValueMatrix, (fold + 1) * numTestInstsPerFold, destValueMatrix, fold * numTestInstsPerFold, (numFolds - fold - 1) * numTestInstsPerFold); System.arraycopy(srcTargetMatrix, 0, destTargetMatrix, 0, fold * numTestInstsPerFold); System.arraycopy(srcTargetMatrix, (fold + 1) * numTestInstsPerFold, destTargetMatrix, fold * numTestInstsPerFold, (numFolds - fold - 1) * numTestInstsPerFold); } ArrayList<double[][]> valueMatrices = new ArrayList<>(); valueMatrices.add(destValueMatrix); return new TimeSeriesDataset2(valueMatrices, destTargetMatrix); } /** * Generates the test dataset for a fold. See * {@link TimeSeriesUtil#getTrainingAndTestDataForFold(int, int, int, int, double[][], int[]) * for further details. * * @param fold The current fold for which the datasets should be * prepared * @param numFolds Number of total folds using within the performed cross * validation * @param numClasses Number of classes in the targets * @param srcValueMatrix Source dataset from which the instances are copied * @param srcTargetMatrix Source targets from which the targets are copied * @return Returns a pair consisting of the training and test dataset */ private static TimeSeriesDataset2 selectTestDataForFold(final int fold, final int numFolds, final double[][] srcValueMatrix, final int[] srcTargetMatrix) { int numTestInstsPerFold = (int) ((double) srcValueMatrix.length / (double) numFolds); double[][] currTestMatrix; int[] currTestTargetMatrix; if (fold == (numFolds - 1)) { int remainingLength = srcValueMatrix.length - (numFolds - 1) * numTestInstsPerFold; currTestMatrix = new double[remainingLength][srcValueMatrix[0].length]; currTestTargetMatrix = new int[remainingLength]; } else { currTestMatrix = new double[numTestInstsPerFold][srcValueMatrix[0].length]; currTestTargetMatrix = new int[numTestInstsPerFold]; } System.arraycopy(srcValueMatrix, fold * numTestInstsPerFold, currTestMatrix, 0, currTestMatrix.length); System.arraycopy(srcTargetMatrix, fold * numTestInstsPerFold, currTestTargetMatrix, 0, currTestTargetMatrix.length); ArrayList<double[][]> testValueMatrices = new ArrayList<>(); testValueMatrices.add(currTestMatrix); return new TimeSeriesDataset2(testValueMatrices, currTestTargetMatrix); } /** * Function creating a {@link TimeSeriesDataset2} object given the * <code>targets</code> and one or multiple <code>valueMatrices</code>. * * @param targets The target values of the instances * @param valueMatrices One or more matrices storing the time series values * @return Returns a {@link TimeSeriesDataset2} object constructed out of the * given parameters */ public static TimeSeriesDataset2 createDatasetForMatrix(final int[] targets, final double[][]... valueMatrices) { if (valueMatrices.length == 0) { throw new IllegalArgumentException("There must be at least one value matrix to generate a TimeSeriesDataset object!"); } List<double[][]> values = Arrays.asList(valueMatrices); return targets == null ? new TimeSeriesDataset2(values) : new TimeSeriesDataset2(values, targets); } /** * Function creating a {@link TimeSeriesDataset2} object given one or multiple * <code>valueMatrices</code>. * * @param valueMatrices One or more matrices storing the time series values * @return Returns a {@link TimeSeriesDataset2} object constructed out of the * given parameters */ public static TimeSeriesDataset2 createDatasetForMatrix(final double[][]... valueMatrices) { return createDatasetForMatrix(null, valueMatrices); } /** * Enables printing of time series. * * @param timeSeries Time series to print. * @return Readable string of the time series, i.e. * <code>"{1.0, 2.0, 3.0, 4.0}"</code> */ public static String toString(final double[] timeSeries) { if (timeSeries.length == 0) { return "{}"; } int stringLength = 2 + timeSeries.length * 3 - 1; StringBuilder sb = new StringBuilder(stringLength); sb.append("{" + timeSeries[0]); for (int i = 1; i < timeSeries.length; i++) { sb.append(", " + timeSeries[i]); } sb.append("}"); return sb.toString(); } /** * Calculates the derivative of a timeseries as described first by Keogh and * Pazzani (2001). * <code>f'(n) = \frac{ f(n) - f(n-1) + /frac{f(i+1) - f(i-1)}{2} }{2}</code> * * @param t * @return */ public static double[] keoghDerivate(final double[] t) { double[] derivate = new double[t.length - 2]; for (int i = 1; i < t.length - 1; i++) { derivate[i - 1] = ((t[i] - t[i - 1]) + (t[i + 1] - t[i - 1]) / 2) / 2; } return derivate; } /** * Calculates the derivateive of a timeseries as described first by Keogh and * Pazzani (2001). * <code>f'(n) = \frac{ f(n) - f(n-1) + /frac{f(i+1) - f(i-1)}{2} }{2}</code> * * @param t * @return */ public static double[] keoghDerivateWithBoundaries(final double[] t) { double[] derivate = new double[t.length]; for (int i = 1; i < t.length - 1; i++) { derivate[i] = ((t[i] - t[i - 1]) + (t[i + 1] - t[i - 1]) / 2) / 2; } derivate[0] = derivate[1]; derivate[t.length - 1] = derivate[t.length - 2]; return derivate; } /** * Calclualtes f'(n) = f(n-1) - f(n) * * @param t Time series. * @return */ public static double[] backwardDifferenceDerivate(final double[] t) { double[] derivate = new double[t.length - 1]; for (int i = 1; i < t.length; i++) { derivate[i - 1] = t[i] - t[i - 1]; } return derivate; } /** * Calclualtes f'(n) = f(n-1) - f(n) * * @param t Time series. * @return */ public static double[] backwardDifferenceDerivateWithBoundaries(final double[] t) { double[] derivate = new double[t.length]; for (int i = 1; i < t.length; i++) { derivate[i] = t[i] - t[i - 1]; } derivate[0] = derivate[1]; return derivate; } /** * f'(n) = f(n+1) - f(n) * * @param t * @return */ public static double[] forwardDifferenceDerivate(final double[] t) { double[] derivate = new double[t.length - 1]; for (int i = 0; i < t.length - 1; i++) { derivate[i] = t[i + 1] - t[i]; } return derivate; } /** * f'(n) = f(n+1) - f(n) * * @param t * @return */ public static double[] forwardDifferenceDerivateWithBoundaries(final double[] t) { double[] derivate = new double[t.length]; for (int i = 0; i < t.length - 1; i++) { derivate[i] = t[i + 1] - t[i]; } derivate[t.length - 1] = derivate[t.length - 2]; return derivate; } /** * Calculates the derivative of a timeseries as described first by Gullo et. al * (2009). * * @param t * @return */ public static double[] gulloDerivate(final double[] t) { double[] derivate = new double[t.length - 1]; for (int i = 1; i < t.length; i++) { derivate[i - 1] = t[i + 1] - t[i - 1] / 2; } return derivate; } /** * f'(n) = \frac{f(i+1)-f(i-1)}{2} * * @param t * @return */ public static double[] gulloDerivateWithBoundaries(final double[] t) { double[] derivate = new double[t.length]; for (int i = 1; i < t.length; i++) { derivate[i] = t[i + 1] - t[i - 1] / 2; } derivate[0] = derivate[1]; return derivate; } public static double sum(final double[] t) { double sum = 0; for (int i = 0; i < t.length; i++) { sum += t[i]; } return sum; } public static double mean(final double[] t) { return sum(t) / t.length; } /** * Calculates the (population) variance of the values of a times series. */ public static double variance(final double[] t) { double mean = mean(t); double squaredDeviations = 0; for (int i = 0; i < t.length; i++) { squaredDeviations += (t[i] - mean) * (t[i] - mean); } return squaredDeviations / t.length; } /** * Calculates the (population) standard deviation of the values of a times * series. */ public static double standardDeviation(final double[] t) { return Math.sqrt(variance(t)); } public static double[] normalizeByStandardDeviation(final double[] t) { double standardDeviation = standardDeviation(t); if (standardDeviation == 0) { return new double[t.length]; } double[] normalizedT = new double[t.length]; for (int i = 0; i < t.length; i++) { normalizedT[i] = t[i] / standardDeviation; } return normalizedT; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/util/package-info.java
/** * This package contains utility functions for time series classification. */ package ai.libs.jaicore.ml.classification.singlelabel.timeseries.util;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/clustering/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.clustering;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/clustering
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/clustering/learner/GMeans.java
package ai.libs.jaicore.ml.clustering.learner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.ml.clustering.CentroidCluster; import org.apache.commons.math3.ml.clustering.Clusterable; import org.apache.commons.math3.ml.clustering.KMeansPlusPlusClusterer; import org.apache.commons.math3.ml.distance.DistanceMeasure; import org.apache.commons.math3.ml.distance.ManhattanDistance; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of Gmeans based on Helen Beierlings implementation of GMeans(https://github.com/helebeen/AILibs/blob/master/JAICore/jaicore-modifiedISAC/src/main/java/jaicore/modifiedISAC/ModifiedISACgMeans.java).<br> * For more Information see: "Hamerly, G., and Elkan, C. 2003. Learning the k in kmeans. in proceedings of the seventeenth annual conference on neural information processing systems (nips)". <br> * <br> * This implementation uses {@link KMeansPlusPlusClusterer} as the k-means cluster algorithm. * * @author Helen Beierling * @author jnowack * @author Felix Mohr * * @param <C> * Points to cluster. */ public class GMeans<C extends Clusterable> implements ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(GMeans.class); private List<double[]> center = new ArrayList<>(); private List<CentroidCluster<C>> gmeansCluster = new ArrayList<>(); private Map<double[], List<C>> currentPoints = new HashMap<>(); private Map<double[], List<C>> intermediatePoints = new HashMap<>(); private List<C> points = new ArrayList<>(); private DistanceMeasure distanceMeasure = new ManhattanDistance(); private RandomGenerator randomGenerator; private final int maxIterationsInInnerLoop; /** * Initializes a basic cluster for the given Point using Mannhatten distance and seed=1 * * @param toClusterPoints * Points which should be clustered */ public GMeans(final Collection<C> toClusterPoints) { this(toClusterPoints, new ManhattanDistance(), -1, 1); } /** * Initializes a cluster for the given Point using a given distance meassure and a seed. * * @param toClusterPoints * P * @param distanceMeasure * @param seed */ public GMeans(final Collection<C> toClusterPoints, final DistanceMeasure distanceMeasure, final int maxIterationsInInnerLoop, final long seed) { this.points = new ArrayList<>(toClusterPoints); this.distanceMeasure = distanceMeasure; this.gmeansCluster = new ArrayList<>(); this.randomGenerator = new JDKRandomGenerator(); this.maxIterationsInInnerLoop = maxIterationsInInnerLoop; this.randomGenerator.setSeed(seed); } public List<CentroidCluster<C>> cluster() { HashMap<Integer, double[]> positionOfCenter = new HashMap<>(); int tmp = 1; int k = 1; int i = 1; // creates a k means clustering instance with all points and an L1 distance // metric as metric KMeansPlusPlusClusterer<C> test = new KMeansPlusPlusClusterer<>(k, -1, this.distanceMeasure, this.randomGenerator); // clusters all points with k = 1 List<CentroidCluster<C>> currentPointsTemp = test.cluster(this.points); for (CentroidCluster<C> centroidCluster : currentPointsTemp) { this.currentPoints.put(centroidCluster.getCenter().getPoint(), centroidCluster.getPoints()); } // puts the first center into the list of center for (double[] d : this.currentPoints.keySet()) { this.center.add(d); } // saves the position of the center for the excess during the g-means clustering // algorithm for (double[] c : this.center) { positionOfCenter.put(tmp, c); tmp++; } while (i <= k) { // looppoints are S_i the points are the points of the considered center C_i List<C> loopPoints = this.currentPoints.get(positionOfCenter.get(i)); // makes a new instance with of kmeans with S_i as base KMeansPlusPlusClusterer<C> loopCluster = new KMeansPlusPlusClusterer<>(2, this.maxIterationsInInnerLoop, this.distanceMeasure, this.randomGenerator); /* clusters S_I into to cluster intermediate points is a HashMap of center with an ArrayList of their corresponding points */ List<double[]> intermediateCenter = new ArrayList<>(2); if (loopPoints.size() < 2) { break; } List<CentroidCluster<C>> intermediatePointsTemp = null; intermediatePointsTemp = loopCluster.cluster(loopPoints); for (CentroidCluster<C> centroidCluster : intermediatePointsTemp) { this.intermediatePoints.put(centroidCluster.getCenter().getPoint(), centroidCluster.getPoints()); // intermediate Center saves the found two Center C`_1 und C`_2 intermediateCenter.add(centroidCluster.getCenter().getPoint()); } // the difference between the two new Center double[] v = this.difference(intermediateCenter.get(0), intermediateCenter.get(1)); /* w is calculated as the summed squares of the entries of the difference between the center if the entry is NaN it is ignored in the sum */ double w = 0; boolean allNan = true; for (int l = 0; l < v.length; l++) { if (!Double.isNaN(v[l])) { w += Math.pow(v[l], 2); allNan = false; } } if (allNan) { throw new IllegalStateException("All entries in v are NaN, cannot compute w!"); } /* All points are projected onto a points by multiplying every entry of point with the corresponding entry of v and divide by the w. For every point the all entrys modified that way are than summed. if the entry of v is Nan or the entry of the point the entry is ignored */ double[] y = new double[loopPoints.size()]; for (int r = 0; r < loopPoints.size(); r++) { for (int p = 0; p < loopPoints.get(r).getPoint().length; p++) { if (Double.isNaN(loopPoints.get(r).getPoint()[p])) { this.logger.warn("Found NaN clustering reference point entry!"); } else if (Double.isNaN(v[p])) { this.logger.warn("Found NaN cluster distance entry!"); } else { y[r] += (v[p] * loopPoints.get(r).getPoint()[p]) / w; } } } /* * if the Anderson Darling test is failed the the center C_i is replaced by C`_1 and S_i is replaced by the points of C`_1. * k is raised by 1. C_k is replaced by C`_2 and the points of C_k S_k are replaced by the one from C`_2 S`_2 if the test is passed i is raised. */ if (!this.andersonDarlingTest(y)) { this.currentPoints.remove(positionOfCenter.get(i)); this.currentPoints.put(intermediateCenter.get(0), this.intermediatePoints.get(intermediateCenter.get(0))); positionOfCenter.replace(i, intermediateCenter.get(0)); k++; this.currentPoints.put(intermediateCenter.get(1), this.intermediatePoints.get(intermediateCenter.get(1))); positionOfCenter.put(k, intermediateCenter.get(1)); } else { i++; } } this.mergeCluster(this.currentPoints); for (Entry<double[], List<C>> entry : this.currentPoints.entrySet()) { List<C> pointsInCluster = this.currentPoints.get(entry.getKey()); CentroidCluster<C> c = new CentroidCluster<>(entry::getKey); for (C point : pointsInCluster) { c.addPoint(point); } this.gmeansCluster.add(c); } return this.gmeansCluster; } protected void mergeCluster(final Map<double[], List<C>> currentPoints) { ArrayList<double[]> toMergeCenter = new ArrayList<>(); for (Entry<double[], List<C>> entry : currentPoints.entrySet()) { if (currentPoints.get(entry.getKey()).size() <= 2) { toMergeCenter.add(entry.getKey()); } } for (double[] d : toMergeCenter) { List<C> tmp = currentPoints.remove(d); for (C tmpPoints : tmp) { double minDist = Double.MAX_VALUE; double[] myCenter = null; for (double[] c : currentPoints.keySet()) { double tmpDist = this.distanceMeasure.compute(tmpPoints.getPoint(), c); if (tmpDist <= minDist) { myCenter = c; minDist = tmpDist; } } currentPoints.get(myCenter).add(tmpPoints); } } } protected boolean andersonDarlingTest(final double[] d) { // sorts the Array so that the smallest entrys are the first. Entrys are // negative too !! Arrays.sort(d); double mean = 0; double variance = 0; int totalvalue = 0; // mean of the sample is estimated by summing all entries and divide by the // total number. // Nans are ignored for (double i : d) { if (!Double.isNaN(i)) { totalvalue++; mean += i; } } mean = mean / totalvalue; totalvalue = 0; // variance sigma^2 is estimated by the sum of the squered difference to the // mean dvided by sample size -1 for (double i : d) { if (!Double.isNaN(i)) { variance += Math.pow((i - mean), 2); totalvalue++; } } variance = variance / (totalvalue - 1); // the standardization is made by the entries of d subtracted by the mean and // divided by the standard deviation // if the value of d is NaN the entry in the standardization is also NaN double[] y = this.standraizeRandomVariable(d, mean, variance); // Are also negative!! // total value is equivalent to y.length // first part of A^2 is -n overall A^2 = -n-second Part. double aSquare1 = (-1.0) * y.length; double aSquare2 = 0; // creates a normal distribution with mean 0 and standard deviation 1 NormalDistribution normal = new NormalDistribution(null, 0, 1); // if y is not Nan than the second part of A^2 is calculated fist the sum. // There are two possible ways to do it but both do not work. for (int i = 1; i < y.length; i++) { if (!Double.isNaN(y[i])) { aSquare2 += ((2 * i) - 1) * ((Math.log(normal.cumulativeProbability(y[i - 1]))) + Math.log(1 - (normal.cumulativeProbability(y[((y.length) - i)])))); } } // A^2 is divided by the the sample size to complete the second part of A^2^*. aSquare2 = aSquare2 / y.length; // By substracting part 2 from part 1 A^2^* is completed double aSqurestar = aSquare1 - aSquare2; // for different sample sizes the threshold weather the distribution is normal // or not varies a little. // Overall if A^2^* is greater than the threshold than the test fails if (y.length <= 10) { return aSqurestar <= 0.683; } else { if (y.length <= 20) { return aSqurestar <= 0.704; } else { if (y.length <= 50) { return aSqurestar <= 0.735; } else { if (y.length <= 100) { return aSqurestar <= 0.754; } else { return aSqurestar <= 0.787; } } } } } private double[] standraizeRandomVariable(final double[] d, final double mean, final double variance) { double[] tmp = new double[d.length]; for (int i = 0; i < tmp.length; i++) { if (!Double.isNaN(d[i])) { tmp[i] = (d[i] - mean) / (Math.sqrt(variance)); } else { tmp[i] = Double.NaN; } } return tmp; } protected double[] difference(final double[] a, final double[] b) { double[] c = new double[a.length]; for (int i = 0; i < a.length; i++) { if (!(Double.isNaN(a[i]) || Double.isNaN(b[i]))) { c[i] = a[i] - b[i]; } else { c[i] = Double.NaN; } } return c; } public List<CentroidCluster<C>> getGmeansCluster() { return this.gmeansCluster; } protected List<double[]> getCentersModifiable() { return this.center; } public List<C> getPoints() { return this.points; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/clustering
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/clustering/learner/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.clustering.learner;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/EScikitLearnProblemType.java
package ai.libs.jaicore.ml.core; public enum EScikitLearnProblemType { REGRESSION("regression"), // CLASSIFICATION("classification", new String[] {}, new String[] { "tpot", "xgboost" }), // TIME_SERIES_REGRESSION("ts-reg", new String[] { "rul-python-connection" }), // TIME_SERIES_FEATURE_ENGINEERING("ts-fe", new String[] { "rul-python-connection" }); private String scikitLearnCommandLineFlag; private String[] pythonRequiredModules; private String[] pythonOptionalModules; private EScikitLearnProblemType(final String scikitLearnCommandLineFlag, final String[] pythonRequiredModules, final String[] pythonOptionalModules) { this(scikitLearnCommandLineFlag, pythonRequiredModules); this.pythonOptionalModules = pythonOptionalModules; } private EScikitLearnProblemType(final String scikitLearnCommandLineFlag, final String[] pythonRequiredModules) { this(scikitLearnCommandLineFlag); this.pythonRequiredModules = pythonRequiredModules; } private EScikitLearnProblemType(final String scikitLearnCommandLineFlag) { this.scikitLearnCommandLineFlag = scikitLearnCommandLineFlag; this.pythonRequiredModules = new String[0]; this.pythonOptionalModules = new String[0]; } public String getScikitLearnCommandLineFlag() { return this.scikitLearnCommandLineFlag; } public String[] getPythonRequiredModules() { return this.pythonRequiredModules; } public String[] getPythonOptionalModules() { return this.pythonOptionalModules; } public String getName() { return this.getClass().getSimpleName() + "." + this.toString(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/package-info.java
package ai.libs.jaicore.ml.core;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/ADataset.java
package ai.libs.jaicore.ml.core.dataset; import java.util.ArrayList; import java.util.Optional; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; public abstract class ADataset<I extends ILabeledInstance> extends ArrayList<I> implements ILabeledDataset<I> { /** * */ private static final long serialVersionUID = 1158266286156653852L; private transient ILabeledInstanceSchema schema; protected ADataset(final ILabeledInstanceSchema schema) { super(); this.schema = schema; } @Override public ILabeledInstanceSchema getInstanceSchema() { return this.schema; } @Override public void removeColumn(final String columnName) { Optional<IAttribute> att = this.schema.getAttributeList().stream().filter(x -> x.getName().equals(columnName)).findFirst(); if (att.isPresent()) { this.removeColumn(this.schema.getAttributeList().indexOf(att.get())); } else { throw new IllegalArgumentException("There is no such attribute with name " + columnName + " to remove."); } } @Override public void removeColumn(final IAttribute attribute) { int index = this.schema.getAttributeList().indexOf(attribute); if (index >= 0) { this.removeColumn(index); } else { throw new IllegalArgumentException("There is no such attribute with name " + attribute.getName() + " to remove."); } } @Override public Object[][] getFeatureMatrix() { Object[][] featureMatrix = new Object[this.size()][]; for (int i = 0; i < this.size(); i++) { featureMatrix[i] = this.get(i).getAttributes(); } return featureMatrix; } @Override public Object[] getLabelVector() { return this.stream().map(ILabeledInstance::getLabel).toArray(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.schema == null) ? 0 : this.schema.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } ADataset other = (ADataset) obj; if (this.schema == null) { if (other.schema != null) { return false; } } else if (!this.schema.equals(other.schema)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/AInstance.java
package ai.libs.jaicore.ml.core.dataset; import java.io.Serializable; import ai.libs.jaicore.ml.core.filter.sampling.IClusterableInstance; public abstract class AInstance implements IClusterableInstance, Serializable { private Object label; /* just for serialization issues */ protected AInstance() { } protected AInstance(final Object label) { this.label = label; } @Override public Object getLabel() { return this.label; } @Override public void setLabel(final Object label) { this.label = label; } @Override public boolean isLabelPresent() { return this.label != null; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/ALabeledDataset.java
package ai.libs.jaicore.ml.core.dataset; import java.util.ArrayList; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; public abstract class ALabeledDataset<I extends ILabeledInstance> extends ArrayList<I> implements ILabeledDataset<I> { private static final long serialVersionUID = 1158266286156653852L; private transient ILabeledInstanceSchema schema; protected ALabeledDataset(final ILabeledInstanceSchema schema) { super(); this.schema = schema; } @Override public ILabeledInstanceSchema getInstanceSchema() { return this.schema; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.schema == null) ? 0 : this.schema.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } ALabeledDataset other = (ALabeledDataset) obj; if (this.schema == null) { if (other.schema != null) { return false; } } else if (!this.schema.equals(other.schema)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/Dataset.java
package ai.libs.jaicore.ml.core.dataset; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.IntStream; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.exception.DatasetCreationException; import org.api4.java.common.reconstruction.IReconstructible; import org.api4.java.common.reconstruction.IReconstructionInstruction; import org.api4.java.common.reconstruction.IReconstructionPlan; import ai.libs.jaicore.basic.reconstruction.ReconstructionInstruction; import ai.libs.jaicore.basic.reconstruction.ReconstructionPlan; public class Dataset extends ArrayList<ILabeledInstance> implements ILabeledDataset<ILabeledInstance>, IReconstructible { /** * */ private static final long serialVersionUID = -3643080541896274181L; private final List<ReconstructionInstruction> instructions = new ArrayList<>(); private final transient ILabeledInstanceSchema schema; public Dataset(final ILabeledInstanceSchema schema) { this.schema = schema; } public Dataset(final ILabeledInstanceSchema schema, final List<ILabeledInstance> instances) { this(schema); this.addAll(instances); } @Override public ILabeledInstanceSchema getInstanceSchema() { return this.schema; } @Override public Dataset createEmptyCopy() throws DatasetCreationException, InterruptedException { return new Dataset(this.schema); } @Override public Object[][] getFeatureMatrix() { return (Object[][]) IntStream.range(0, this.size()).mapToObj(x -> this.get(x).getAttributes()).toArray(); } @Override public Object[] getLabelVector() { return IntStream.range(0, this.size()).mapToObj(x -> this.get(x).getLabel()).toArray(); } @Override public void removeColumn(final int columnPos) { this.schema.removeAttribute(columnPos); this.stream().forEach(x -> x.removeColumn(columnPos)); } @Override public void removeColumn(final String columnName) { Optional<IAttribute> att = this.schema.getAttributeList().stream().filter(x -> x.getName().equals(columnName)).findFirst(); if (att.isPresent()) { this.removeColumn(this.schema.getAttributeList().indexOf(att.get())); } else { throw new IllegalArgumentException("There is no such attribute with name " + columnName + " to remove."); } } @Override public void removeColumn(final IAttribute attribute) { int index = this.schema.getAttributeList().indexOf(attribute); if (index >= 0) { this.removeColumn(index); } else { throw new IllegalArgumentException("There is no such attribute with name " + attribute.getName() + " to remove."); } } @Override public Dataset createCopy() throws DatasetCreationException, InterruptedException { Dataset ds = this.createEmptyCopy(); for (ILabeledInstance i : this) { ds.add(i); } return ds; } @Override public IReconstructionPlan getConstructionPlan() { return new ReconstructionPlan(this.instructions); } public String getInstancesAsString() { StringBuilder sb = new StringBuilder(); this.stream().map(ILabeledInstance::toString).forEach(x -> sb.append(x + "\n")); return sb.toString(); } @Override public void addInstruction(final IReconstructionInstruction instruction) { this.instructions.add((ReconstructionInstruction) instruction); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.schema == null) ? 0 : this.schema.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } Dataset other = (Dataset) obj; if (this.schema == null) { if (other.schema != null) { return false; } } else if (!this.schema.equals(other.schema)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/DatasetDeriver.java
package ai.libs.jaicore.ml.core.dataset; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.ai.ml.core.dataset.IInstance; import org.api4.java.ai.ml.core.exception.DatasetCreationException; public class DatasetDeriver<D extends IDataset<?>> { private class GenericCapsula<I extends IInstance> { private final IDataset<I> dsOriginal; private final int initialDatasetHashCode; // this is for consistency checks private final List<Integer> indicesToCopy = new ArrayList<>(); public GenericCapsula(final IDataset<I> dataset, final Class<I> clazz) { super(); this.dsOriginal = dataset; this.initialDatasetHashCode = dataset.hashCode(); if (!clazz.isInstance(dataset.get(0))) { throw new IllegalArgumentException(); } } public IDataset<I> getCopyBasedOnDefinedLines() throws InterruptedException, DatasetCreationException { if (this.initialDatasetHashCode != this.dsOriginal.hashCode()) { throw new IllegalStateException("Dataset underlying the deriver has changed!"); } IDataset<I> copy = this.dsOriginal.createEmptyCopy(); for (int index : this.indicesToCopy) { copy.add(this.dsOriginal.get(index)); } if (copy.size() != this.indicesToCopy.size()) { throw new IllegalStateException("The copy has " + copy.size() + " elements while it should have " + this.indicesToCopy.size() + "."); } return copy; } public void addInstance(final int inst, final int count) { for (int i = 0; i < count; i++) { this.indicesToCopy.add(inst); } } } private final GenericCapsula<?> caps; public DatasetDeriver(final D dataset) { this(dataset, (Class<? extends IInstance>) dataset.get(0).getClass()); } protected <I extends IInstance> DatasetDeriver(final D dataset, final Class<I> instanceClass) { this.caps = new GenericCapsula<>((IDataset<I>) dataset, instanceClass); } public void add(final int item, final int count) { this.caps.addInstance(item, count); } public void add(final int item) { this.add(item, 1); } public void addIndices(final Collection<Integer> indices, final int count) { Objects.requireNonNull(indices); for (int i : indices) { this.caps.addInstance(i, count); } } public void addIndices(final Collection<Integer> indices) { this.addIndices(indices, 1); } public boolean contains(final IInstance inst) { return this.caps.indicesToCopy.contains(this.caps.dsOriginal.indexOf(inst)); } public D build() throws InterruptedException, DatasetCreationException { return (D)this.caps.getCopyBasedOnDefinedLines(); } public int currentSizeOfTarget() { return this.caps.indicesToCopy.size(); } public D getDataset() { return (D)this.caps.dsOriginal; } public List<Integer> getIndicesOfNewInstancesInOriginalDataset() { return Collections.unmodifiableList(this.caps.indicesToCopy); } public Collection<Integer> getIndicesOfNewInstancesInOriginalDataset(final Collection<Integer> indicesInBuiltDataset) { return Collections.unmodifiableList(indicesInBuiltDataset.stream().map(this.caps.indicesToCopy::get).collect(Collectors.toList())); } public List<Integer> getIndicesOfNewInstancesInOriginalDataset(final List<Integer> indicesInBuiltDataset) { return Collections.unmodifiableList(indicesInBuiltDataset.stream().map(this.caps.indicesToCopy::get).collect(Collectors.toList())); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/DatasetUtil.java
package ai.libs.jaicore.ml.core.dataset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttribute; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.common.reconstruction.IReconstructible; import ai.libs.jaicore.basic.reconstruction.ReconstructionInstruction; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.ml.core.dataset.schema.LabeledInstanceSchema; import ai.libs.jaicore.ml.core.dataset.schema.attribute.IntBasedCategoricalAttribute; import ai.libs.jaicore.ml.core.dataset.schema.attribute.NumericAttribute; public class DatasetUtil { private DatasetUtil() { /* just to avoid instantiation */ } public static Map<Object, Integer> getLabelCounts(final ILabeledDataset<?> ds) { Map<Object, Integer> labelCounter = new HashMap<>(); ds.forEach(li -> { Object label = li.getLabel(); labelCounter.put(label, labelCounter.computeIfAbsent(label, l -> 0) + 1); }); return labelCounter; } public static int getLabelCountDifference(final ILabeledDataset<?> d1, final ILabeledDataset<?> d2) { Map<Object, Integer> c1 = getLabelCounts(d1); Map<Object, Integer> c2 = getLabelCounts(d2); Collection<Object> labels = SetUtil.union(c1.keySet(), c2.keySet()); int diff = 0; for (Object label : labels) { diff += Math.abs(c1.get(label) - c2.get(label)); } return diff; } private static ILabeledDataset<?> convertTargetOfDataset(final ILabeledDataset<?> dataset, final IAttribute attr, final Map<Object, ? extends Object> conversionMap, final String utilMethodName) { /* copy attribute list and exchange this attribute */ List<IAttribute> attList = new ArrayList<>(dataset.getInstanceSchema().getAttributeList()); /* get new scheme */ LabeledInstanceSchema scheme = new LabeledInstanceSchema(dataset.getRelationName(), attList, attr); Dataset datasetModified = new Dataset(scheme); /* now copy all the instances*/ int numAttributes = dataset.getNumAttributes(); for (ILabeledInstance i : dataset) { ILabeledInstance ci; if (i instanceof DenseInstance) { ci = new DenseInstance(i.getAttributes(), conversionMap.get(i.getLabel())); } else if (i instanceof SparseInstance) { ci = new SparseInstance(numAttributes, ((SparseInstance) i).getAttributeMap(), conversionMap.get(i.getLabel())); } else { throw new UnsupportedOperationException(); } if (!datasetModified.getLabelAttribute().isValidValue(ci.getLabel())) { throw new IllegalStateException("Value " + ci.getLabel() + " is not a valid label value for label attribute " + datasetModified.getLabelAttribute()); } datasetModified.add(ci); } /* add reconstruction instructions to the dataset */ if (dataset instanceof IReconstructible) { ((IReconstructible) dataset).getConstructionPlan().getInstructions().forEach(datasetModified::addInstruction); try { datasetModified.addInstruction(new ReconstructionInstruction(DatasetUtil.class.getMethod(utilMethodName, ILabeledDataset.class), "this")); } catch (NoSuchMethodException | SecurityException e) { throw new UnsupportedOperationException(e); } } return datasetModified; } public static ILabeledDataset<?> convertToClassificationDataset(final ILabeledDataset<?> dataset) { IAttribute currentLabelAttribute = dataset.getLabelAttribute(); if (currentLabelAttribute instanceof ICategoricalAttribute) { return dataset; } Set<String> values = dataset.stream().map(x -> x.getLabel().toString()).collect(Collectors.toSet()); IntBasedCategoricalAttribute attr = new IntBasedCategoricalAttribute(currentLabelAttribute.getName(), new ArrayList<>(values)); Map<Object, Object> conversionMap = new HashMap<>(); for (ILabeledInstance i : dataset) { if (!conversionMap.containsKey(i.getLabel())) { conversionMap.put(i.getLabel(), attr.deserializeAttributeValue(i.getLabel().toString())); } } return convertTargetOfDataset(dataset, attr, conversionMap, "convertToClassificationDataset"); } public static ILabeledDataset<?> convertToRegressionDataset(final ILabeledDataset<?> dataset) { IAttribute currentLabelAttribute = dataset.getLabelAttribute(); if (currentLabelAttribute instanceof INumericAttribute) { return dataset; } NumericAttribute attr = new NumericAttribute(currentLabelAttribute.getName()); Map<Object, Double> labelMap = new HashMap<>(); ICategoricalAttribute catLabel = (ICategoricalAttribute) dataset.getLabelAttribute(); try { for (String label : catLabel.getLabels()) { try { labelMap.put(catLabel.deserializeAttributeValue(label), Integer.valueOf(label).doubleValue()); } catch (NumberFormatException e) { labelMap.put(catLabel.deserializeAttributeValue(label), Double.parseDouble(label)); } } } catch (NumberFormatException e) { labelMap.clear(); List<String> labels = catLabel.getLabels(); for (int i = 0; i < labels.size(); i++) { labelMap.put(catLabel.deserializeAttributeValue(labels.get(i)), (double) labels.indexOf(labels.get(i))); } } return convertTargetOfDataset(dataset, attr, labelMap, "convertToRegressionDataset"); } public static ILabeledDataset<?> getDatasetFromMapCollection(final Collection<Map<String, Object>> datasetAsListOfMaps, final String nameOfLabelAttribute) { List<String> keyOrder = datasetAsListOfMaps.iterator().next().keySet().stream().sorted().collect(Collectors.toList()); return getDatasetFromMapCollection(datasetAsListOfMaps, nameOfLabelAttribute, keyOrder); } public static ILabeledDataset<?> getDatasetFromMapCollection(final Collection<Map<String, Object>> datasetAsListOfMaps, final String nameOfLabelAttribute, final List<String> orderOfAttributes) { /* check that all keys are identical */ Set<String> keys = new HashSet<>(orderOfAttributes); for (Map<String, Object> dataPoint : datasetAsListOfMaps) { if (!keys.equals(dataPoint.keySet())) { throw new IllegalStateException(); } } List<IAttribute> attributeList = new ArrayList<>(); for (String key : orderOfAttributes) { if (key.equals(nameOfLabelAttribute)) { continue; } Object val = datasetAsListOfMaps.iterator().next().get(key); if (val instanceof Number) { attributeList.add(new NumericAttribute(key)); } else if (val instanceof Boolean) { attributeList.add(new IntBasedCategoricalAttribute(key, Arrays.asList("false", "true"))); } else { throw new UnsupportedOperationException(); } } LabeledInstanceSchema schema = new LabeledInstanceSchema("rel", attributeList, new NumericAttribute(nameOfLabelAttribute)); Dataset metaDataset = new Dataset(schema); for (Map<String, Object> row : datasetAsListOfMaps) { ILabeledInstance inst = getInstanceFromMap(schema, row, nameOfLabelAttribute); metaDataset.add(inst); } return metaDataset; } public static ILabeledInstance getInstanceFromMap(final ILabeledInstanceSchema schema, final Map<String, Object> row, final String nameOfLabelAttribute) { return getInstanceFromMap(schema, row, nameOfLabelAttribute, new HashMap<>()); } public static ILabeledInstance getInstanceFromMap(final ILabeledInstanceSchema schema, final Map<String, Object> row, final String nameOfLabelAttribute, final Map<IAttribute, Function<ILabeledInstance, Double>> attributeValueComputer) { List<Object> attributes = new ArrayList<>(schema.getNumAttributes()); List<Integer> attributeToRecover = new ArrayList<>(); int i = 0; for (IAttribute att : schema.getAttributeList()) { if (row.containsKey(att.getName())) { attributes.add(row.get(att.getName())); } else { attributeToRecover.add(i); attributes.add(null); } i++; } ILabeledInstance inst = new DenseInstance(attributes, row.get(nameOfLabelAttribute)); if (inst.getNumAttributes() != schema.getNumAttributes()) { throw new IllegalStateException("Created dense instance with " + inst.getNumAttributes() + " attributes where the scheme requires " + schema.getNumAttributes()); } /* post-compute the missing attribute values */ for (int attIndex : attributeToRecover) { inst.setAttributeValue(attIndex, attributeValueComputer.get(schema.getAttribute(attIndex)).apply(inst)); } return inst; } public static final int EXPANSION_SQUARES = 1; public static final int EXPANSION_LOGARITHM = 2; public static final int EXPANSION_PRODUCTS = 3; public static Pair<List<IAttribute>, Map<IAttribute, Function<ILabeledInstance, Double>>> getPairOfNewAttributesAndExpansionMap(final ILabeledDataset<?> dataset, final int... expansions) throws InterruptedException { List<IAttribute> attributeList = dataset.getInstanceSchema().getAttributeList(); List<IAttribute> newAttributes = new ArrayList<>(); boolean computeSquares = false; boolean computeProducts = false; boolean computeLogs = false; for (int expansion : expansions) { switch (expansion) { case EXPANSION_LOGARITHM: computeLogs = true; break; case EXPANSION_SQUARES: computeSquares = true; break; case EXPANSION_PRODUCTS: computeProducts = true; break; default: throw new UnsupportedOperationException("Unknown expansion " + expansion); } } /* compute new attribute objects */ Map<IAttribute, Function<ILabeledInstance, Double>> transformations = new HashMap<>(); for (int attId = 0; attId < dataset.getNumAttributes(); attId++) { final int attIdFinal = attId; IAttribute att = dataset.getAttribute(attId); if (computeSquares && (att instanceof INumericAttribute)) { IAttribute dAtt = new NumericAttribute(att.getName() + "_2"); newAttributes.add(dAtt); transformations.put(dAtt, i -> Math.pow(Double.parseDouble(i.getAttributeValue(attIdFinal).toString()), 2)); } else if (computeLogs && (att instanceof INumericAttribute)) { IAttribute dAtt = new NumericAttribute(att.getName() + "_log"); newAttributes.add(dAtt); transformations.put(dAtt, i -> Math.log((double) i.getAttributeValue(attIdFinal))); } } /* compute products */ if (computeProducts) { /* compute all sub-sets of features */ Collection<Collection<IAttribute>> featureSubSets = SetUtil.powerset(attributeList); for (Collection<IAttribute> subset : featureSubSets) { if (subset.size() > 3 || subset.size() < 2) { continue; } StringBuilder featureName = new StringBuilder("x"); final List<Integer> indices = new ArrayList<>(); for (IAttribute feature : subset.stream().sorted((a1, a2) -> a1.getName().compareTo(a2.getName())).collect(Collectors.toList())) { featureName.append("_" + feature.getName()); indices.add(attributeList.indexOf(feature)); } IAttribute dAtt = new NumericAttribute(featureName.toString()); if (attributeList.contains(dAtt)) { throw new IllegalStateException("Dataset already has attribute " + dAtt.getName()); } else if (newAttributes.contains(dAtt)) { throw new IllegalStateException("Already added attribute " + dAtt.getName()); } newAttributes.add(dAtt); transformations.put(dAtt, i -> { double val = 1; for (int index : indices) { val *= Double.parseDouble(i.getAttributeValue(index).toString()); } return val; }); } } return new Pair<>(newAttributes, transformations); } public static ILabeledDataset<?> getExpansionOfDataset(final ILabeledDataset<?> dataset, final int... expansions) throws InterruptedException { return getExpansionOfDataset(dataset, getPairOfNewAttributesAndExpansionMap(dataset, expansions)); } public static ILabeledDataset<?> getExpansionOfDataset(final ILabeledDataset<?> dataset, final Pair<List<IAttribute>, Map<IAttribute, Function<ILabeledInstance, Double>>> expansionDescription) { /* compute values for new attributes */ List<IAttribute> newAttributeList = new ArrayList<>(dataset.getInstanceSchema().getAttributeList()); newAttributeList.addAll(expansionDescription.getX()); ILabeledInstanceSchema schema = new LabeledInstanceSchema(dataset.getRelationName() + "_expansion", newAttributeList, dataset.getLabelAttribute()); Dataset ds = new Dataset(schema); for (ILabeledInstance i : dataset) { ds.add(getExpansionOfInstance(i, expansionDescription)); } return ds; } public static ILabeledInstance getExpansionOfInstance(final ILabeledInstance i, final Pair<List<IAttribute>, Map<IAttribute, Function<ILabeledInstance, Double>>> expansionDescription) { List<Object> attributes = new ArrayList<>(Arrays.asList(i.getAttributes())); for (IAttribute newAtt : expansionDescription.getX()) { attributes.add(expansionDescription.getY().get(newAtt).apply(i)); } return new DenseInstance(attributes, i.getLabel()); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/DenseInstance.java
package ai.libs.jaicore.ml.core.dataset; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DenseInstance extends AInstance implements Serializable { private static final long serialVersionUID = -4214595761791391816L; private List<Object> attributes; /* this is just for serialization issues */ public DenseInstance() { super(); } public DenseInstance(final Object[] attributes, final Object label) { this(new ArrayList<>(Arrays.asList(attributes)), label); } public DenseInstance(final List<Object> attributes, final Object label) { super(label); this.attributes = attributes; } @Override public Object getAttributeValue(final int pos) { return this.attributes.get(pos); } @Override public void setAttributeValue(final int pos, final Object value) { this.attributes.remove(pos); this.attributes.add(pos, value); } @Override public Object[] getAttributes() { return this.attributes.toArray(); } @Override public double[] getPoint() { int n = this.attributes.size(); double[] point = new double[n]; for (int i = 0; i < n; i++) { Object val = this.attributes.get(i); if (val == null) { val = 0; } if (val instanceof Boolean) { val = (boolean)val ? 1.0 : 0.0; } if (!(val instanceof Number)) { throw new UnsupportedOperationException("The given instance cannot be cast to a point, because it has a non-numeric value: " + this.attributes); } if (val instanceof Integer) { val = Double.valueOf((int) val); } if (val instanceof Long) { val = Double.valueOf((long) val); } if (val instanceof Float) { val = Double.valueOf((float) val); } point[i] = (double) val; } return point; } @Override public double getPointValue(final int pos) { return this.getPoint()[pos]; } @Override public void removeColumn(final int columnPos) { this.attributes.remove(columnPos); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.attributes == null) ? 0 : this.attributes.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } DenseInstance other = (DenseInstance) obj; if (this.attributes == null) { if (other.attributes != null) { return false; } } else if (!this.attributes.equals(other.attributes)) { return false; } return true; } @Override public String toString() { return Arrays.toString(this.getAttributes()) + "->" + this.getLabel(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/FileDatasetDescriptor.java
package ai.libs.jaicore.ml.core.dataset; import java.io.File; import org.api4.java.ai.ml.core.dataset.descriptor.IFileDatasetDescriptor; public class FileDatasetDescriptor implements IFileDatasetDescriptor { private final File file; public FileDatasetDescriptor(final File file) { super(); this.file = file; } @Override public File getDatasetDescription() { return this.file; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/MapInstance.java
package ai.libs.jaicore.ml.core.dataset; import java.util.HashMap; import java.util.stream.Collectors; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import ai.libs.jaicore.ml.core.filter.sampling.IClusterableInstance; public class MapInstance extends HashMap<IAttribute, Object> implements IClusterableInstance { private static final long serialVersionUID = -5548696792257032346L; private final transient ILabeledInstanceSchema scheme; private final IAttribute labelAttribute; public MapInstance(final ILabeledInstanceSchema scheme, final IAttribute labelAttribute) { super(); this.scheme = scheme; this.labelAttribute = labelAttribute; } @Override public void setAttributeValue(final int pos, final Object value) { this.put(this.scheme.getAttribute(pos), value); } @Override public Object[] getAttributes() { return this.scheme.getAttributeList().stream().map(this::get).collect(Collectors.toList()).toArray(); } @Override public double[] getPoint() { throw new UnsupportedOperationException(); } @Override public void removeColumn(final int columnPos) { throw new UnsupportedOperationException(); } @Override public Object getLabel() { return this.get(this.labelAttribute); } @Override public void setLabel(final Object obj) { this.put(this.labelAttribute, obj); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.labelAttribute == null) ? 0 : this.labelAttribute.hashCode()); result = prime * result + ((this.scheme == null) ? 0 : this.scheme.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } MapInstance other = (MapInstance) obj; if (this.labelAttribute == null) { if (other.labelAttribute != null) { return false; } } else if (!this.labelAttribute.equals(other.labelAttribute)) { return false; } if (this.scheme == null) { if (other.scheme != null) { return false; } } else if (!this.scheme.equals(other.scheme)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/SparseInstance.java
package ai.libs.jaicore.ml.core.dataset; import java.util.Map; import java.util.stream.IntStream; public class SparseInstance extends AInstance { public static final ENullElement DEF_NULL_ELEMENT = ENullElement.ZERO; /** * Determines a default interpretation of values not contained in the map of attributes. * An attribute value can - by default - be understood either to be unknown or zero. */ public enum ENullElement { UNKNOWN, ZERO; } private ENullElement nullElement; private Map<Integer, Object> attributeMap; private int numAttributes; public SparseInstance(final int numAttributes, final Map<Integer, Object> attributes, final Object label) { super(label); this.numAttributes = numAttributes; this.attributeMap = attributes; } @Override public Object getAttributeValue(final int pos) { if (this.attributeMap.containsKey(pos)) { return this.attributeMap.get(pos); } else if (this.nullElement != null) { switch (this.nullElement) { case UNKNOWN: return "?"; case ZERO: return 0; default: throw new UnsupportedOperationException("The use of the specified null element is not defined."); } } else { return null; } } @Override public Object[] getAttributes() { return IntStream.range(0, this.numAttributes).mapToObj(this::getAttributeValue).toArray(); } @Override public double[] getPoint() { double[] point = new double[this.numAttributes]; for (int i = 0; i < this.numAttributes; i++) { point[i] = this.getPointValue(i); } return point; } @Override public double getPointValue(final int pos) { return this.attributeMap.containsKey(pos) ? (double)this.attributeMap.get(pos) : 0; } @Override public void setAttributeValue(final int pos, final Object value) { if ((this.nullElement == ENullElement.ZERO && value.equals(0)) || (this.nullElement == ENullElement.UNKNOWN && value.equals("?"))) { return; } this.attributeMap.put(pos, value); } public Map<Integer, Object> getAttributeMap() { return this.attributeMap; } @Override public void removeColumn(final int columnPos) { this.attributeMap.remove(columnPos); this.numAttributes --; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.attributeMap == null) ? 0 : this.attributeMap.hashCode()); result = prime * result + ((this.nullElement == null) ? 0 : this.nullElement.hashCode()); result = prime * result + this.numAttributes; return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } SparseInstance other = (SparseInstance) obj; if (this.attributeMap == null) { if (other.attributeMap != null) { return false; } } else if (!this.attributeMap.equals(other.attributeMap)) { return false; } if (this.nullElement != other.nullElement) { return false; } return (this.numAttributes == other.numAttributes); } @Override public String toString() { return "SparseInstance [nullElement=" + this.nullElement + ", attributeMap=" + this.attributeMap + ", numAttributes=" + this.numAttributes + "]"; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/package-info.java
package ai.libs.jaicore.ml.core.dataset;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/clusterable/ClusterableDataset.java
package ai.libs.jaicore.ml.core.dataset.clusterable; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.exception.DatasetCreationException; import ai.libs.jaicore.ml.core.dataset.ADataset; import ai.libs.jaicore.ml.core.filter.sampling.IClusterableInstance; public class ClusterableDataset extends ADataset<IClusterableInstance> implements ILabeledDataset<IClusterableInstance> { /** * */ private static final long serialVersionUID = -6066251665166527020L; public ClusterableDataset(final ILabeledInstanceSchema schema) { super(schema); } public ClusterableDataset(final ILabeledDataset<ILabeledInstance> dataset) { this(dataset.getInstanceSchema()); dataset.stream().map(x -> (IClusterableInstance) x).forEach(this::add); } @Override public void removeColumn(final int columnPos) { throw new UnsupportedOperationException("Not yet implemented."); } @Override public ClusterableDataset createEmptyCopy() throws DatasetCreationException, InterruptedException { return new ClusterableDataset(this.getInstanceSchema()); } @Override public ClusterableDataset createCopy() throws DatasetCreationException, InterruptedException { ClusterableDataset copy = this.createEmptyCopy(); for (IClusterableInstance i : this) { copy.add(i); } return copy; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/clusterable/package-info.java
package ai.libs.jaicore.ml.core.dataset.clusterable;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/DatasetPropertyComputer.java
package ai.libs.jaicore.ml.core.dataset.schema; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.ai.ml.core.dataset.IInstance; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; public class DatasetPropertyComputer implements ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(DatasetPropertyComputer.class); public Map<Integer, Set<Object>> computeAttributeValues(final IDataset<?> dataset) { List<Integer> allAttributeIndices = new ArrayList<>(); int n = dataset.getNumAttributes(); for (int i = 0; i < n; i++) { allAttributeIndices.add(i); } return this.computeAttributeValues(dataset, allAttributeIndices, 1); } /** * This method computes for each desired attribute the set of occurring values. * If numCPU > 1, the computation is done in parallel. */ public Map<Integer, Set<Object>> computeAttributeValues(final IDataset<?> dataset, final List<Integer> pAttributeIndices, final int numCPUs) { this.logger.info("computeAttributeValues(): enter"); Map<Integer, Set<Object>> attributeValues = new HashMap<>(); // SCALE-54: Use target attribute only if no attribute indices are provided int targetIndex = -1; List<Integer> attributeIndices; if (dataset instanceof ILabeledDataset<?>) { // We assume that the last attribute is the target attribute targetIndex = dataset.getNumAttributes(); if ((pAttributeIndices == null || pAttributeIndices.isEmpty())) { if (this.logger.isInfoEnabled()) { this.logger.info(String.format("No attribute indices provided. Working with target attribute only (index: %d", targetIndex)); } attributeIndices = Collections.singletonList(targetIndex); } else { attributeIndices = new ArrayList<>(pAttributeIndices); attributeIndices.add(targetIndex); } } else { attributeIndices = new ArrayList<>(pAttributeIndices); } if (this.logger.isDebugEnabled()) { this.logger.debug("Computing attribute values for attribute indices {}", attributeIndices); } // Check validity of the attribute indices for (int attributeIndex : attributeIndices) { if (attributeIndex > dataset.getNumAttributes()) { throw new IndexOutOfBoundsException(String.format("Attribute index %d is out of bounds for the delivered data set!", attributeIndex)); } } // Setup map with empty sets for (int attributeIndex : attributeIndices) { attributeValues.put(attributeIndex, new HashSet<>()); } /* partitions the dataset and computes, in parallel, all the values that exist in each partition for each attribute */ ExecutorService threadPool = Executors.newFixedThreadPool(numCPUs); List<Future<Map<Integer, Set<Object>>>> futures = new ArrayList<>(); if (this.logger.isInfoEnabled()) { this.logger.info(String.format("Starting %d threads for computation..", numCPUs)); } int listSize = dataset.size() / numCPUs; for (List<? extends IInstance> sublist : Lists.partition(dataset, listSize)) { futures.add(threadPool.submit(new ListProcessor<>(sublist, new HashSet<>(attributeIndices), dataset, this.logger))); } threadPool.shutdown(); // blocks until all computations are ready /* now merge the results of the partitions into a global set of existing values for each attribute */ for (Future<Map<Integer, Set<Object>>> future : futures) { try { // Merge locally computed attribute values into the global list Map<Integer, Set<Object>> localAttributeValues = future.get(); for (Entry<Integer, Set<Object>> entry : attributeValues.entrySet()) { IAttribute att = entry.getKey() == targetIndex ? ((ILabeledDataset<?>)dataset).getLabelAttribute() : dataset.getAttribute(entry.getKey()); for (Object o : entry.getValue()) { if (!att.isValidValue(o)) { throw new IllegalStateException("Collecting invalid value " + o + " for attribute " + att + ". Valid values: " + att.getStringDescriptionOfDomain()); } } attributeValues.get(entry.getKey()).addAll(localAttributeValues.get(entry.getKey())); } } catch (ExecutionException e) { this.logger.error("Exception while waiting for future to complete..", e); } catch (InterruptedException e) { this.logger.error("Thread has been interrupted"); Thread.currentThread().interrupt(); } } return attributeValues; } /** * Helper class which processes a sublist of the original data set and collects * the occurring attribute values on this sublist. * * @author Felix Weiland * */ static class ListProcessor<D extends IDataset<?>> implements Callable<Map<Integer, Set<Object>>> { private final Logger logger; private List<? extends IInstance> list; private Set<Integer> attributeIndices; private D dataset; public ListProcessor(final List<? extends IInstance> list, final Set<Integer> attributeIndices, final D dataset, final Logger logger) { super(); this.list = list; this.attributeIndices = attributeIndices; this.dataset = dataset; this.logger = logger; } @Override public Map<Integer, Set<Object>> call() { if (this.logger.isInfoEnabled()) { this.logger.info("Starting computation on local sublist of length {}", this.list.size()); } // Setup local map Map<Integer, Set<Object>> attributeValues = new HashMap<>(); // Initialize local map with empty sets for (int attributeIndex : this.attributeIndices) { attributeValues.put(attributeIndex, new HashSet<>()); } // Collect attribute values for (IInstance instance : this.list) { for (int attributeIndex : this.attributeIndices) { if (attributeIndex == this.dataset.getNumAttributes()) { // Attribute index describes target attribute Object label = ((ILabeledInstance)instance).getLabel(); if (label != null) { attributeValues.get(attributeIndex).add(label); } } else { Object value = instance.getAttributeValue(attributeIndex); if (value != null) { attributeValues.get(attributeIndex).add(value); } } } } this.logger.info("Finished local computation. Identified {} values.", attributeValues.size()); return attributeValues; } } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/InstanceSchema.java
package ai.libs.jaicore.ml.core.dataset.schema; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.api4.java.ai.ml.core.dataset.schema.IInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; public class InstanceSchema implements IInstanceSchema, Serializable { private String relationName; private List<IAttribute> attributeList; /* just for serialization */ public InstanceSchema() { } public InstanceSchema(final String relationName, final Collection<IAttribute> attributeList) { this.relationName = relationName; this.attributeList = new ArrayList<>(attributeList); } @Override public List<IAttribute> getAttributeList() { return this.attributeList; } @Override public IAttribute getAttribute(final int pos) { return this.attributeList.get(pos); } @Override public int getNumAttributes() { return this.attributeList.size(); } @Override public String getRelationName() { return this.relationName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Relation: " + this.relationName); sb.append("\n"); sb.append("Features: " + this.attributeList); return sb.toString(); } @Override public void removeAttribute(final int columnPos) { this.attributeList.remove(columnPos); } @Override public void addAttribute(final int pos, final IAttribute attribute) { this.attributeList.add(pos, attribute); } @Override public void addAttribute(final IAttribute attribute) { this.attributeList.add(attribute); } @Override public IInstanceSchema getCopy() { return new InstanceSchema(this.relationName, new ArrayList<>(this.attributeList)); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.attributeList == null) ? 0 : this.attributeList.hashCode()); result = prime * result + ((this.relationName == null) ? 0 : this.relationName.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } InstanceSchema other = (InstanceSchema) obj; if (this.attributeList == null) { if (other.attributeList != null) { return false; } } else if (!this.attributeList.equals(other.attributeList)) { return false; } if (this.relationName == null) { if (other.relationName != null) { return false; } } else if (!this.relationName.equals(other.relationName)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/LabeledInstanceSchema.java
package ai.libs.jaicore.ml.core.dataset.schema; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; public class LabeledInstanceSchema extends InstanceSchema implements ILabeledInstanceSchema, Serializable { private IAttribute labelAttribute; /* just for serialization purposes */ public LabeledInstanceSchema() { super(); } public LabeledInstanceSchema(final String relationName, final List<IAttribute> attributeList, final IAttribute labelAttribute) { super(relationName, attributeList); this.labelAttribute = labelAttribute; } @Override public IAttribute getLabelAttribute() { return this.labelAttribute; } @Override public void replaceLabelAttribute(final IAttribute labelAttribute) { this.labelAttribute = labelAttribute; } @Override public LabeledInstanceSchema getCopy() { return new LabeledInstanceSchema(this.getRelationName(), new ArrayList<>(this.getAttributeList()), this.labelAttribute); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append("\n"); sb.append("Target: "); sb.append(this.labelAttribute); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.labelAttribute == null) ? 0 : this.labelAttribute.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } LabeledInstanceSchema other = (LabeledInstanceSchema) obj; if (this.labelAttribute == null) { if (other.labelAttribute != null) { return false; } } else if (!this.labelAttribute.equals(other.labelAttribute)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.core.dataset.schema;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/AAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericEncodingAttribute; public abstract class AAttribute implements INumericEncodingAttribute { /** * */ private static final long serialVersionUID = 8319254880082572177L; private String name; protected AAttribute(final String name) { this.name = name; } @Override public String getName() { return this.name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } AAttribute other = (AAttribute) obj; if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/ACollectionOfObjectsAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Collection; public abstract class ACollectionOfObjectsAttribute<O> extends AGenericObjectAttribute<Collection<O>> { private static final long serialVersionUID = 2086475349391194480L; protected ACollectionOfObjectsAttribute(final String name) { super(name); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/AGenericObjectAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttributeValue; /** * * @author mwever * * @param <O> The type of object that can be stored. */ public abstract class AGenericObjectAttribute<O> extends AAttribute { /** * */ private static final long serialVersionUID = 614829108498630281L; private transient Map<O, Double> objectToDoubleMap = new HashMap<>(); private transient Map<Double, O> doubleToObjectMap = new HashMap<>(); private AtomicInteger objectCounter = new AtomicInteger(1); protected AGenericObjectAttribute(final String name) { super(name); } @Override public double encodeValue(final Object attributeValue) { if (!this.isValidValue(attributeValue)) { throw new IllegalArgumentException("No valid attribute value"); } O value = this.getValueAsTypeInstance(attributeValue); if (!this.objectToDoubleMap.containsKey(attributeValue)) { double encodedValue = this.objectCounter.getAndIncrement(); this.objectToDoubleMap.put(value, encodedValue); this.doubleToObjectMap.put(encodedValue, value); return encodedValue; } else { return this.objectToDoubleMap.get(value); } } @Override public O decodeValue(final double encodedAttributeValue) { return this.doubleToObjectMap.get(encodedAttributeValue); } @Override public IAttributeValue getAsAttributeValue(final double encodedAttributeValue) { return this.getAsAttributeValue(this.doubleToObjectMap.get(encodedAttributeValue)); } protected abstract O getValueAsTypeInstance(Object object); @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.doubleToObjectMap == null) ? 0 : this.doubleToObjectMap.hashCode()); result = prime * result + ((this.objectCounter == null) ? 0 : this.objectCounter.hashCode()); result = prime * result + ((this.objectToDoubleMap == null) ? 0 : this.objectToDoubleMap.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AGenericObjectAttribute other = (AGenericObjectAttribute) obj; if (this.doubleToObjectMap == null) { if (other.doubleToObjectMap != null) { return false; } } else if (!this.doubleToObjectMap.equals(other.doubleToObjectMap)) { return false; } if (this.objectCounter == null) { if (other.objectCounter != null) { return false; } } else if (this.objectCounter.get() != other.objectCounter.get()) { return false; } if (this.objectToDoubleMap == null) { if (other.objectToDoubleMap != null) { return false; } } else if (!this.objectToDoubleMap.equals(other.objectToDoubleMap)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/ARankingAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IRankingAttribute; import org.api4.java.ai.ml.ranking.IRanking; public abstract class ARankingAttribute<O> extends AGenericObjectAttribute<IRanking<O>> implements IRankingAttribute<O> { /** * */ private static final long serialVersionUID = -9045962289246750137L; protected ARankingAttribute(final String name) { super(name); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/DyadRankingAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Arrays; import org.api4.java.ai.ml.core.dataset.schema.attribute.IRankingAttributeValue; import org.api4.java.ai.ml.ranking.IRanking; import org.api4.java.ai.ml.ranking.dyad.dataset.IDyad; import org.api4.java.common.math.IVector; import ai.libs.jaicore.math.linearalgebra.DenseDoubleVector; import ai.libs.jaicore.ml.ranking.dyad.learner.Dyad; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.Ranking; public class DyadRankingAttribute extends ARankingAttribute<IDyad> { /** * */ private static final long serialVersionUID = -7427433693910952078L; public DyadRankingAttribute(final String name) { super(name); } @Override public boolean isValidValue(final Object value) { if (value instanceof IRanking) { return (((IRanking<?>) value).get(0) instanceof IDyad); } return (value instanceof DyadRankingAttributeValue); } @Override public String getStringDescriptionOfDomain() { return "[DR] " + this.getName(); } @SuppressWarnings("unchecked") @Override public IRankingAttributeValue<IDyad> getAsAttributeValue(final Object object) { if (this.isValidValue(object)) { if (object instanceof DyadRankingAttributeValue) { return new DyadRankingAttributeValue(this, ((DyadRankingAttributeValue) object).getValue()); } else { return new DyadRankingAttributeValue(this, (IRanking<IDyad>) object); } } else { throw new IllegalArgumentException("No valid value for this attribute"); } } @SuppressWarnings("unchecked") @Override protected IRanking<IDyad> getValueAsTypeInstance(final Object object) { if (this.isValidValue(object)) { if (object instanceof DyadRankingAttributeValue) { return ((DyadRankingAttributeValue) object).getValue(); } else { return (IRanking<IDyad>) object; } } else { throw new IllegalArgumentException("No valid value for this attribute"); } } @Override public double toDouble(final Object object) { throw new UnsupportedOperationException("Not yet implemented in DyadRankingAttribute"); } @Override public String serializeAttributeValue(final Object value) { if (value == null) { return null; } return this.getValueAsTypeInstance(value).stream().map(x -> "(" + x.getContext() + ";" + x.getAlternative() + ")").reduce("", (a, b) -> a + (a.isEmpty() ? "" : ">") + b); } @Override public Object deserializeAttributeValue(final String string) { String[] split = string.split(">"); IRanking<IDyad> ranking = new Ranking<>(); Arrays.stream(split).map(x -> x.substring(1, x.length() - 1)).map(x -> new Dyad(this.parseVector(x.split(";")[0]), this.parseVector(x.split(",")[1]))).forEach(ranking::add); return ranking; } private IVector parseVector(final String vectorString) { String[] split = vectorString.substring(1, vectorString.length() - 1).split(","); return new DenseDoubleVector(Arrays.stream(split).mapToDouble(Double::parseDouble).toArray()); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/DyadRankingAttributeValue.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IRankingAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IRankingAttributeValue; import org.api4.java.ai.ml.ranking.IRanking; import org.api4.java.ai.ml.ranking.dyad.dataset.IDyad; public class DyadRankingAttributeValue implements IRankingAttributeValue<IDyad> { private final IRankingAttribute<IDyad> attribute; private final IRanking<IDyad> value; public DyadRankingAttributeValue(final IRankingAttribute<IDyad> attribute, final IRanking<IDyad> value) { this.attribute = attribute; this.value = value; } @Override public IRanking<IDyad> getValue() { return this.value; } @Override public IRankingAttribute<IDyad> getAttribute() { return null; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/IntBasedCategoricalAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttributeValue; public class IntBasedCategoricalAttribute extends AAttribute implements ICategoricalAttribute { /** * */ private static final long serialVersionUID = 3727153881173459843L; private final Map<String, Integer> valuePosCache = new HashMap<>(); private final List<String> domain; private final int numCategories; public IntBasedCategoricalAttribute(final String name, final List<String> domain) { super(name); this.domain = domain; IntStream.range(0, domain.size()).forEach(i -> this.valuePosCache.put(domain.get(i), i)); this.numCategories = domain.size(); } @Override public String getStringDescriptionOfDomain() { return this.domain.toString(); } @Override public List<String> getLabels() { return Collections.unmodifiableList(this.domain); } @Override public boolean isBinary() { return this.getLabels().size() == 2; } @Override public boolean isValidValue(final Object attributeValue) { if (attributeValue == null) { return true; } Integer value = null; if (attributeValue instanceof ICategoricalAttributeValue) { value = ((ICategoricalAttributeValue) attributeValue).getValue(); } else if (attributeValue instanceof Integer) { value = (Integer) attributeValue; } else if (attributeValue instanceof Double) { value = (int) (double) attributeValue; } else if (this.domain.contains(attributeValue)) { value = this.valuePosCache.get(attributeValue); } if (value == null) { return false; } else { return value < this.domain.size(); } } @Override public double encodeValue(final Object attributeValue) { if (!this.isValidValue(attributeValue)) { throw new IllegalArgumentException("No valid attribute value."); } return this.valuePosCache.get(this.getLabelOfAttributeValue(attributeValue)); } @Override public String decodeValue(final double encodedAttributeValue) { return this.domain.get((int) encodedAttributeValue); } private String getLabelOfAttributeValue(final Object object) { if (object instanceof ICategoricalAttributeValue) { return this.domain.get(((ICategoricalAttributeValue) object).getValue()); } else if (object instanceof String) { return (String) object; } else { throw new IllegalArgumentException("No valid attribute value"); } } @Override public ICategoricalAttributeValue getAsAttributeValue(final Object object) { if (object == null) { return null; } if (this.isValidValue(object)) { int cObject; if (object instanceof Integer) { cObject = (int) object; } else if (object instanceof ICategoricalAttributeValue) { cObject = ((ICategoricalAttributeValue) object).getValue(); } else { cObject = this.valuePosCache.get(object); if (cObject < 0) { throw new IllegalStateException("Object should be parseable after the test."); } } return new IntBasedCategoricalAttributeValue(this, cObject); } else { throw new IllegalArgumentException(object + " is an invalid value for categorical attribute with domain " + this.getStringDescriptionOfDomain()); } } @Override public ICategoricalAttributeValue getAsAttributeValue(final double encodedAttributeValue) { return this.getAsAttributeValue(this.decodeValue(encodedAttributeValue)); } public String getNameOfCategory(final int categoryId) { return this.domain.get(categoryId); } @Override public double toDouble(final Object value) { if (!(value instanceof Integer)) { throw new IllegalArgumentException(); } return (double)value; } @Override public String serializeAttributeValue(final Object value) { if (value == null) { return null; } if (!(value instanceof Integer)) { if (!this.domain.contains(value)) { throw new IllegalArgumentException("The given value \"" + value + "\" is not part of the domain and cannot be serialized. The domain is: " + this.domain); } return (String) value; // here we know that this must be a String; otherwise it could not be in the domain! } if (((Integer) value) < 0) { return null; } return this.domain.get((Integer) value); } @Override public Integer deserializeAttributeValue(final String string) { String trimmedString = string.trim(); if ((string.startsWith("'") && string.endsWith("'")) || (string.startsWith("\"") && string.endsWith("\""))) { trimmedString = trimmedString.substring(1, trimmedString.length() - 1); } if (!this.valuePosCache.containsKey(trimmedString)) { return null; // return null for missing values } int indexOf = this.valuePosCache.get(trimmedString); // storing this as an int here is important in order to obtain an exception on null return indexOf; } @Override public int getNumberOfCategories() { return this.numCategories; } @Override public String getLabelOfCategory(final Number categoryId) { return this.domain.get((int) categoryId); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.domain == null) ? 0 : this.domain.hashCode()); result = prime * result + this.numCategories; return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } IntBasedCategoricalAttribute other = (IntBasedCategoricalAttribute) obj; if (this.domain == null) { if (other.domain != null) { return false; } } else if (!this.domain.equals(other.domain)) { return false; } return this.numCategories == other.numCategories; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/IntBasedCategoricalAttributeValue.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttributeValue; public class IntBasedCategoricalAttributeValue implements ICategoricalAttributeValue { private final ICategoricalAttribute attribute; private final int value; public IntBasedCategoricalAttributeValue(final ICategoricalAttribute attribute, final int value) { this.attribute = attribute; this.value = value; } public IntBasedCategoricalAttributeValue(final ICategoricalAttributeValue value) { this(value.getAttribute(), value.getValue()); } @Override public Integer getValue() { return this.value; } @Override public ICategoricalAttribute getAttribute() { return this.attribute; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/LabelRankingAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.api4.java.ai.ml.core.dataset.schema.attribute.IRankingAttributeValue; import org.api4.java.ai.ml.ranking.IRanking; public class LabelRankingAttribute extends ARankingAttribute<String> { private static final long serialVersionUID = -7357189772771718391L; private final Collection<String> labels; public LabelRankingAttribute(final String name, final Collection<String> labels) { super(name); this.labels = labels; } @Override public boolean isValidValue(final Object value) { if (value instanceof IRanking) { IRanking<?> ranking = (IRanking<?>) value; Set<String> labelsInRanking = new HashSet<>(); for (Object rankedObject : ranking) { if (rankedObject instanceof String) { labelsInRanking.add((String) rankedObject); } else { return false; } } return this.labels.containsAll(labelsInRanking); } return (value instanceof LabelRankingAttributeValue); } public Collection<String> getLabels() { return this.labels; } @Override public String getStringDescriptionOfDomain() { return "[LR] " + this.getName() + " " + this.labels; } @Override public IRankingAttributeValue<String> getAsAttributeValue(final Object object) { return new LabelRankingAttributeValue(this, this.getValueAsTypeInstance(object)); } @SuppressWarnings("unchecked") @Override protected IRanking<String> getValueAsTypeInstance(final Object object) { if (this.isValidValue(object)) { if (object instanceof LabelRankingAttributeValue) { return ((LabelRankingAttributeValue) object).getValue(); } else { return (IRanking<String>) object; } } else { throw new IllegalArgumentException("No valid value of this attribute"); } } @Override public double toDouble(final Object object) { throw new UnsupportedOperationException("Not yet implemented in LabelRankingAttribute"); } @Override public String serializeAttributeValue(final Object value) { throw new UnsupportedOperationException("Not yet implemented."); } @Override public Object deserializeAttributeValue(final String string) { throw new UnsupportedOperationException("Not yet implemented."); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.labels == null) ? 0 : this.labels.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } LabelRankingAttribute other = (LabelRankingAttribute) obj; if (this.labels == null) { if (other.labels != null) { return false; } } else if (!this.labels.equals(other.labels)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/LabelRankingAttributeValue.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IRankingAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IRankingAttributeValue; import org.api4.java.ai.ml.ranking.IRanking; public class LabelRankingAttributeValue implements IRankingAttributeValue<String> { private IRankingAttribute<String> attribute; private IRanking<String> value; public LabelRankingAttributeValue(final IRankingAttribute<String> attribute, final IRanking<String> value) { this.value = value; this.attribute = attribute; } @Override public IRanking<String> getValue() { return this.value; } @Override public IAttribute getAttribute() { return this.attribute; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/MultiLabelAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Collection; import java.util.List; import java.util.Set; import org.api4.java.ai.ml.core.dataset.schema.attribute.IMultiLabelAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IMultiLabelAttributeValue; public class MultiLabelAttribute extends ACollectionOfObjectsAttribute<String> implements IMultiLabelAttribute { /** * */ private static final long serialVersionUID = -6840951353348119686L; private final List<String> domain; public MultiLabelAttribute(final String name, final List<String> domain) { super(name); this.domain = domain; } @SuppressWarnings("unchecked") @Override public boolean isValidValue(final Object value) { if ((value instanceof Set<?> && ((Set<?>) value).iterator().next() instanceof String)) { return this.domain.containsAll((Set<String>) value); } else if (value instanceof IMultiLabelAttributeValue) { return this.domain.containsAll(((IMultiLabelAttributeValue) value).getValue()); } else { return false; } } @Override public String getStringDescriptionOfDomain() { return "MultiValuedNominalAttribute " + this.getName() + " " + this.domain; } @SuppressWarnings("unchecked") @Override public IMultiLabelAttributeValue getAsAttributeValue(final Object object) { if (this.isValidValue(object)) { if (object instanceof IMultiLabelAttributeValue) { return new MultiLabelAttributeValue(this, ((IMultiLabelAttributeValue) object).getValue()); } else { return new MultiLabelAttributeValue(this, (Collection<String>) object); } } else { throw new IllegalArgumentException("No valid value for the type"); } } @SuppressWarnings("unchecked") @Override protected Collection<String> getValueAsTypeInstance(final Object object) { if (this.isValidValue(object)) { if (object instanceof IMultiLabelAttributeValue) { return ((IMultiLabelAttributeValue) object).getValue(); } else { return (Collection<String>) object; } } else { throw new IllegalArgumentException("No valid value for the type"); } } @Override public double toDouble(final Object object) { throw new UnsupportedOperationException("Not yet implemented in MultiValueAttribute"); } @Override public String serializeAttributeValue(final Object value) { throw new UnsupportedOperationException("Not yet implemented."); } @Override public Object deserializeAttributeValue(final String string) { throw new UnsupportedOperationException("Not yet implemented."); } @Override public List<String> getValues() { return this.domain; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.domain == null) ? 0 : this.domain.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } MultiLabelAttribute other = (MultiLabelAttribute) obj; if (this.domain == null) { if (other.domain != null) { return false; } } else if (!this.domain.equals(other.domain)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/MultiLabelAttributeValue.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Collection; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IMultiLabelAttributeValue; public class MultiLabelAttributeValue implements IMultiLabelAttributeValue { private MultiLabelAttribute attribute; private Collection<String> value; public MultiLabelAttributeValue(final MultiLabelAttribute attribute, final Collection<String> value) { this.attribute = attribute; this.value = value; } @Override public Collection<String> getValue() { return this.value; } @Override public IAttribute getAttribute() { return this.attribute; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/MultidimensionalAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Arrays; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IObjectAttribute; /** * This is an {@link IAttribute} class that holds Multidimensional Double Arrays. * * @author Lukas Fehring * * @param <O> O is the type of the {@link MultidimensionalAttributeValue} that is parsed using this {@link IAttribute}. This should be a double array of dimension 2 or 3. */ public abstract class MultidimensionalAttribute<O> extends AGenericObjectAttribute<O> implements IObjectAttribute<NumericAttribute> { private static final long serialVersionUID = -1416829149499898655L; protected static final String SINGLE_SPACE = " "; protected static final String ARRAY_STRING_SPLITTER = ","; protected static final String EMPTY_STRING = ""; protected static final String OPEN_OR_CLOSED_BRACES_REGEX = "\\[|\\]"; protected static final String INNTER_ARRAY_SPLITTER = "\\],\\["; protected static final String WHITESPACE_REGEX = "\\s+"; protected MultidimensionalAttribute(final String name) { super(name); } @Override public double toDouble(final Object object) { throw new UnsupportedOperationException("Not yet implemented in MultidimensionalAttribute"); } /** * {@inheritDoc} This method takes and parameter of type {@link MultidimensionalAttributeValue} or O and serializes it. The resulting form should look like [[a b] [c d] ... [e f]]. */ @Override public String serializeAttributeValue(final Object value) { Object[] castvalue = (Object[]) value; String serialisedString = Arrays.deepToString(castvalue); return serialisedString.replace(MultidimensionalAttribute.ARRAY_STRING_SPLITTER, MultidimensionalAttribute.SINGLE_SPACE).replaceAll(MultidimensionalAttribute.WHITESPACE_REGEX, MultidimensionalAttribute.SINGLE_SPACE); } protected abstract O formGenericMultidimensionalArray(String[] values); @Override public O deserializeAttributeValue(final String string) { String formatstring = string.replaceAll(MultidimensionalAttribute.OPEN_OR_CLOSED_BRACES_REGEX, MultidimensionalAttribute.EMPTY_STRING); String[] stringvalues = formatstring.split(MultidimensionalAttribute.SINGLE_SPACE); return this.formGenericMultidimensionalArray(stringvalues); } @SuppressWarnings("unchecked") @Override protected O getValueAsTypeInstance(final Object object) { if (this.isValidValue(object)) { if (object instanceof MultidimensionalAttributeValue<?>) { return (O) ((MultidimensionalAttributeValue<?>) object).getValue(); } else { return (O) object; } } throw new IllegalArgumentException("No valid value for this attribute"); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/MultidimensionalAttributeValue.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttributeValue; public class MultidimensionalAttributeValue<O> implements IAttributeValue { protected O value; protected MultidimensionalAttribute<O> attribute; public MultidimensionalAttributeValue(final MultidimensionalAttribute<O> attribute, final O object) { this.value = object; this.attribute = attribute; } @Override public IAttribute getAttribute() { return this.attribute; } @Override public O getValue() { return this.value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.attribute == null) ? 0 : this.attribute.hashCode()); result = prime * result + ((this.value == null) ? 0 : this.value.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") MultidimensionalAttributeValue<O> other = (MultidimensionalAttributeValue<O>) obj; if (this.attribute == null) { if (other.attribute != null) { return false; } } else if (!this.attribute.equals(other.attribute)) { return false; } if (this.value == null) { if (other.value != null) { return false; } } else if (!this.value.equals(other.value)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/NumericAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.apache.commons.lang3.math.NumberUtils; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttributeValue; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttributeValue; public class NumericAttribute extends AAttribute implements INumericAttribute { private static final long serialVersionUID = 657993241775006166L; public NumericAttribute(final String name) { super(name); } @Override public boolean isValidValue(final Object value) { return (value == null || value instanceof Number || value instanceof INumericAttributeValue); } @Override public String getStringDescriptionOfDomain() { return "[Num] " + this.getName(); } private double getAttributeValueAsDouble(final Object attributeValue) { if (attributeValue == null || attributeValue.toString().trim().isEmpty()) { return Double.NaN; } if (attributeValue instanceof INumericAttributeValue) { return ((INumericAttributeValue) attributeValue).getValue(); } else if (attributeValue instanceof Integer) { return ((Integer) attributeValue); } else if (attributeValue instanceof Long) { return ((Long) attributeValue); } else if (attributeValue instanceof Double) { return (Double) attributeValue; } else if (attributeValue instanceof String && NumberUtils.isCreatable((String) attributeValue)) { return NumberUtils.createDouble((String) attributeValue); } else { throw new IllegalArgumentException("No valid attribute value " + attributeValue + " for attribute " + this.getClass().getName()); } } @Override public INumericAttributeValue getAsAttributeValue(final Object obj) { return new NumericAttributeValue(this, this.getAttributeValueAsDouble(obj)); } @Override public double encodeValue(final Object attributeValue) { if (!this.isValidValue(attributeValue)) { throw new IllegalArgumentException("No valid attribute value"); } return this.getAttributeValueAsDouble(attributeValue); } @Override public Double decodeValue(final double encodedAttributeValue) { return encodedAttributeValue; } @Override public IAttributeValue getAsAttributeValue(final double encodedAttributeValue) { return new NumericAttributeValue(this, encodedAttributeValue); } @Override public double toDouble(final Object object) { return this.getAttributeValueAsDouble(object); } @Override public String serializeAttributeValue(final Object value) { if (value == null) { return null; } Double doubleValue = this.getAttributeValueAsDouble(value); if (doubleValue % 1 == 0) { if (doubleValue > Integer.MAX_VALUE) { return doubleValue.longValue() + ""; } else { return doubleValue.intValue() + ""; } } return doubleValue + ""; } @Override public Double deserializeAttributeValue(final String string) { return string.equals("null") ? null : Double.parseDouble(string); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/NumericAttributeValue.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttributeValue; public class NumericAttributeValue implements INumericAttributeValue { private INumericAttribute attribute; private final double value; public NumericAttributeValue(final INumericAttribute attribute, final double value) { this.attribute = attribute; this.value = value; } public NumericAttributeValue(final INumericAttributeValue value) { this(value.getAttribute(), value.getValue()); } @Override public Double getValue() { return this.value; } @Override public INumericAttribute getAttribute() { return this.attribute; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/SetOfObjectsAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Collection; import java.util.Set; import java.util.StringJoiner; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttributeValue; import org.api4.java.ai.ml.core.dataset.schema.attribute.ISetOfObjectsAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ISetOfObjectsAttributeValue; public class SetOfObjectsAttribute<O> extends ACollectionOfObjectsAttribute<O> implements ISetOfObjectsAttribute<O> { private static final long serialVersionUID = 4372755490714119056L; private Class<O> classOfObject; private transient Set<O> domain; public SetOfObjectsAttribute(final String name, final Class<O> classOfObject, final Set<O> domain) { super(name); this.domain = domain; this.classOfObject = classOfObject; } public SetOfObjectsAttribute(final String name, final Class<O> classOfObject) { this(name, classOfObject, null); } @Override public boolean isValidValue(final Object value) { if (value instanceof Set) { Set<?> set = (Set<?>) value; if (!set.isEmpty()) { Object anyElement = set.iterator().next(); if (this.classOfObject.isInstance(anyElement) && this.domain != null) { return set.stream().allMatch(o -> this.domain.contains(o)); } } } if (value instanceof SetOfObjectsAttributeValue) { Set<?> setOfObjects = ((SetOfObjectsAttributeValue<?>) value).getValue(); return this.isValidValue(setOfObjects); } return false; } @Override public String getStringDescriptionOfDomain() { String description = "[Set]"; if (this.domain != null) { StringJoiner stringJoiner = new StringJoiner(","); for (O object : this.domain) { stringJoiner.add(object.toString()); } description += stringJoiner.toString(); } return description + this.getName(); } @SuppressWarnings("unchecked") @Override public IAttributeValue getAsAttributeValue(final Object object) { if (this.isValidValue(object)) { if (object instanceof SetOfObjectsAttributeValue<?>) { return new SetOfObjectsAttributeValue<>(((SetOfObjectsAttributeValue<O>) object).getValue(), this); } return new SetOfObjectsAttributeValue<>((Set<O>) object, this); } throw new IllegalArgumentException("No valid value of this attribute"); } @Override public double toDouble(final Object object) { throw new UnsupportedOperationException("Not supported"); } @Override public String serializeAttributeValue(final Object value) { throw new UnsupportedOperationException("Not yet implemented!"); } @Override public Object deserializeAttributeValue(final String string) { throw new UnsupportedOperationException("Not yet implemented!"); } @SuppressWarnings("unchecked") @Override protected Collection<O> getValueAsTypeInstance(final Object object) { if (this.isValidValue(object) && object instanceof ISetOfObjectsAttributeValue) { Set<?> set = ((ISetOfObjectsAttributeValue<?>) object).getValue(); if (!set.isEmpty()) { Object elementFromSet = set.iterator().next(); if (this.classOfObject.isInstance(elementFromSet)) { return ((ISetOfObjectsAttributeValue<O>) object).getValue(); } } } throw new IllegalArgumentException("No valid value for the type"); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.classOfObject == null) ? 0 : this.classOfObject.hashCode()); result = prime * result + ((this.domain == null) ? 0 : this.domain.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } SetOfObjectsAttribute other = (SetOfObjectsAttribute) obj; if (this.classOfObject == null) { if (other.classOfObject != null) { return false; } } else if (!this.classOfObject.equals(other.classOfObject)) { return false; } if (this.domain == null) { if (other.domain != null) { return false; } } else if (!this.domain.equals(other.domain)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/SetOfObjectsAttributeValue.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import java.util.Set; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ISetOfObjectsAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ISetOfObjectsAttributeValue; public class SetOfObjectsAttributeValue<O> implements ISetOfObjectsAttributeValue<O> { private Set<O> setOfObjects; private ISetOfObjectsAttribute<O> attribute; public SetOfObjectsAttributeValue(Set<O> setOfObjects, ISetOfObjectsAttribute<O> attribute) { super(); this.setOfObjects = setOfObjects; this.attribute = attribute; } @Override public IAttribute getAttribute() { return attribute; } @Override public Set<O> getValue() { return setOfObjects; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/StringAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IStringAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IStringAttributeValue; public class StringAttribute extends AGenericObjectAttribute<String> implements IStringAttribute { /** * */ private static final long serialVersionUID = -4891018283425655933L; public StringAttribute(final String name) { super(name); } @Override public boolean isValidValue(final Object value) { return (value instanceof String || value instanceof IStringAttributeValue); } @Override public String getStringDescriptionOfDomain() { return "[Str] " + this.getName(); } @Override public IStringAttributeValue getAsAttributeValue(final Object object) { return new StringAttributeValue(this, this.getValueAsTypeInstance(object)); } @Override protected String getValueAsTypeInstance(final Object object) { if (this.isValidValue(object)) { if (object instanceof String) { return (String) object; } else { return ((StringAttributeValue) object).getValue(); } } else { throw new IllegalArgumentException("No valid value of this attribute"); } } @Override public double toDouble(final Object object) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public String serializeAttributeValue(final Object value) { return this.getValueAsTypeInstance(value); } @Override public Object deserializeAttributeValue(final String string) { return string; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/StringAttributeValue.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IStringAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IStringAttributeValue; public class StringAttributeValue implements IStringAttributeValue { private IStringAttribute attribute; private final String value; public StringAttributeValue(final IStringAttribute attribute, final String value) { this.attribute = attribute; this.value = value; } @Override public String getValue() { return this.value; } @Override public IStringAttribute getAttribute() { return this.attribute; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/ThreeDimensionalAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttributeValue; /** * A {@link MultidimensionalAttribute} that holds three dimensional double arrays. * * @author Lukas * */ public class ThreeDimensionalAttribute extends MultidimensionalAttribute<double[][][]> { private static final long serialVersionUID = 3932496459363695399L; private int xsize; private int ysize; private int zsize; public ThreeDimensionalAttribute(final String name, final int xsize, final int ysize, final int zsize) { super(name); this.xsize = xsize; this.ysize = ysize; this.zsize = zsize; } /** * {@inheritDoc} This method takes object type double[][][] or {@link MultidimensionalAttributeValue} and returns a {@link MultidimensionalAttributeValue} that holds the same values. */ @Override public IAttributeValue getAsAttributeValue(final Object object) { if (object instanceof double[][][]) { return new MultidimensionalAttributeValue<double[][][]>(this, (double[][][]) object); } else if (object instanceof MultidimensionalAttributeValue) { return new MultidimensionalAttributeValue<double[][][]>(this, (double[][][]) ((MultidimensionalAttributeValue) object).getValue()); } throw new IllegalArgumentException("No valid value for this attribute"); } @Override public boolean isValidValue(final Object value) { return (value instanceof MultidimensionalAttributeValue || value instanceof double[][][]); } @Override public String getStringDescriptionOfDomain() { return "[3d] " + this.getName(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + this.xsize; result = prime * result + this.ysize; result = prime * result + this.zsize; return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } ThreeDimensionalAttribute other = (ThreeDimensionalAttribute) obj; return this.xsize == other.xsize && this.ysize == other.ysize && this.zsize == other.zsize; } @Override public double[][][] formGenericMultidimensionalArray(final String[] stringvalues) { double[][][] doublevalues = new double[this.xsize][this.ysize][this.zsize]; int position = 0; for (int x = 0; x < this.xsize; x++) { double[][] nextdouble = new double[this.ysize][this.zsize]; for (int y = 0; y < this.ysize; y++) { double[] nextsingle = new double[this.zsize]; for (int z = 0; z < this.zsize; z++) { try { nextsingle[z] = Double.parseDouble(stringvalues[position]); } catch (NumberFormatException e) { throw new IllegalArgumentException("No valid value of this attribute"); } position++; } nextdouble[y] = nextsingle; } doublevalues[x] = nextdouble; } return doublevalues; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/TwoDimensionalAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttributeValue; /** * A {@link MultidimensionalAttribute} that holds two dimensional double arrays. * * @author Lukas Fehring * */ public class TwoDimensionalAttribute extends MultidimensionalAttribute<double[][]> { private static final long serialVersionUID = -3300254871190010390L; private int xsize; private int ysize; public int getXsize() { return this.xsize; } public int getYsize() { return this.ysize; } public TwoDimensionalAttribute(final String name, final int xsize, final int ysize) { super(name); this.xsize = xsize; this.ysize = ysize; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + this.xsize; result = prime * result + this.ysize; return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } TwoDimensionalAttribute other = (TwoDimensionalAttribute) obj; return this.xsize == other.xsize && this.ysize == other.ysize; } /** * {@inheritDoc} This method takes a parameter of type double[][] or {@link MultidimensionalAttributeValue} and returns a {@link MultidimensionalAttributeValue} that holds the same values */ @SuppressWarnings("unchecked") @Override public IAttributeValue getAsAttributeValue(final Object object) { if (object instanceof double[][]) { return new MultidimensionalAttributeValue<double[][]>(this, (double[][]) object); } else if (object instanceof MultidimensionalAttributeValue) { return new MultidimensionalAttributeValue<double[][]>(this, ((MultidimensionalAttributeValue<double[][]>) object).getValue()); } throw new IllegalArgumentException("No valid value for this attribute"); } @Override public boolean isValidValue(final Object value) { return (value instanceof MultidimensionalAttributeValue || value instanceof double[][]); } @Override public String getStringDescriptionOfDomain() { return "[2D] " + this.getName(); } /** * {@inheritDoc} parses String string to MutidimensionalAttributeValue */ @Override public double[][] formGenericMultidimensionalArray(final String[] stringvalues) { double[][] doubleValues = new double[this.xsize][this.ysize]; int position = 0; for (int x = 0; x < this.xsize; x++) { double[] innerArray = new double[this.ysize]; for (int y = 0; y < this.ysize; y++) { try { innerArray[y] = Double.parseDouble(stringvalues[position]); } catch (NumberFormatException e) { throw new IllegalArgumentException("No valid value of this attribute"); } position++; } doubleValues[x] = innerArray; } return doubleValues; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/schema/attribute/package-info.java
/** * This package contains various types of attributes and their respective values that can be used within a dataset. * Each of these attributes is capable of encoding a possibly complex attribute value as a double. * */ package ai.libs.jaicore.ml.core.dataset.schema.attribute;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/ArffDatasetAdapter.java
package ai.libs.jaicore.ml.core.dataset.serialization; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.api4.java.ai.ml.core.dataset.descriptor.IDatasetDescriptor; import org.api4.java.ai.ml.core.dataset.descriptor.IFileDatasetDescriptor; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.IStringAttribute; import org.api4.java.ai.ml.core.dataset.serialization.DatasetDeserializationFailedException; import org.api4.java.ai.ml.core.dataset.serialization.IDatasetDeserializer; import org.api4.java.ai.ml.core.dataset.serialization.UnsupportedAttributeTypeException; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.OptionsParser; import ai.libs.jaicore.basic.kvstore.KVStore; import ai.libs.jaicore.ml.core.dataset.Dataset; import ai.libs.jaicore.ml.core.dataset.DenseInstance; import ai.libs.jaicore.ml.core.dataset.SparseInstance; import ai.libs.jaicore.ml.core.dataset.schema.LabeledInstanceSchema; import ai.libs.jaicore.ml.core.dataset.schema.attribute.IntBasedCategoricalAttribute; import ai.libs.jaicore.ml.core.dataset.schema.attribute.NumericAttribute; import ai.libs.jaicore.ml.core.dataset.schema.attribute.StringAttribute; import ai.libs.jaicore.ml.core.dataset.schema.attribute.ThreeDimensionalAttribute; import ai.libs.jaicore.ml.core.dataset.schema.attribute.TwoDimensionalAttribute; import ai.libs.jaicore.ml.core.dataset.serialization.arff.EArffAttributeType; import ai.libs.jaicore.ml.core.dataset.serialization.arff.EArffItem; import ai.libs.jaicore.ml.pdm.dataset.SensorTimeSeriesAttribute; /** * Handles dataset files in the arff format {@link https://waikato.github.io/weka-wiki/formats_and_processing/arff/} */ public class ArffDatasetAdapter implements IDatasetDeserializer<ILabeledDataset<ILabeledInstance>>, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(ArffDatasetAdapter.class); public static final String V_MISSING_VALUE = "?"; public static final String K_RELATION_NAME = "relationName"; public static final String K_CLASS_INDEX = "classIndex"; public static final Pattern REG_EXP_DATA_LINE = Pattern.compile("(?<=,|^)( *'([^']*)'| *\"([^\"]*)\"|([^,]*))(?=,|$)"); private static final String F_CLASS_INDEX = "C"; private static final String SEPARATOR_RELATIONNAME = ":"; private static final Pattern REG_EXP_ATTRIBUTE_DESCRIPTION = Pattern.compile("('[^']*'|[^ ]+)\\s+(.*)"); private static final String SEPARATOR_DENSE_INSTANCE_VALUES = ","; private final boolean sparseMode; private IDatasetDescriptor datasetDescriptor = null; public ArffDatasetAdapter(final boolean sparseMode, final IDatasetDescriptor datasetDescriptor) { this(sparseMode); this.datasetDescriptor = datasetDescriptor; } public ArffDatasetAdapter(final boolean sparseMode) { this.sparseMode = sparseMode; } public ArffDatasetAdapter() { this(false); } public IAttribute getAttributeWithName(final IFileDatasetDescriptor datasetFile, final String nameOfAttribute) throws DatasetDeserializationFailedException { try (BufferedReader br = Files.newBufferedReader(datasetFile.getDatasetDescription().toPath())) { String line; while ((line = br.readLine()) != null) { if (line.toLowerCase().startsWith(EArffItem.ATTRIBUTE.getValue().toLowerCase())) { IAttribute att = this.parseAttribute(line); if (att.getName().equals(nameOfAttribute)) { return att; } } } throw new NoSuchElementException("No attribute with name " + nameOfAttribute + " found."); } catch (Exception e) { throw new DatasetDeserializationFailedException(e); } } public ILabeledDataset<ILabeledInstance> deserializeDataset(final IFileDatasetDescriptor datasetFile, final String nameOfClassAttribute) throws DatasetDeserializationFailedException { Objects.requireNonNull(datasetFile, "No dataset has been configured."); /* read the file until the class parameter is found and count the params */ int numAttributes = 0; try (BufferedReader br = Files.newBufferedReader(datasetFile.getDatasetDescription().toPath())) { String line; while ((line = br.readLine()) != null) { if (line.toLowerCase().startsWith(EArffItem.ATTRIBUTE.getValue().toLowerCase())) { IAttribute att = this.parseAttribute(line); if (att.getName().equals(nameOfClassAttribute)) { break; } numAttributes++; } } } catch (Exception e) { throw new DatasetDeserializationFailedException(e); } this.logger.info("Successfully identified class attribute index {} for attribute with name {}. Now reading in the dataset based on this info.", numAttributes, nameOfClassAttribute); return this.deserializeDataset(datasetFile, numAttributes); } public ILabeledDataset<ILabeledInstance> deserializeDataset(final IFileDatasetDescriptor datasetDescriptor, final int columnWithClassIndex) throws DatasetDeserializationFailedException { Objects.requireNonNull(datasetDescriptor, "No dataset has been configured."); return this.readDataset(this.sparseMode, datasetDescriptor.getDatasetDescription(), columnWithClassIndex); } @Override public ILabeledDataset<ILabeledInstance> deserializeDataset(final IDatasetDescriptor datasetDescriptor) throws DatasetDeserializationFailedException, InterruptedException { if (!(datasetDescriptor instanceof IFileDatasetDescriptor)) { throw new DatasetDeserializationFailedException("Cannot handle dataset descriptor of type " + datasetDescriptor.getClass().getName()); } return this.deserializeDataset((IFileDatasetDescriptor) datasetDescriptor, -1); } public ILabeledDataset<ILabeledInstance> deserializeDataset() throws InterruptedException, DatasetDeserializationFailedException { return this.deserializeDataset(this.datasetDescriptor); } /** * Extracts meta data about a relation from a string. * * @param line The line which is to be parsed to extract the necessary information from the relation name. * @return A KVStore containing the parsed meta data. */ protected KVStore parseRelation(final String line) { KVStore metaData = new KVStore(); // cut off relation tag String relationDescription = line.substring(EArffItem.RELATION.getValue().length()).trim(); if (relationDescription.startsWith("'") && relationDescription.endsWith("'")) { String[] relationNameAndOptions = line.substring(line.indexOf('\'') + 1, line.lastIndexOf('\'')).split(SEPARATOR_RELATIONNAME); metaData.put(K_RELATION_NAME, relationNameAndOptions[0].trim()); if (relationNameAndOptions.length > 1) { OptionsParser optParser = new OptionsParser(relationNameAndOptions[1].trim()); try { int classIndex = Integer.parseInt(optParser.get(F_CLASS_INDEX).toString()); metaData.put(K_CLASS_INDEX, classIndex); } catch (Exception e) { this.logger.warn("Could not read in class index from relation name: {}, class index: {}", line, optParser.get(F_CLASS_INDEX)); } } } else { metaData.put(K_RELATION_NAME, relationDescription); } return metaData; } /** * parses an attribute definition of an ARff file. General format: {@literal @}Attribute {@literal <}attribute_name {@literal >} {@literal <}attribute_type{@literal >} * * @param line to be analyzed * @return Object of class IAttribute * @throws UnsupportedAttributeTypeException when the parsed Attribute not implemented */ protected IAttribute parseAttribute(final String line) throws UnsupportedAttributeTypeException { String attributeDefinitionSplit = line.replace("\\t", " ").substring(EArffItem.ATTRIBUTE.getValue().length() + 1).trim(); Matcher m = REG_EXP_ATTRIBUTE_DESCRIPTION.matcher(attributeDefinitionSplit); if (!m.find()) { throw new IllegalArgumentException("Cannot parse attribute definition: " + line); } String name = m.group(1); String type = m.group(2); name = name.trim(); if ((name.startsWith("'") && name.endsWith("'")) || (name.startsWith("\"") && name.endsWith("\""))) { name = name.substring(1, name.length() - 1); } EArffAttributeType attType; String[] values = null; if (type.startsWith("{") && type.endsWith("}")) { values = this.splitDenseInstanceLine(type.substring(1, type.length() - 1)); attType = EArffAttributeType.NOMINAL; } else if (type.toLowerCase().startsWith(EArffAttributeType.MULTIDIMENSIONAL.getName())) { attType = EArffAttributeType.MULTIDIMENSIONAL; values = type.toLowerCase().substring(EArffAttributeType.MULTIDIMENSIONAL.getName().length() + 1, type.length() - 1).split(SEPARATOR_DENSE_INSTANCE_VALUES); } else { try { attType = EArffAttributeType.valueOf(type.toUpperCase()); } catch (IllegalArgumentException e) { throw new UnsupportedAttributeTypeException("The attribute type " + type.toUpperCase() + " is not supported in the EArffAttributeType ENUM. (line: " + line + ")"); } } switch (attType) { case NUMERIC: case REAL: case INTEGER: return new NumericAttribute(name); case STRING: return new StringAttribute(name); case TIMESERIES: return new SensorTimeSeriesAttribute(name); case NOMINAL: if (values != null) { return new IntBasedCategoricalAttribute(name, Arrays.stream(values).map(String::trim).map(x -> (((x.startsWith("'") && x.endsWith("'")) || x.startsWith("\"") && x.endsWith("\"")) ? x.substring(1, x.length() - 1) : x)).collect(Collectors.toList())); } else { throw new IllegalStateException("Identified a " + EArffAttributeType.NOMINAL.getName() + " attribute but it seems to have no values."); } case MULTIDIMENSIONAL: if (values != null) { if (values.length == 2) { return new TwoDimensionalAttribute(name, Integer.parseInt(values[0]), Integer.parseInt(values[1])); } else if (values.length == 3) { return new ThreeDimensionalAttribute(name, Integer.parseInt(values[0]), Integer.parseInt(values[1]), Integer.parseInt(values[2])); } } throw new IllegalStateException("Identified a " + EArffAttributeType.MULTIDIMENSIONAL.getName() + " attribute but the syntax seems to be wrong."); default: throw new UnsupportedAttributeTypeException("Can not deal with attribute type " + type); } } private boolean tryParseInt(final String string) { try { Integer.parseInt(string); return true; } catch (Exception e) { return false; } } public String[] splitDenseInstanceLine(final String line) { List<String> lineSplit = new ArrayList<>(); Matcher matcher = REG_EXP_DATA_LINE.matcher(line); while (matcher.find()) { String entry = matcher.group(); lineSplit.add(entry); } return lineSplit.toArray(new String[] {}); } /** * Parses a single instance of an ARff file containing values for each attribute given (attributes parameter). Syntax <attribute1_value>, <attribute2_value>, ... * * @param sparseData if true there are ? in the data - if it false there are not * @param attributes List of given IAttribute Objects. * @param targetIndex * @param line line of data * @return list of IAttribute values */ protected List<Object> parseInstance(final boolean sparseData, final List<IAttribute> attributes, final int targetIndex, final String line) { if (line.trim().startsWith("%")) { throw new IllegalArgumentException("Cannot create object for commented line!"); } this.logger.trace("Parsing line with target col {}: {}", targetIndex, line); boolean instanceSparseMode = sparseData; String curLine = line; if (curLine.trim().startsWith("{") && curLine.trim().endsWith("}")) { curLine = curLine.substring(1, curLine.length() - 1); if (curLine.trim().isEmpty()) { // the instance does not mention any explicit values => return an empty map. return Arrays.asList(new HashMap<>(), 0); } } String[] lineSplit = curLine.split(","); if (!(lineSplit[0].startsWith("'") && lineSplit[0].endsWith("'") || lineSplit[0].startsWith("\"") && lineSplit[0].endsWith("\"")) && lineSplit[0].contains(" ") && this.tryParseInt(lineSplit[0].split(" ")[0])) { instanceSparseMode = true; } if (!instanceSparseMode) { lineSplit = this.splitDenseInstanceLine(curLine); if (lineSplit.length != attributes.size()) { throw new IllegalArgumentException("Cannot parse instance as this is not a sparse instance but has less columns than there are attributes defined. Expected values: " + attributes.size() + ". Actual number of values: " + lineSplit.length + ". Values: " + Arrays.toString(lineSplit)); } Object[] parsedDenseInstance = new Object[lineSplit.length - 1]; Object target = null; int cI = 0; for (int i = 0; i < lineSplit.length; i++) { final Object value; if (lineSplit[i].trim().equals(V_MISSING_VALUE)) { value = null; } else { try { value = attributes.get(i).deserializeAttributeValue(lineSplit[i]); } catch (RuntimeException e) { IAttribute att = attributes.get(i); throw new IllegalArgumentException("Could not unserizalize value " + lineSplit[i] + " on attribute " + att.getName() + " with domain " + att.getStringDescriptionOfDomain(), e); } } if (i == targetIndex) { target = value; } else { parsedDenseInstance[cI++] = value; } } return Arrays.asList(parsedDenseInstance, target); } else { Map<Integer, Object> parsedSparseInstance = new HashMap<>(); Object target = 0; for (String sparseValue : lineSplit) { sparseValue = sparseValue.trim(); // remove leading or trailing white spaces. int indexOfFirstSpace = sparseValue.indexOf(' '); int indexOfAttribute = Integer.parseInt(sparseValue.substring(0, indexOfFirstSpace)); String attributeValue = sparseValue.substring(indexOfFirstSpace + 1); assert !parsedSparseInstance.containsKey(indexOfAttribute) : "The attribute index " + indexOfAttribute + " has already been set!"; if (indexOfAttribute == targetIndex) { target = attributes.get(indexOfAttribute).deserializeAttributeValue(attributeValue); } else { parsedSparseInstance.put(indexOfAttribute > targetIndex ? indexOfAttribute - 1 : indexOfAttribute, attributes.get(indexOfAttribute).deserializeAttributeValue(attributeValue)); } } return Arrays.asList(parsedSparseInstance, target); } } protected ILabeledDataset<ILabeledInstance> createDataset(final KVStore relationMetaData, final List<IAttribute> attributes) { if (!relationMetaData.containsKey(K_CLASS_INDEX) || relationMetaData.getAsInt(K_CLASS_INDEX) < 0) { throw new IllegalArgumentException("No (valid) class index given!"); } List<IAttribute> attributeList = new ArrayList<>(attributes); IAttribute labelAttribute = attributeList.remove((int) relationMetaData.getAsInt(K_CLASS_INDEX)); ILabeledInstanceSchema schema = new LabeledInstanceSchema(relationMetaData.getAsString(K_RELATION_NAME), attributeList, labelAttribute); return new Dataset(schema); } public ILabeledDataset<ILabeledInstance> readDataset(final File datasetFile) throws DatasetDeserializationFailedException { return this.readDataset(false, datasetFile); } public ILabeledDataset<ILabeledInstance> readDataset(final boolean sparseMode, final File datasetFile) throws DatasetDeserializationFailedException { return this.readDataset(sparseMode, datasetFile, -1); } /** * Parses the ARff dataset from the given file into a {@link ILabeledDataset} * * @param sparseMode * @param datasetFile file to be parsed * @param columnWithClassIndex * @throws DatasetDeserializationFailedException */ public ILabeledDataset<ILabeledInstance> readDataset(final boolean sparseMode, final File datasetFile, final int columnWithClassIndex) throws DatasetDeserializationFailedException { long timeStart = System.currentTimeMillis(); this.logger.info("Reading in dataset {} considering class index {}. Sparse Mode: {}", datasetFile, columnWithClassIndex, sparseMode); String line = null; long lineCounter = 0; try (BufferedReader br = Files.newBufferedReader(datasetFile.toPath())) { ILabeledDataset<ILabeledInstance> dataset = null; KVStore relationMetaData = new KVStore(); List<IAttribute> attributes = new ArrayList<>(); boolean instanceReadMode = false; while ((line = br.readLine()) != null) { lineCounter++; this.logger.trace("Reading in line {}", lineCounter); // skip comments in arff if (line.trim().startsWith("%")) { continue; } if (!instanceReadMode) { if (line.toLowerCase().startsWith(EArffItem.RELATION.getValue())) { // parse relation meta data relationMetaData = this.parseRelation(line); if (columnWithClassIndex >= 0) { relationMetaData.put(K_CLASS_INDEX, columnWithClassIndex); } } else if (line.toLowerCase().startsWith(EArffItem.ATTRIBUTE.getValue())) { // parse attribute meta data attributes.add(this.parseAttribute(line)); } else if (line.toLowerCase().startsWith(EArffItem.DATA.getValue())) { // switch to instance read mode if (!line.toLowerCase().trim().equals(EArffItem.DATA.getValue())) { throw new IllegalArgumentException( "Error while parsing arff-file on line " + lineCounter + ": There is more in this line than just the data declaration " + EArffItem.DATA.getValue() + ", which is not supported"); } instanceReadMode = true; if (relationMetaData.containsKey(K_CLASS_INDEX) && relationMetaData.getAsInt(K_CLASS_INDEX) >= 0) { dataset = this.createDataset(relationMetaData, attributes); } else { this.logger.warn("Invalid class index in the dataset's meta data ({}): Assuming last column to be the target attribute!", relationMetaData.get(K_CLASS_INDEX)); relationMetaData.put(K_CLASS_INDEX, attributes.size() - 1); dataset = this.createDataset(relationMetaData, attributes); } this.logger.debug("Switched to instance read mode in line {}. Class index is {}", lineCounter, relationMetaData.getAsInt(K_CLASS_INDEX)); } } else { // require dataset to be not null. Objects.requireNonNull(dataset, "The dataset point is empty even though we have skipped to instance read mode already."); line = line.trim(); if (!line.isEmpty() && !line.startsWith("%")) { // ignore empty and comment lines List<Object> parsedInstance = this.parseInstance(sparseMode, attributes, relationMetaData.getAsInt(K_CLASS_INDEX), line); ILabeledInstance newI; if ((parsedInstance.get(0) instanceof Object[])) { newI = new DenseInstance((Object[]) ((List<?>) parsedInstance).get(0), ((List<?>) parsedInstance).get(1)); } else if (parsedInstance.get(0) instanceof Map) { @SuppressWarnings("unchecked") Map<Integer, Object> parsedSparseInstance = (Map<Integer, Object>) parsedInstance.get(0); newI = new SparseInstance(dataset.getNumAttributes(), parsedSparseInstance, parsedInstance.get(1)); } else { throw new IllegalStateException("Severe Error: The format of the parsed instance is not as expected."); } if (newI.getNumAttributes() != dataset.getNumAttributes()) { throw new IllegalStateException("Instance has " + newI.getNumAttributes() + " attributes, but the dataset defines " + dataset.getNumAttributes() + " attributes."); } dataset.add(newI); } } } Objects.requireNonNull(dataset, "Dataset is null, which must not happen!"); long timeEnd = System.currentTimeMillis(); this.logger.info("Dataset of size {}x{} read completely. Runtime was {}ms", dataset.size(), dataset.getNumAttributes(), timeEnd - timeStart); return dataset; } catch (Exception e) { throw new DatasetDeserializationFailedException("Could not deserialize dataset from ARFF file. Error occurred on line " + lineCounter + ": " + line, e); } } public void serializeDataset(final File arffOutputFile, final ILabeledDataset<? extends ILabeledInstance> data) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(arffOutputFile))) { // write metadata this.serializeMetaData(bw, data); bw.write("\n\n"); // write actual data (payload) this.serializeData(bw, data); bw.flush(); } } private void serializeData(final BufferedWriter bw, final ILabeledDataset<? extends ILabeledInstance> data) throws IOException { bw.write(EArffItem.DATA.getValue() + "\n"); for (ILabeledInstance instance : data) { if (instance instanceof SparseInstance) { StringBuilder sb = new StringBuilder(); Map<Integer, Object> attributeValues = ((SparseInstance) instance).getAttributeMap(); List<Integer> keys = new ArrayList<>(attributeValues.keySet()); Collections.sort(keys); sb.append("{"); sb.append(keys.stream().map(x -> x + " " + this.serializeAttributeValue(data.getInstanceSchema().getAttribute(x), attributeValues.get(x))).collect(Collectors.joining(", "))); if (!attributeValues.isEmpty() && instance.isLabelPresent()) { sb.append(","); } sb.append(data.getNumAttributes()); sb.append(" "); sb.append(this.serializeAttributeValue(data.getInstanceSchema().getLabelAttribute(), instance.getLabel())); sb.append("}\n"); bw.write(sb.toString()); } else { Object[] atts = instance.getAttributes(); bw.write(IntStream.range(0, atts.length).mapToObj(x -> this.serializeAttributeValue(data.getInstanceSchema().getAttribute(x), atts[x])).collect(Collectors.joining(","))); bw.write(","); bw.write(this.serializeAttributeValue(data.getInstanceSchema().getLabelAttribute(), instance.getLabel())); bw.write("\n"); } } } private String serializeAttributeValue(final IAttribute att, final Object value) { if (value == null) { return V_MISSING_VALUE; } String returnValue = att.serializeAttributeValue(value); if (att instanceof ICategoricalAttribute || att instanceof IStringAttribute) { returnValue = "'" + returnValue + "'"; } return returnValue; } private void serializeMetaData(final BufferedWriter bw, final ILabeledDataset<? extends ILabeledInstance> data) throws IOException { StringBuilder sb = new StringBuilder(); sb.append(EArffItem.RELATION.getValue() + " '" + data.getRelationName() + "'"); sb.append("\n"); sb.append("\n"); for (IAttribute att : data.getInstanceSchema().getAttributeList()) { sb.append(this.serializeAttribute(att)); sb.append("\n"); } sb.append(this.serializeAttribute(data.getInstanceSchema().getLabelAttribute())); bw.write(sb.toString()); } private String serializeAttribute(final IAttribute att) { StringBuilder sb = new StringBuilder(); sb.append(EArffItem.ATTRIBUTE.getValue() + " '" + att.getName() + "' "); if (att instanceof ICategoricalAttribute) { sb.append("{'" + ((ICategoricalAttribute) att).getLabels().stream().collect(Collectors.joining("','")) + "'}"); } else if (att instanceof INumericAttribute) { sb.append(EArffAttributeType.NUMERIC.getName()); } else if (att instanceof IStringAttribute) { sb.append(EArffAttributeType.STRING.getName()); } else if (att instanceof SensorTimeSeriesAttribute) { sb.append(EArffAttributeType.TIMESERIES.getName()); } return sb.toString(); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/CSVDatasetAdapter.java
package ai.libs.jaicore.ml.core.dataset.serialization; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.api4.java.ai.ml.core.dataset.descriptor.IDatasetDescriptor; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttribute; import org.api4.java.ai.ml.core.dataset.serialization.DatasetDeserializationFailedException; import org.api4.java.ai.ml.core.dataset.serialization.IDatasetDeserializer; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; public class CSVDatasetAdapter implements IDatasetDeserializer<ILabeledDataset<ILabeledInstance>> { public CSVDatasetAdapter() { // nothing to do here } @Override public ILabeledDataset<ILabeledInstance> deserializeDataset(final IDatasetDescriptor datasetDescription) throws DatasetDeserializationFailedException, InterruptedException { throw new UnsupportedOperationException("Not yet supported!"); } public static ILabeledDataset<ILabeledInstance> readDataset(final File csvInputFile) { throw new UnsupportedOperationException("Not yet supported!"); } public static void writeDataset(final File arffOutputFile, final ILabeledDataset<? extends ILabeledInstance> data) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(arffOutputFile))) { // write header line for csv bw.write(data.getInstanceSchema().getAttributeList().stream().map(x -> "\"" + x.getName() + "\"").collect(Collectors.joining(","))); bw.write(","); bw.write("\"" + data.getLabelAttribute().getName() + "\""); bw.write("\n"); for (ILabeledInstance instance : data) { bw.write(IntStream.range(0, instance.getNumAttributes()).mapToObj(x -> serializeAttributeValue(data.getAttribute(x), instance.getAttributeValue(x))).collect(Collectors.joining(","))); bw.write(","); bw.write(serializeAttributeValue(data.getInstanceSchema().getLabelAttribute(), instance.getLabel())); bw.write("\n"); } } } private static String serializeAttributeValue(final IAttribute att, final Object attValue) { if (attValue == null) { return ""; } String value = att.serializeAttributeValue(attValue); if (att instanceof ICategoricalAttribute) { if (value.startsWith("'") && value.endsWith("'")) { value = value.substring(1, value.length() - 2); } if (!value.startsWith("\"")) { value = "\"" + value + "\""; } } return value; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/FileDatasetDescriptor.java
package ai.libs.jaicore.ml.core.dataset.serialization; import java.io.File; import org.api4.java.ai.ml.core.dataset.descriptor.IFileDatasetDescriptor; public class FileDatasetDescriptor implements IFileDatasetDescriptor { private final File datasetFile; public FileDatasetDescriptor(final File datasetFile) { this.datasetFile = datasetFile; } @Override public File getDatasetDescription() { return this.datasetFile; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/ISQLDatasetMapper.java
package ai.libs.jaicore.ml.core.dataset.serialization; import java.io.IOException; import java.sql.SQLException; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.ai.ml.core.dataset.schema.IInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; /** * This interface is meant to offer the ability to serialize and unserialize datasets from and to database tables. * The assumption is that the mapper has information about the database hose and the database itself, so that the * interface only allows to specify the table on which the operations take place. * * @author Felix Mohr * */ public interface ISQLDatasetMapper { public IDataset<?> readDatasetFromTable(String tableName) throws SQLException, IOException; public IInstanceSchema getInstanceSchemaOfTable(String tableName) throws SQLException, IOException; public ILabeledInstanceSchema getInstanceSchemaOfTable(String tableName, String labelField) throws SQLException, IOException; public ILabeledDataset<?> readDatasetFromTable(String tableName, String labelField) throws SQLException, IOException; public IDataset<?> readDatasetFromQuery(String sqlQuery) throws SQLException, IOException; public IInstanceSchema getInstanceSchemaForQuery(String sqlQuery) throws SQLException, IOException; public ILabeledInstanceSchema getInstanceSchemaForQuery(String sqlQuery, String labelField) throws SQLException, IOException; public ILabeledDataset<?> readDatasetFromQuery(String sqlQuery, String labelField) throws SQLException, IOException; public void writeDatasetToDatabase(IDataset<?> dataset, String tableName) throws SQLException, IOException; }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/MySQLDatasetMapper.java
package ai.libs.jaicore.ml.core.dataset.serialization; import java.io.IOException; import java.sql.SQLException; import java.sql.Time; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.math.NumberUtils; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.ai.ml.core.dataset.IInstance; import org.api4.java.ai.ml.core.dataset.schema.IInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.ILabeledInstanceSchema; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttribute; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.datastructure.kvstore.IKVStore; import ai.libs.jaicore.db.IDatabaseAdapter; import ai.libs.jaicore.ml.core.dataset.Dataset; import ai.libs.jaicore.ml.core.dataset.DenseInstance; import ai.libs.jaicore.ml.core.dataset.schema.InstanceSchema; import ai.libs.jaicore.ml.core.dataset.schema.LabeledInstanceSchema; import ai.libs.jaicore.ml.core.dataset.schema.attribute.IntBasedCategoricalAttribute; import ai.libs.jaicore.ml.core.dataset.schema.attribute.NumericAttribute; public class MySQLDatasetMapper implements ISQLDatasetMapper { private final IDatabaseAdapter adapter; public MySQLDatasetMapper(final IDatabaseAdapter adapter) { super(); this.adapter = adapter; } private String getTableSelectQuery(final String tableName) { return "SELECT * FROM `" + tableName + "`"; } @Override public IDataset<?> readDatasetFromTable(final String tableName) throws SQLException { return this.readDatasetFromQuery(this.getTableSelectQuery(tableName)); } @Override public ILabeledDataset<?> readDatasetFromTable(final String tableName, final String labelField) throws SQLException { return this.readDatasetFromQuery(this.getTableSelectQuery(tableName), labelField); } @Override public IDataset<?> readDatasetFromQuery(final String sqlQuery) throws SQLException { throw new UnsupportedOperationException("Can currently only handle labeled data"); } @Override public ILabeledDataset<?> readDatasetFromQuery(final String sqlQuery, final String labelField) throws SQLException { List<IKVStore> relation = this.adapter.getResultsOfQuery(sqlQuery); ILabeledInstanceSchema schema = this.getInstanceSchemaFromResultList(relation, labelField); Dataset ds = new Dataset(schema); for (IKVStore row : relation) { List<Object> attributeValues = new ArrayList<>(); for (IAttribute attribute : schema.getAttributeList()) { if (attribute.getName().equals(labelField)) { continue; } Object receivedVal = row.get(attribute.getName()); Object convertedVal = receivedVal == null ? null : attribute.getAsAttributeValue(receivedVal).getValue() ;// maybe the received val is a number hidden in a string attributeValues.add(convertedVal); } Object labelAttribute = schema.getLabelAttribute().getAsAttributeValue(row.get(labelField)).getValue(); ds.add(new DenseInstance(attributeValues, labelAttribute)); } return ds; } @Override public void writeDatasetToDatabase(final IDataset<?> dataset, final String tableName) throws SQLException, IOException { if (this.adapter.doesTableExist(tableName)) { throw new IllegalArgumentException("Table " + tableName + " already exists!"); } /* create table */ List<String> fieldnames = new ArrayList<>(); Map<String, String> types = new HashMap<>(); List<IAttribute> attributes = dataset.getInstanceSchema().getAttributeList(); if (dataset instanceof ILabeledDataset) { attributes.add(((ILabeledDataset<?>)dataset).getInstanceSchema().getLabelAttribute()); } dataset.getInstanceSchema().getAttributeList().forEach(a -> { if (!a.getName().equals("id")) { fieldnames.add(a.getName()); } String type; if (a.getName().equals("id")) { type = "INT(8)"; } else if (a instanceof ICategoricalAttribute) { type = "VARCHAR(100)"; } else if (a instanceof INumericAttribute) { type = "DOUBLE"; } else { throw new IllegalArgumentException("Unsupported attribute type " + a.getClass()); } types.put(a.getName(), type); }); this.adapter.createTable(tableName, "id", fieldnames, types, Arrays.asList("id")); /* write entries */ List<List<? extends Object>> vals = new ArrayList<>(); for (IInstance i : dataset) { List<Object> row = new ArrayList<>(Arrays.asList(i.getAttributes())); if (i instanceof ILabeledInstance) { row.add(((ILabeledInstance) i).getLabel()); } vals.add(row); } this.adapter.insertMultiple(tableName, attributes.stream().map(IAttribute::getName).collect(Collectors.toList()), vals); } @Override public IInstanceSchema getInstanceSchemaOfTable(final String tableName) throws SQLException { return this.getInstanceSchemaForQuery(this.getTableSelectQuery(tableName)); } @Override public ILabeledInstanceSchema getInstanceSchemaOfTable(final String tableName, final String labelField) throws SQLException { return this.getInstanceSchemaForQuery(this.getTableSelectQuery(tableName), labelField); } @Override public IInstanceSchema getInstanceSchemaForQuery(final String sqlQuery) throws SQLException { return this.getInstanceSchemaFromResultList(this.adapter.getResultsOfQuery(sqlQuery)); } @Override public ILabeledInstanceSchema getInstanceSchemaForQuery(final String sqlQuery, final String labelField) throws SQLException { return this.convertInstanceSchemaIntoLabeledInstanceSchema(this.getInstanceSchemaForQuery(sqlQuery), labelField); } public IInstanceSchema getInstanceSchemaFromResultList(final List<IKVStore> data) { IKVStore firstRow = data.get(0); List<IAttribute> attributeList = new ArrayList<>(firstRow.size()); for (Entry<String, Object> serializedAttribute : firstRow.entrySet()) { Object val = serializedAttribute.getValue(); String key = serializedAttribute.getKey(); if (val == null) { continue; } if (val instanceof Number || (val instanceof String && NumberUtils.isCreatable((String)val))) { attributeList.add(new NumericAttribute(key)); } else if (val instanceof String || val instanceof Time) { Set<Object> availableValues = data.stream().map(r -> r.get(key)).filter(Objects::nonNull).collect(Collectors.toSet()); attributeList.add(new IntBasedCategoricalAttribute(key, availableValues.stream().map(Object::toString).collect(Collectors.toList()))); } else { throw new UnsupportedOperationException("Cannot recognize type of attribute " + key + " with value " + val + " of type " + val.getClass().getName()); } } return new InstanceSchema("SQL-mapped data", attributeList); } public ILabeledInstanceSchema convertInstanceSchemaIntoLabeledInstanceSchema(final IInstanceSchema schema, final String labelField) { List<IAttribute> allAttributes = new ArrayList<>(schema.getAttributeList()); IAttribute targetAttribute = allAttributes.stream().filter(a -> a.getName().equals(labelField)).findAny().get(); allAttributes.remove(targetAttribute); return new LabeledInstanceSchema(schema.getRelationName(), allAttributes, targetAttribute); } public ILabeledInstanceSchema getInstanceSchemaFromResultList(final List<IKVStore> data, final String labelField) { return this.convertInstanceSchemaIntoLabeledInstanceSchema(this.getInstanceSchemaFromResultList(data), labelField); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/OpenMLDatasetDescriptor.java
package ai.libs.jaicore.ml.core.dataset.serialization; import org.api4.java.ai.ml.core.dataset.descriptor.IDatasetDescriptor; public class OpenMLDatasetDescriptor implements IDatasetDescriptor { private final int openMLId; public OpenMLDatasetDescriptor(final int openMLId) { super(); this.openMLId = openMLId; } @Override public String getDatasetDescription() { return "" + this.openMLId; } public int getOpenMLId() { return this.openMLId; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/OpenMLDatasetReader.java
package ai.libs.jaicore.ml.core.dataset.serialization; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.api4.java.ai.ml.core.dataset.descriptor.IDatasetDescriptor; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttribute; import org.api4.java.ai.ml.core.dataset.serialization.DatasetDeserializationFailedException; import org.api4.java.ai.ml.core.dataset.serialization.IDatasetDeserializer; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.common.control.ILoggingCustomizable; import org.openml.apiconnector.io.OpenmlConnector; import org.openml.apiconnector.xml.DataSetDescription; import org.openml.apiconnector.xml.Task; import org.openml.apiconnector.xml.Task.Input; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.reconstruction.ReconstructionInstruction; import ai.libs.jaicore.ml.core.dataset.Dataset; import ai.libs.jaicore.ml.core.filter.SplitterUtil; public class OpenMLDatasetReader implements IDatasetDeserializer<ILabeledDataset<ILabeledInstance>>, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(OpenMLDatasetReader.class); private ArffDatasetAdapter adapter = new ArffDatasetAdapter(); private static final OpenmlConnector connector = new OpenmlConnector(); public static ILabeledDataset<ILabeledInstance> get(final int openmlid) throws DatasetDeserializationFailedException { return new OpenMLDatasetReader().deserializeDataset(openmlid); } public ILabeledDataset<ILabeledInstance> deserializeDataset(final int openMLId) throws DatasetDeserializationFailedException { try { DataSetDescription dsd = connector.dataGet(openMLId); if (dsd.getDefault_target_attribute().contains(",")) { throw new IllegalArgumentException("The dataset with ID " + openMLId + " cannot be read as it is a multi-target dataset which is currently not supported."); } ILabeledDataset<ILabeledInstance> dataset = this.deserializeDataset(openMLId, dsd.getDefault_target_attribute()); if (dsd.getIgnore_attribute() != null) { for (String columnNameToIgnore : dsd.getIgnore_attribute()) { if (dataset.getListOfAttributes().stream().anyMatch(a -> a.getName().equals(columnNameToIgnore))) { dataset.removeColumn(columnNameToIgnore); } else { this.logger.warn("Ignored attribute \"{}\" is not a column of the dataset. Ignoring to ignore it!", columnNameToIgnore); } } } if (dsd.getRow_id_attribute() != null && dataset.getInstanceSchema().getAttributeList().stream().anyMatch(x -> x.getName().equals(dsd.getRow_id_attribute()))) { dataset.removeColumn(dsd.getRow_id_attribute()); } return dataset; } catch (Exception e) { throw new DatasetDeserializationFailedException("Could not deserialize OpenML dataset with id " + openMLId, e); } } public ILabeledDataset<ILabeledInstance> deserializeDataset(final int openMLId, final String targetAttribute) throws DatasetDeserializationFailedException { try { DataSetDescription dsd = connector.dataGet(openMLId); if (dsd.getDefault_target_attribute().contains(",")) { throw new IllegalArgumentException("The dataset with ID " + openMLId + " cannot be read as it is a multi-target dataset which is currently not supported."); } File arffFile = connector.datasetGet(dsd); Dataset ds = (Dataset) (this.adapter.deserializeDataset(new FileDatasetDescriptor(arffFile), targetAttribute)); ds.addInstruction(new ReconstructionInstruction(OpenMLDatasetReader.class.getMethod("get", int.class), openMLId)); return ds; } catch (Exception e) { throw new DatasetDeserializationFailedException("Could not deserialize OpenML dataset with id " + openMLId, e); } } public File getArffFileOfOpenMLID(final int id) throws Exception { DataSetDescription dsd = connector.dataGet(id); return connector.datasetGet(dsd); } @Override public ILabeledDataset<ILabeledInstance> deserializeDataset(final IDatasetDescriptor descriptor) throws DatasetDeserializationFailedException, InterruptedException { if (!(descriptor instanceof OpenMLDatasetDescriptor)) { throw new IllegalArgumentException("Only openml descriptors supported."); } OpenMLDatasetDescriptor cDescriptor = (OpenMLDatasetDescriptor) descriptor; return this.deserializeDataset(cDescriptor.getOpenMLId()); } public List<ILabeledDataset<ILabeledInstance>> loadTaskFold(final int openmlTaskID, final int fold) throws Exception { OpenmlConnector con = new OpenmlConnector(); Task task = con.taskGet(openmlTaskID); File file = con.taskSplitsGet(task); ILabeledDataset<? extends ILabeledInstance> splitDescription = this.adapter.readDataset(file); List<Integer> fitFold = new ArrayList<>(); List<Integer> predictFold = new ArrayList<>(); for (ILabeledInstance i : splitDescription) { if (((int) (double) i.getLabel()) == fold) { int instanceIndex = (int) (double) i.getAttributeValue(1); switch (((ICategoricalAttribute) splitDescription.getAttribute(0)).getLabels().get((int) i.getAttributeValue(0))) { case "TRAIN": fitFold.add(instanceIndex); break; case "TEST": predictFold.add(instanceIndex); break; default: /* ignore this case */ break; } } } ILabeledDataset<ILabeledInstance> dataset = null; for (Input input : task.getInputs()) { if (input.getName().equals("source_data")) { dataset = this.deserializeDataset(input.getData_set().getData_set_id(), input.getData_set().getTarget_feature()); } } return SplitterUtil.getRealizationOfSplitSpecification(dataset, Arrays.asList(fitFold, predictFold)); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); this.adapter.setLoggerName(this.getLoggerName() + ".arffadapter"); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/package-info.java
package ai.libs.jaicore.ml.core.dataset.serialization;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/arff/EArffAttributeType.java
package ai.libs.jaicore.ml.core.dataset.serialization.arff; /** * Enum of supported attribute types * */ public enum EArffAttributeType { NOMINAL("nominal"), // NUMERIC("numeric"), // INTEGER("integer"), // REAL("real"), // STRING("string"), // TIMESERIES("timeseries"), // MULTIDIMENSIONAL("multidimensional"); private final String name; private EArffAttributeType(final String name) { this.name = name; } public String getName() { return this.name; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/arff/EArffItem.java
package ai.libs.jaicore.ml.core.dataset.serialization.arff; /** * enum of possible arff declarations * */ public enum EArffItem { RELATION("@relation"), ATTRIBUTE("@attribute"), DATA("@data"); private final String value; private EArffItem(final String value) { this.value = value; } public String getValue() { return this.value; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/serialization/arff/package-info.java
package ai.libs.jaicore.ml.core.dataset.serialization.arff;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/splitter/DatasetSplitSet.java
package ai.libs.jaicore.ml.core.dataset.splitter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.ai.ml.core.evaluation.execution.IDatasetSplitSet; public class DatasetSplitSet<D extends IDataset<?>> implements IDatasetSplitSet<D> { private final List<List<D>> splits = new ArrayList<>(); public DatasetSplitSet() { /* do nothing */ } public DatasetSplitSet(final IDatasetSplitSet<D> set) { int n = set.getNumberOfSplits(); if (n == 0) { throw new IllegalArgumentException("Cannot create a split set with no folds."); } for (int i = 0; i < n; i++) { this.splits.add(new ArrayList<>(set.getFolds(i))); } } public DatasetSplitSet(final List<List<D>> splits) { this.splits.addAll(splits); } public void addSplit(final List<D> split) { this.splits.add(split); } @Override public int getNumberOfSplits() { return this.splits.size(); } @Override public int getNumberOfFoldsPerSplit() { return this.splits.get(0).size(); } public int getNumberOfFoldsForSplit(final int pos) { return this.splits.get(pos).size(); } @Override public List<D> getFolds(final int splitId) { return Collections.unmodifiableList(this.splits.get(splitId)); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/splitter/RandomHoldoutSplitter.java
package ai.libs.jaicore.ml.core.dataset.splitter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.stream.IntStream; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.ai.ml.core.dataset.splitter.IFoldSizeConfigurableRandomDatasetSplitter; import org.api4.java.ai.ml.core.dataset.splitter.IRandomDatasetSplitter; import org.api4.java.ai.ml.core.dataset.splitter.SplitFailedException; import org.api4.java.ai.ml.core.evaluation.execution.IDatasetSplitSet; import org.api4.java.ai.ml.core.evaluation.execution.IDatasetSplitSetGenerator; import org.api4.java.ai.ml.core.exception.DatasetCreationException; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.common.reconstruction.IReconstructible; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.reconstruction.ReconstructionInstruction; import ai.libs.jaicore.basic.reconstruction.ReconstructionUtil; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.SimpleRandomSampling; /** * This splitter just creates random split without looking at the data. * * @author fmohr * * @param <D> */ public class RandomHoldoutSplitter<D extends IDataset<?>> implements IRandomDatasetSplitter<D>, IDatasetSplitSetGenerator<D>, ILoggingCustomizable, IFoldSizeConfigurableRandomDatasetSplitter<D> { private final Random rand; private final double[] portions; private Logger logger = LoggerFactory.getLogger(RandomHoldoutSplitter.class); public RandomHoldoutSplitter(final double... portions) { this(new Random(), portions); } public RandomHoldoutSplitter(final Random rand, final double... portions) { double portionSum = Arrays.stream(portions).sum(); if (!(portionSum > 0 && portionSum <= 1.0)) { throw new IllegalArgumentException("The sum of the given portions must not be less or equal 0 or larger than 1. Given portions: " + Arrays.toString(portions)); } this.rand = rand; if (portionSum == 1) { this.portions = portions; } else { this.portions = Arrays.copyOf(portions, portions.length + 1); this.portions[portions.length] = 1 - portionSum; } } public static <D extends IDataset<?>> List<D> createSplit(final D data, final long seed, final double... portions) throws SplitFailedException, InterruptedException { return createSplit(data, seed, LoggerFactory.getLogger(RandomHoldoutSplitter.class), portions); } /** * This static method exists to enable reproducibility. * * @param <D> * @param data * @param seed * @param logger * @param portions * @return * @throws SplitFailedException * @throws InterruptedException */ public static <D extends IDataset<?>> List<D> createSplit(final D data, final long seed, final Logger logger, final double... pPortions) throws SplitFailedException, InterruptedException { double portionsSum = Arrays.stream(pPortions).sum(); if (portionsSum > 1) { throw new IllegalArgumentException("Sum of portions must not be greater than 1."); } final double[] portions; if (portionsSum < 1.0 - 1E-8) { portions = new double[pPortions.length + 1]; IntStream.range(0, pPortions.length).forEach(x -> portions[x] = pPortions[x]); portions[portions.length - 1] = 1.0 - portionsSum; } else { portions = pPortions; } logger.info("Creating new split with {} folds.", portions.length); List<D> folds = new ArrayList<>(portions.length); /* create sub-indices for the respective folds */ int totalItems = data.size(); try { D copy = (D) data.createCopy(); Collections.shuffle(copy, new Random(seed)); double remainingMass = 1; for (int numFold = 0; numFold < portions.length; numFold++) { double portion = numFold < portions.length ? portions[numFold] : remainingMass; remainingMass -= portion; if (remainingMass > 0) { SimpleRandomSampling<D> subSampler = new SimpleRandomSampling<>(new Random(seed), copy); int sampleSize = (int) Math.round(portion * totalItems); subSampler.setSampleSize(sampleSize); logger.debug("Computing fold of size {}/{}, i.e. a portion of {}", sampleSize, totalItems, portion); D fold = subSampler.call(); addReconstructionInfo(data, fold, seed, numFold, portions); folds.add(fold); copy = subSampler.getComplementOfLastSample(); logger.debug("Reduced the data by the fold. Remaining items: {}", copy.size()); } else { logger.debug("This is the last fold, which exhausts the complete original data, so no more sampling will be conducted."); folds.add(copy); addReconstructionInfo(data, copy, seed, numFold, portions); } } } catch (AlgorithmTimeoutedException | AlgorithmExecutionCanceledException | AlgorithmException | DatasetCreationException e) { throw new SplitFailedException(e); } if (folds.size() != portions.length) { throw new IllegalStateException("Needed to generate " + portions.length + " folds, but only produced " + folds.size()); } return folds; } private static void addReconstructionInfo(final IDataset<?> data, final IDataset<?> fold, final long seed, final int numFold, final double[] portions) { if (data instanceof IReconstructible && ReconstructionUtil.areInstructionsNonEmptyIfReconstructibilityClaimed(data)) { // make data reconstructible, but only if the given data is already reconstructible ((IReconstructible) data).getConstructionPlan().getInstructions().forEach(((IReconstructible) fold)::addInstruction); ((IReconstructible) fold).addInstruction( new ReconstructionInstruction(RandomHoldoutSplitter.class.getName(), "getFoldOfSplit", new Class<?>[] { IDataset.class, long.class, int.class, double[].class }, new Object[] { "this", seed, numFold, portions })); } } public static <D extends IDataset<?>> D getFoldOfSplit(final D data, final long seed, final int fold, final double... portions) throws SplitFailedException, InterruptedException { return createSplit(data, seed, portions).get(fold); } @Override public List<D> split(final D data, final Random random) throws SplitFailedException, InterruptedException { return createSplit(data, this.rand.nextLong(), this.logger, this.portions); } @Override public int getNumberOfFoldsPerSplit() { return this.portions.length; } @Override public int getNumSplitsPerSet() { return 1; } @Override public int getNumFoldsPerSplit() { return this.portions.length; } @Override public IDatasetSplitSet<D> nextSplitSet(final D data) throws InterruptedException, SplitFailedException { return new DatasetSplitSet<>(Arrays.asList(this.split(data))); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } @Override public String toString() { return "RandomHoldoutSplitter [rand=" + this.rand + ", portions=" + Arrays.toString(this.portions) + "]"; } @Override public List<D> split(final D data, final Random random, final double... relativeFoldSizes) throws SplitFailedException, InterruptedException { return createSplit(data, random.nextLong(), this.logger, relativeFoldSizes); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/splitter/ReproducibleSplit.java
package ai.libs.jaicore.ml.core.dataset.splitter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.common.reconstruction.IReconstructible; import org.api4.java.common.reconstruction.IReconstructionInstruction; import org.api4.java.common.reconstruction.IReconstructionPlan; import ai.libs.jaicore.basic.reconstruction.ReconstructionInstruction; import ai.libs.jaicore.basic.reconstruction.ReconstructionPlan; public class ReproducibleSplit<D extends IDataset<?>> extends ArrayList<D> implements IReconstructible { /** * */ private static final long serialVersionUID = 5080066497964848476L; private final ReconstructionPlan reproductionPlan; public ReproducibleSplit(final ReconstructionInstruction creationInstruction, final D dataset, final D...folds) { if (!(dataset instanceof IReconstructible)) { throw new IllegalArgumentException("The given dataset itself is not reconstructible."); } Collections.addAll(this, folds); List<ReconstructionInstruction> instructions = new ArrayList<>(); ((IReconstructible)dataset).getConstructionPlan().getInstructions().forEach(i -> instructions.add((ReconstructionInstruction)i)); instructions.add(creationInstruction); this.reproductionPlan = new ReconstructionPlan(instructions); } @Override public IReconstructionPlan getConstructionPlan() { return this.reproductionPlan; } @Override public void addInstruction(final IReconstructionInstruction instruction) { throw new UnsupportedOperationException(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.reproductionPlan == null) ? 0 : this.reproductionPlan.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } ReproducibleSplit other = (ReproducibleSplit) obj; if (this.reproductionPlan == null) { if (other.reproductionPlan != null) { return false; } } else if (!this.reproductionPlan.equals(other.reproductionPlan)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/splitter/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.core.dataset.splitter;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/util/LatexDatasetTableGenerator.java
package ai.libs.jaicore.ml.core.dataset.util; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.api4.java.ai.ml.core.dataset.schema.attribute.ICategoricalAttribute; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.openml.apiconnector.io.OpenmlConnector; import org.openml.apiconnector.xml.DataSetDescription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.ml.core.dataset.serialization.ArffDatasetAdapter; public class LatexDatasetTableGenerator { private static final Logger logger = LoggerFactory.getLogger(LatexDatasetTableGenerator.class); private final List<File> datasets = new ArrayList<>(); private int numMajorColumns = 1; private String caption = "Dataset overview"; private String label = "tab:datasets"; @SuppressWarnings("serial") public class DataSourceCreationFailedException extends Exception { public DataSourceCreationFailedException(final Exception e) { super(e); } } public void addLocalFiles(final File... files) throws DataSourceCreationFailedException { this.addLocalFiles(Arrays.asList(files)); } public void addLocalFiles(final List<File> files) throws DataSourceCreationFailedException { for (File file : files) { try { this.datasets.add(file); } catch (Exception e) { throw new DataSourceCreationFailedException(e); } } } public void addOpenMLDatasets(final int... datasetIds) throws Exception { OpenmlConnector client = new OpenmlConnector(); for (int id : datasetIds) { DataSetDescription description = client.dataGet(id); File file = client.datasetGet(description); this.datasets.add(file); } } public List<File> getDatasets() { return this.datasets; } public int getNumMajorColumns() { return this.numMajorColumns; } public void setNumMajorColumns(final int numMajorColumns) { this.numMajorColumns = numMajorColumns; } public String getCaption() { return this.caption; } public void setCaption(final String caption) { this.caption = caption; } public String getLabel() { return this.label; } public void setLabel(final String label) { this.label = label; } public String getLatexCode() { StringBuilder sb = new StringBuilder(); /* create header */ sb.append("\\begin{table}\r\n"); sb.append(" \\begin{center}\r\n"); sb.append(" \\begin{tabular}{lrrr"); for (int i = 1; i < this.numMajorColumns; i++) { sb.append("l|llrrr"); } sb.append("}\r\n "); for (int i = 0; i < this.numMajorColumns; i++) { if (i > 0) { sb.append("& ~ & ~ &"); // have an empty field to get some spacing } sb.append("Dataset & \\#Inst.& \\#Attr. & \\#Cl."); } sb.append("\\\\\\hline\r\n"); /* create row content */ int rows = (int) Math.ceil(this.datasets.size() * 1f / this.numMajorColumns); int k = 0; for (int i = 0; i < rows && k < this.datasets.size(); i++) { sb.append(" "); for (int j = 0; j < this.numMajorColumns && k < this.datasets.size(); j++, k++) { File source = this.datasets.get(k); String datasetName = source.toString(); String numInstances = "?"; String numAttributes = "?"; String numClasses = "?"; try { ILabeledDataset<ILabeledInstance> inst = new ArffDatasetAdapter().readDataset(source); datasetName = inst.getRelationName().replaceAll("(&|_)", ""); numInstances = String.valueOf(inst.size()); numAttributes = String.valueOf(inst.getNumAttributes() - 1); if (inst.getInstanceSchema().getLabelAttribute() instanceof ICategoricalAttribute) { numClasses = String.valueOf(((ICategoricalAttribute) inst.getInstanceSchema().getLabelAttribute()).getLabels().size()); } else { numClasses = "inf"; } } catch (Exception e) { logger.error("Could not read dataset from source {}", source); } if (j > 0) { sb.append("& & &"); } sb.append(datasetName); sb.append(" & "); sb.append(numInstances); sb.append(" & "); sb.append(numAttributes); sb.append(" & "); sb.append(numClasses); } sb.append("\\\\\r\n"); } sb.append(" \\end{tabular}\r\n"); sb.append(" \\end{center}\r\n"); sb.append(" \\caption{"); sb.append(this.caption); sb.append("}\r\n \\label{"); sb.append(this.label); sb.append("}\r\n\\end{table}"); return sb.toString(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/dataset/util/package-info.java
package ai.libs.jaicore.ml.core.dataset.util;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/AggregatingPredictionPerformanceMeasure.java
package ai.libs.jaicore.ml.core.evaluation; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.api4.java.ai.ml.core.evaluation.IPredictionAndGroundTruthTable; import org.api4.java.ai.ml.core.evaluation.execution.IAggregatedPredictionPerformanceMeasure; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; import org.api4.java.common.aggregate.IRealsAggregateFunction; public class AggregatingPredictionPerformanceMeasure<E, A> implements IAggregatedPredictionPerformanceMeasure<E, A> { private final IRealsAggregateFunction aggregator; private final IDeterministicPredictionPerformanceMeasure<E, A> baseMeasure; public AggregatingPredictionPerformanceMeasure(final IRealsAggregateFunction aggregator, final IDeterministicPredictionPerformanceMeasure<E, A> baseMeasure) { super(); this.aggregator = aggregator; this.baseMeasure = baseMeasure; } @Override public double loss(final List<List<? extends E>> expected, final List<List<? extends A>> actual) { int n = expected.size(); List<Double> losses = new ArrayList<>(); for (int i = 0; i < n; i++) { losses.add(this.baseMeasure.loss(expected.get(i), actual.get(i))); } return this.aggregator.aggregate(losses); } @Override public double loss(final List<IPredictionAndGroundTruthTable<? extends E, ? extends A>> pairTables) { List<List<? extends E>> expected = pairTables.stream().map(IPredictionAndGroundTruthTable::getGroundTruthAsList).collect(Collectors.toList()); List<List<? extends A>> predicted = pairTables.stream().map(IPredictionAndGroundTruthTable::getPredictionsAsList).collect(Collectors.toList()); return this.loss(expected, predicted); } @Override public double score(final List<List<? extends E>> expected, final List<List<? extends A>> actual) { return 1 - this.loss(expected, actual); } @Override public double score(final List<IPredictionAndGroundTruthTable<? extends E, ? extends A>> pairTables) { return 1 - this.loss(pairTables); } @Override public IDeterministicPredictionPerformanceMeasure<E, A> getBaseMeasure() { return this.baseMeasure; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/AveragingPredictionPerformanceMeasure.java
package ai.libs.jaicore.ml.core.evaluation; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; import ai.libs.jaicore.basic.aggregate.reals.Mean; public class AveragingPredictionPerformanceMeasure<E, A> extends AggregatingPredictionPerformanceMeasure<E, A> { private static final Mean MEAN = new Mean(); public AveragingPredictionPerformanceMeasure(final IDeterministicPredictionPerformanceMeasure<E, A> baseMeasure) { super(MEAN, baseMeasure); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/IGeneralPredictionAndGroundTruthTable.java
package ai.libs.jaicore.ml.core.evaluation; import org.api4.java.ai.ml.core.evaluation.IPredictionAndGroundTruthTable; public interface IGeneralPredictionAndGroundTruthTable extends IPredictionAndGroundTruthTable<Object, Object> { }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/MLEvaluationUtil.java
package ai.libs.jaicore.ml.core.evaluation; import java.util.Random; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.ISupervisedLearnerEvaluator; import org.api4.java.ai.ml.core.evaluation.execution.ILearnerRunReport; import org.api4.java.ai.ml.core.evaluation.execution.LearnerExecutionFailedException; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import ai.libs.jaicore.ml.classification.loss.dataset.EAggregatedClassifierMetric; import ai.libs.jaicore.ml.core.evaluation.evaluator.MonteCarloCrossValidationEvaluator; import ai.libs.jaicore.ml.core.evaluation.evaluator.SupervisedLearnerExecutor; public class MLEvaluationUtil { private MLEvaluationUtil() { /* avoids instantiation */ } public static double evaluate(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> learner, final ISupervisedLearnerEvaluator<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> evaluator) throws ObjectEvaluationFailedException, InterruptedException { return evaluator.evaluate(learner); } public static double getLossForTrainedClassifier(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> learner, final ILabeledDataset<? extends ILabeledInstance> testData, final IDeterministicPredictionPerformanceMeasure<Integer, ISingleLabelClassification> measure) throws LearnerExecutionFailedException { SupervisedLearnerExecutor executor = new SupervisedLearnerExecutor(); ILearnerRunReport report = executor.execute(learner, testData); return measure.loss(report.getPredictionDiffList().getCastedView(Integer.class, ISingleLabelClassification.class)); } public static double mccv(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> learner, final ILabeledDataset<? extends ILabeledInstance> data, final int repeats, final double trainFoldSize, final long seed, final EAggregatedClassifierMetric metric) throws ObjectEvaluationFailedException, InterruptedException { return evaluate(learner, new MonteCarloCrossValidationEvaluator(false, data, repeats, trainFoldSize, new Random(seed), metric)); } public static double mccv(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> learner, final ILabeledDataset<? extends ILabeledInstance> data, final int repeats, final double trainFoldSize, final long seed) throws ObjectEvaluationFailedException, InterruptedException { return mccv(learner, data, repeats, trainFoldSize, seed, EAggregatedClassifierMetric.MEAN_ERRORRATE); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/Prediction.java
package ai.libs.jaicore.ml.core.evaluation; import java.util.Map; import org.api4.java.ai.ml.core.evaluation.IPrediction; public class Prediction implements IPrediction { private final Object predicted; private static final String MSG_NOSUPPORT = "Dumb jaicore-ml prediction objects don't support probabilistic predictions yet."; public Prediction(final Object predicted) { this.predicted = predicted; } @Override public Object getPrediction() { return this.predicted; } @Override public Object getLabelWithHighestProbability() { throw new UnsupportedOperationException(MSG_NOSUPPORT); } @Override public Map<?, Double> getClassDistribution() { throw new UnsupportedOperationException(MSG_NOSUPPORT); } @Override public Map<?, Double> getClassConfidence() { throw new UnsupportedOperationException(MSG_NOSUPPORT); } @Override public double getProbabilityOfLabel(final Object label) { throw new UnsupportedOperationException(MSG_NOSUPPORT); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/PredictionBatch.java
package ai.libs.jaicore.ml.core.evaluation; import java.util.Arrays; import java.util.List; import org.api4.java.ai.ml.core.evaluation.IPrediction; import org.api4.java.ai.ml.core.evaluation.IPredictionBatch; public class PredictionBatch implements IPredictionBatch { private final List<? extends IPrediction> predictions; public PredictionBatch(final List<? extends IPrediction> predictions) { super(); this.predictions = predictions; } public <I extends IPrediction> PredictionBatch(final I[] predictions) { super(); this.predictions = Arrays.asList(predictions); } @Override public List<? extends IPrediction> getPredictions() { return this.predictions; } @Override public int getNumPredictions() { return this.predictions.size(); } @Override public IPrediction get(final int index) { return this.predictions.get(index); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/SingleEvaluationAggregatedMeasure.java
package ai.libs.jaicore.ml.core.evaluation; import java.util.List; import org.api4.java.ai.ml.core.evaluation.IPredictionAndGroundTruthTable; import org.api4.java.ai.ml.core.evaluation.execution.IAggregatedPredictionPerformanceMeasure; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; public class SingleEvaluationAggregatedMeasure<E, A> implements IAggregatedPredictionPerformanceMeasure<E, A> { private final IDeterministicPredictionPerformanceMeasure<E, A> lossFunction; public SingleEvaluationAggregatedMeasure(final IDeterministicPredictionPerformanceMeasure<E, A> lossFunction) { super(); this.lossFunction = lossFunction; } @Override public double loss(final List<List<? extends E>> expected, final List<List<? extends A>> actual) { if (expected.size() != 1) { throw new IllegalArgumentException(); } return this.lossFunction.loss(expected.get(0), actual.get(0)); } @Override public double loss(final List<IPredictionAndGroundTruthTable<? extends E, ? extends A>> pairTables) { if (pairTables.size() != 1) { throw new IllegalArgumentException(); } return this.lossFunction.loss(pairTables.get(0)); } @Override public double score(final List<List<? extends E>> expected, final List<List<? extends A>> actual) { return 1 - this.loss(expected, actual); } @Override public double score(final List<IPredictionAndGroundTruthTable<? extends E, ? extends A>> pairTables) { return 1 - this.loss(pairTables); } @Override public IDeterministicPredictionPerformanceMeasure<E, A> getBaseMeasure() { return this.lossFunction; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.core.evaluation;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/ConfigurationLearningCurveExtrapolationEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.ISupervisedLearnerEvaluator; import org.api4.java.ai.ml.core.evaluation.learningcurve.ILearningCurve; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.ASamplingAlgorithm; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.factories.interfaces.ISamplingAlgorithmFactory; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.ConfigurationLearningCurveExtrapolator; /** * Predicts the accuracy of a classifier with certain configurations on a point * of its learning curve, given some anchorpoint and its configurations using * the LCNet of pybnn * * Note: This code was copied from LearningCurveExtrapolationEvaluator and * slightly reworked * * @author noni4 */ public class ConfigurationLearningCurveExtrapolationEvaluator implements ISupervisedLearnerEvaluator<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> { private Logger logger = LoggerFactory.getLogger(ConfigurationLearningCurveExtrapolationEvaluator.class); // Configuration for the learning curve extrapolator. private int[] anchorpoints; private ISamplingAlgorithmFactory<ILabeledDataset<?>, ASamplingAlgorithm<ILabeledDataset<?>>> samplingAlgorithmFactory; private ILabeledDataset<?> dataset; private double trainSplitForAnchorpointsMeasurement; private long seed; private String identifier; private double[] configurations; private int fullDatasetSize = -1; public ConfigurationLearningCurveExtrapolationEvaluator(final int[] anchorpoints, final ISamplingAlgorithmFactory<ILabeledDataset<?>, ASamplingAlgorithm<ILabeledDataset<?>>> samplingAlgorithmFactory, final ILabeledDataset<?> dataset, final double trainSplitForAnchorpointsMeasurement, final long seed, final String identifier, final double[] configurations) { super(); this.anchorpoints = anchorpoints; this.samplingAlgorithmFactory = samplingAlgorithmFactory; this.dataset = dataset; this.trainSplitForAnchorpointsMeasurement = trainSplitForAnchorpointsMeasurement; this.seed = seed; this.identifier = identifier; this.configurations = configurations; } public void setFullDatasetSize(final int fullDatasetSize) { this.fullDatasetSize = fullDatasetSize; } @Override public Double evaluate(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> classifier) throws InterruptedException, ObjectEvaluationFailedException { // Create the learning curve extrapolator with the given configuration. try { ConfigurationLearningCurveExtrapolator extrapolator = new ConfigurationLearningCurveExtrapolator(classifier, this.dataset, this.trainSplitForAnchorpointsMeasurement, this.anchorpoints, this.samplingAlgorithmFactory, this.seed, this.identifier, this.configurations); // Create the extrapolator and calculate the accuracy the classifier would have // if it was trained on the complete dataset. ILearningCurve learningCurve = extrapolator.extrapolateLearningCurve(); int evaluationPoint = this.dataset.size(); // Overwrite evaluation point if a value was provided, otherwise evaluate on the // size of the given dataset if (this.fullDatasetSize != -1) { evaluationPoint = this.fullDatasetSize; } return learningCurve.getCurveValue(evaluationPoint) * 100.0d; } catch (InterruptedException e) { throw e; } catch (Exception e) { this.logger.warn("Evaluation of classifier failed due Exception {} with message {}. Returning null.", e.getClass().getName(), e.getMessage()); return null; } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/ExtrapolatedSaturationPointEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.util.Random; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.ISupervisedLearnerEvaluator; import org.api4.java.ai.ml.core.evaluation.learningcurve.IAnalyticalLearningCurve; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; import org.api4.java.ai.ml.core.exception.DatasetCreationException; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.ASamplingAlgorithm; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.factories.interfaces.ISamplingAlgorithmFactory; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.InvalidAnchorPointsException; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.LearningCurveExtrapolationMethod; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.LearningCurveExtrapolator; /** * For the classifier a learning curve will be extrapolated with a given set of * anchorpoints. This learning curve can predict a saturation point with a * tolerance epsilon. When a subsample is drawn at this saturation point it is * the optimal trade-off between a fast training (therefore fast classifier * evaluation) and dataset representability (therefore evaluation result * expressiveness). * * @author Lukas Brandt */ public class ExtrapolatedSaturationPointEvaluator implements ISupervisedLearnerEvaluator<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> { private static final Logger logger = LoggerFactory.getLogger(ExtrapolatedSaturationPointEvaluator.class); private static final double DEFAULT_EPSILON = 0.1; // Configuration for the learning curve extrapolator. private int[] anchorpoints; private ISamplingAlgorithmFactory<ILabeledDataset<?>, ? extends ASamplingAlgorithm<ILabeledDataset<?>>> samplingAlgorithmFactory; private ILabeledDataset<?> train; private double trainSplitForAnchorpointsMeasurement; private LearningCurveExtrapolationMethod extrapolationMethod; private long seed; // Configuration for the measurement at the saturation point. private double epsilon; private ILabeledDataset<?> test; private IDeterministicPredictionPerformanceMeasure<?, ?> measure; /** * Create a classifier evaluator with an accuracy measurement at the * extrapolated learning curves saturation point. * * @param anchorpoints * Anchorpoints for the learning curve extrapolation. * @param samplingAlgorithmFactory * Subsampling factory for a subsampler to create samples at the * given anchorpoints. * @param train * Dataset predict the learning curve with and where the subsample * for the measurement is drawn from. * @param trainSplitForAnchorpointsMeasurement * Ratio to split the subsamples at the anchorpoints into train and * test. * @param extrapolationMethod * Method to extrapolate a learning curve from the accuracy * measurements at the anchorpoints. * @param seed * Random seed. * @param test * Test dataset to measure the accuracy. */ public ExtrapolatedSaturationPointEvaluator(final int[] anchorpoints, final ISamplingAlgorithmFactory<ILabeledDataset<?>, ? extends ASamplingAlgorithm<ILabeledDataset<?>>> samplingAlgorithmFactory, final ILabeledDataset<?> train, final double trainSplitForAnchorpointsMeasurement, final LearningCurveExtrapolationMethod extrapolationMethod, final long seed, final ILabeledDataset<?> test, final IDeterministicPredictionPerformanceMeasure<?, ?> measure) { super(); this.anchorpoints = anchorpoints; this.samplingAlgorithmFactory = samplingAlgorithmFactory; this.train = train; this.trainSplitForAnchorpointsMeasurement = trainSplitForAnchorpointsMeasurement; this.extrapolationMethod = extrapolationMethod; this.seed = seed; this.epsilon = DEFAULT_EPSILON; this.test = test; this.measure = measure; } public void setEpsilon(final double epsilon) { this.epsilon = epsilon; } @Override public Double evaluate(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> learner) throws InterruptedException, ObjectEvaluationFailedException { // Create the learning curve extrapolator with the given configuration. try { LearningCurveExtrapolator extrapolator = new LearningCurveExtrapolator(this.extrapolationMethod, learner, this.train, this.trainSplitForAnchorpointsMeasurement, this.anchorpoints, this.samplingAlgorithmFactory, this.seed); // Create the extrapolator and calculate sample size of the saturation point // with the given epsilon IAnalyticalLearningCurve learningCurve = (IAnalyticalLearningCurve) extrapolator.extrapolateLearningCurve(); int optimalSampleSize = Math.min(this.train.size(), (int) learningCurve.getSaturationPoint(this.epsilon)); // Create a subsample with this size ASamplingAlgorithm<ILabeledDataset<?>> samplingAlgorithm = this.samplingAlgorithmFactory.getAlgorithm(optimalSampleSize, this.train, new Random(this.seed)); ILabeledDataset<?> saturationPointTrainSet = samplingAlgorithm.call(); // Measure the accuracy with this subsample FixedSplitClassifierEvaluator evaluator = new FixedSplitClassifierEvaluator(saturationPointTrainSet, this.test, this.measure); return evaluator.evaluate(learner); } catch (AlgorithmException | InvalidAnchorPointsException | AlgorithmExecutionCanceledException | DatasetCreationException | AlgorithmTimeoutedException e) { logger.warn("Evaluation of classifier failed due Exception {} with message {}. Returning null.", e.getClass().getName(), e.getMessage()); return null; } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/FixedSplitClassifierEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.util.Arrays; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; import ai.libs.jaicore.ml.core.dataset.splitter.DatasetSplitSet; import ai.libs.jaicore.ml.core.evaluation.SingleEvaluationAggregatedMeasure; import ai.libs.jaicore.ml.core.evaluation.splitsetgenerator.ConstantSplitSetGenerator; public class FixedSplitClassifierEvaluator extends TrainPredictionBasedClassifierEvaluator { public FixedSplitClassifierEvaluator(final ILabeledDataset<? extends ILabeledInstance> train, final ILabeledDataset<? extends ILabeledInstance> validate, final IDeterministicPredictionPerformanceMeasure<?, ?> lossFunction) { super(new ConstantSplitSetGenerator<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>>(new DatasetSplitSet<ILabeledDataset<? extends ILabeledInstance>>(Arrays.asList(Arrays.asList(train, validate)))), new SingleEvaluationAggregatedMeasure(lossFunction)); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/IMultiFidelityObjectEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import org.api4.java.common.attributedobjects.IObjectEvaluator; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; /** * A multi-fidelity object evaluator allows for specifying a certain amount of an evaluation resource. * * @author mwever * * @param <T> The type of object to be evaluated. * @param <V> The comparable evaluation value. */ public interface IMultiFidelityObjectEvaluator<T, V extends Comparable<V>> extends IObjectEvaluator<T, V> { /** * @return The maximum allocable budget. */ public double getMaxBudget(); /** * @return The minimum allocable budget. */ public double getMinBudget(); /** * Evaluate the object t with the specified budget. * * @param t The object to be evaluated. * @param budget The budget assigned for the evaluation of t. * @return The evaluation score for the object t. * @throws InterruptedException Thrown if the evaluation routine is interrupted. * @throws ObjectEvaluationFailedException Thrown, if the object t cannot be successfully evaluated. */ public V evaluate(T t, double budget) throws InterruptedException, ObjectEvaluationFailedException; @Override default V evaluate(final T t) throws InterruptedException, ObjectEvaluationFailedException { // Whenever no budget is specified, evaluated with the maximum budget. return this.evaluate(t, this.getMaxBudget()); } /** * Evaluate the object t with minimal resources. * @param t The object to be evaluated. * @return The evaluation score for the object t. * @throws InterruptedException Thrown, if the evaluation routine is interrupted. * @throws ObjectEvaluationFailedException Thrown, if the object t cannot be successfully evaluated. */ default V evaluateMinimal(final T t) throws InterruptedException, ObjectEvaluationFailedException { return this.evaluate(t, this.getMinBudget()); } /** * Evaluate the object t with maximal resources. * @param t The object to be evaluated. * @return The evaluation score for the object t. * @throws InterruptedException Thrown, if the evaluation routine is interrupted. * @throws ObjectEvaluationFailedException Thrown, if the object t cannot be successfully evaluated. */ default V evaluateMaximal(final T t) throws InterruptedException, ObjectEvaluationFailedException { return this.evaluate(t, this.getMaxBudget()); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/LearnerRunReport.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.util.HashMap; import java.util.Map; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.evaluation.IPredictionAndGroundTruthTable; import org.api4.java.ai.ml.core.evaluation.execution.ILearnerRunReport; import ai.libs.jaicore.logging.ToJSONStringUtil; public class LearnerRunReport implements ILearnerRunReport { private final ILabeledDataset<?> trainSet; private final ILabeledDataset<?> testSet; private final long trainStartTime; private final long trainEndTime; private final long testStartTime; private final long testEndTime; private final Throwable exception; private final IPredictionAndGroundTruthTable<?, ?> diff; public LearnerRunReport(final ILabeledDataset<?> trainSet, final ILabeledDataset<?> testSet, final long trainStartTime, final long trainEndTime, final Throwable exception) { super(); this.trainSet = trainSet; this.testSet = testSet; this.trainStartTime = trainStartTime; this.trainEndTime = trainEndTime; this.testStartTime = -1; this.testEndTime = -1; this.diff = null; this.exception = exception; } public LearnerRunReport(final ILabeledDataset<?> trainSet, final ILabeledDataset<?> testSet, final long trainStartTime, final long trainEndTime, final long testStartTime, final long testEndTime, final Throwable exception) { super(); this.trainSet = trainSet; this.testSet = testSet; this.trainStartTime = trainStartTime; this.trainEndTime = trainEndTime; this.testStartTime = testStartTime; this.testEndTime = testEndTime; this.diff = null; this.exception = exception; } public LearnerRunReport(final ILabeledDataset<?> trainSet, final ILabeledDataset<?> testSet, final long trainStartTime, final long trainEndTime, final long testStartTime, final long testEndTime, final IPredictionAndGroundTruthTable<?, ?> diff) { super(); this.trainSet = trainSet; this.testSet = testSet; this.trainStartTime = trainStartTime; this.trainEndTime = trainEndTime; this.testStartTime = testStartTime; this.testEndTime = testEndTime; this.diff = diff; this.exception = null; } @Override public long getTrainStartTime() { return this.trainStartTime; } @Override public long getTrainEndTime() { return this.trainEndTime; } @Override public long getTestStartTime() { return this.testStartTime; } @Override public long getTestEndTime() { return this.testEndTime; } @Override public ILabeledDataset<?> getTrainSet() { return this.trainSet; } @Override public ILabeledDataset<?> getTestSet() { return this.testSet; } @Override public IPredictionAndGroundTruthTable<?, ?> getPredictionDiffList() { return this.diff; } @Override public Throwable getException() { return this.exception; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("trainStartTime", this.trainStartTime); fields.put("trainEndTime", this.trainEndTime); fields.put("testStartTime", this.testStartTime); fields.put("testEndTime", this.testEndTime); fields.put("exception", this.exception); if (this.diff != null) { fields.put("diffClass", this.diff.getClass().getName()); } return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/LearningCurveExtrapolationEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import org.api4.java.ai.ml.classification.IClassifierEvaluator; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.learningcurve.ILearningCurve; import org.api4.java.ai.ml.core.exception.DatasetCreationException; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.common.event.IEventEmitter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.ASamplingAlgorithm; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.factories.interfaces.ISamplingAlgorithmFactory; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.InvalidAnchorPointsException; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.LearningCurveExtrapolatedEvent; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.LearningCurveExtrapolationMethod; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.LearningCurveExtrapolator; /** * Evaluates a classifier by predicting its learning curve with a few * anchorpoints. The evaluation result is the accuracy or the error rate (configurable) for the * complete dataset. Depending on the chosen anchorpoints this evaluation method * will be really fast, but can be inaccurate depending on the learning curve * extrapolation method, since it will only give a prediction of the accuracy * and does not measure it. * * @author Lukas Brandt */ public class LearningCurveExtrapolationEvaluator implements IClassifierEvaluator, ILoggingCustomizable, IEventEmitter<Object> { private Logger logger = LoggerFactory.getLogger(LearningCurveExtrapolationEvaluator.class); // Configuration for the learning curve extrapolator. private int[] anchorpoints; private ISamplingAlgorithmFactory<ILabeledDataset<?>, ? extends ASamplingAlgorithm<ILabeledDataset<?>>> samplingAlgorithmFactory; private ILabeledDataset<?> dataset; private double trainSplitForAnchorpointsMeasurement; private LearningCurveExtrapolationMethod extrapolationMethod; private long seed; private int fullDatasetSize = -1; private static final boolean EVALUATE_ACCURACY = false; // otherwise error rate private final EventBus eventBus = new EventBus(); /** * Create a classifier evaluator with learning curve extrapolation. * * @param anchorpoints Anchorpoints for the learning * curve extrapolation. * @param samplingAlgorithmFactory Subsampling factory to create a * subsampler for the samples at the given anchorpoints. * @param dataset Dataset to evaluate the classifier with. * @param trainSplitForAnchorpointsMeasurement Ratio to split the subsamples at * the anchorpoints into train and test. * @param extrapolationMethod Method to extrapolate a learning * curve from the accuracy * measurements at the anchorpoints. * @param seed Random seed. */ public LearningCurveExtrapolationEvaluator(final int[] anchorpoints, final ISamplingAlgorithmFactory<ILabeledDataset<?>, ? extends ASamplingAlgorithm<ILabeledDataset<?>>> samplingAlgorithmFactory, final ILabeledDataset<?> dataset, final double trainSplitForAnchorpointsMeasurement, final LearningCurveExtrapolationMethod extrapolationMethod, final long seed) { super(); this.anchorpoints = anchorpoints; this.samplingAlgorithmFactory = samplingAlgorithmFactory; this.dataset = dataset; this.trainSplitForAnchorpointsMeasurement = trainSplitForAnchorpointsMeasurement; this.extrapolationMethod = extrapolationMethod; this.seed = seed; } public void setFullDatasetSize(final int fullDatasetSize) { this.fullDatasetSize = fullDatasetSize; } /** * Computes the (estimated) measure of the classifier on the full dataset */ @Override public Double evaluate(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> classifier) throws InterruptedException, ObjectEvaluationFailedException { // Create the learning curve extrapolator with the given configuration. this.logger.info("Receive request to evaluate classifier {}", classifier); try { LearningCurveExtrapolator extrapolator = new LearningCurveExtrapolator(this.extrapolationMethod, classifier, this.dataset, this.trainSplitForAnchorpointsMeasurement, this.anchorpoints, this.samplingAlgorithmFactory, this.seed); extrapolator.setLoggerName(this.getLoggerName() + ".extrapolator"); /* Create the extrapolator and calculate the accuracy the classifier would have if it was trained on the complete dataset. */ this.logger.debug("Extrapolating learning curve."); ILearningCurve learningCurve = extrapolator.extrapolateLearningCurve(); this.logger.debug("Retrieved learning curve {}.", learningCurve); this.eventBus.post(new LearningCurveExtrapolatedEvent(extrapolator)); int evaluationPoint = this.dataset.size(); /* Overwrite evaluation point if a value was provided, otherwise evaluate on the size of the given dataset */ if (this.fullDatasetSize != -1) { evaluationPoint = this.fullDatasetSize; } Double val = EVALUATE_ACCURACY ? learningCurve.getCurveValue(evaluationPoint) : 1 - learningCurve.getCurveValue(evaluationPoint); this.logger.info("Estimate for performance on full dataset is {}", val); return val; } catch (AlgorithmException | InvalidAnchorPointsException | DatasetCreationException e) { throw new ObjectEvaluationFailedException("Could not compute a score based on the learning curve.", e); } } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } /** * Register observers for learning curve predictions (including estimates of the time) * * @param listener */ @Override public void registerListener(final Object listener) { this.eventBus.register(listener); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/MonteCarloCrossValidationEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.util.Random; import org.api4.java.ai.ml.core.dataset.splitter.IRandomDatasetSplitter; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.execution.IAggregatedPredictionPerformanceMeasure; import ai.libs.jaicore.ml.classification.loss.dataset.EAggregatedClassifierMetric; import ai.libs.jaicore.ml.core.dataset.splitter.RandomHoldoutSplitter; import ai.libs.jaicore.ml.core.evaluation.splitsetgenerator.CachingMonteCarloCrossValidationSplitSetGenerator; import ai.libs.jaicore.ml.core.evaluation.splitsetgenerator.FixedDataSplitSetGenerator; import ai.libs.jaicore.ml.core.evaluation.splitsetgenerator.MonteCarloCrossValidationSplitSetGenerator; public class MonteCarloCrossValidationEvaluator extends TrainPredictionBasedClassifierEvaluator { private final IRandomDatasetSplitter<ILabeledDataset<? extends ILabeledInstance>> datasetSplitter; private final int repeats; private final Random random; public MonteCarloCrossValidationEvaluator(final ILabeledDataset<? extends ILabeledInstance> data, final int repeats, final double trainingPortion, final Random random) { this(false, data, new RandomHoldoutSplitter<>(trainingPortion), repeats, random, EAggregatedClassifierMetric.MEAN_ERRORRATE); } public MonteCarloCrossValidationEvaluator(final boolean cacheSplitSets, final ILabeledDataset<? extends ILabeledInstance> data, final int repeats, final double trainingPortion, final Random random, final IAggregatedPredictionPerformanceMeasure<?, ?> metric) { this(cacheSplitSets, data, new RandomHoldoutSplitter<>(trainingPortion), repeats, random, metric); } public MonteCarloCrossValidationEvaluator(final boolean cacheSplitSets, final ILabeledDataset<? extends ILabeledInstance> data, final IRandomDatasetSplitter<ILabeledDataset<? extends ILabeledInstance>> datasetSplitter, final int repeats, final Random random, final IAggregatedPredictionPerformanceMeasure<?, ?> metric) { super(new FixedDataSplitSetGenerator<ILabeledDataset<? extends ILabeledInstance>>(data, (cacheSplitSets ? new CachingMonteCarloCrossValidationSplitSetGenerator<>(datasetSplitter, repeats, random) : new MonteCarloCrossValidationSplitSetGenerator<>(datasetSplitter, repeats, random))), metric); this.datasetSplitter = datasetSplitter; this.repeats = repeats; this.random = random; } public int getRepeats() { return this.repeats; } @Override public String toString() { return "MonteCarloCrossValidationEvaluator [splitter = " + this.datasetSplitter + ", repeats = " + this.repeats + ", Random = " + this.random + ", metric = " + this.getMetric().getBaseMeasure() + "]"; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/PreTrainedPredictionBasedClassifierEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import org.api4.java.ai.ml.classification.IClassifierEvaluator; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.execution.LearnerExecutionFailedException; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; /** * This evaluator can be used to compute the performance of a pre-trained classifier on a given validation dataset * * @author Felix Mohr * */ public class PreTrainedPredictionBasedClassifierEvaluator implements IClassifierEvaluator { private final ILabeledDataset<?> testData; private final SupervisedLearnerExecutor executor = new SupervisedLearnerExecutor(); private final IDeterministicPredictionPerformanceMeasure<Object, Object> metric; public PreTrainedPredictionBasedClassifierEvaluator(final ILabeledDataset<?> testData, final IDeterministicPredictionPerformanceMeasure metric) { super(); this.testData = testData; this.metric = metric; } @Override public Double evaluate(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> learner) throws InterruptedException, ObjectEvaluationFailedException { try { return this.metric.loss(this.executor.execute(learner, this.testData).getPredictionDiffList()); } catch (LearnerExecutionFailedException e) { throw new ObjectEvaluationFailedException(e); } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/PredictionDiff.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.lang.reflect.Array; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.api4.java.ai.ml.core.evaluation.IPredictionAndGroundTruthTable; import ai.libs.jaicore.basic.sets.ListView; public class PredictionDiff<E, A> implements IPredictionAndGroundTruthTable<E, A> { private final Class<?> expectedClass; private final Class<?> predictionClass; private final List<E> groundTruths = new ArrayList<>(); private final List<A> predictions = new ArrayList<>(); public PredictionDiff() { super(); Type genericSuperClass = this.getClass().getGenericSuperclass(); this.expectedClass = (genericSuperClass instanceof ParameterizedType) ? (Class<E>)((ParameterizedType)genericSuperClass).getActualTypeArguments()[0].getClass() : Object.class; this.predictionClass = (genericSuperClass instanceof ParameterizedType) ? (Class<A>)((ParameterizedType)genericSuperClass).getActualTypeArguments()[1].getClass() : Object.class; } public PredictionDiff(final List<? extends E> groundTruths, final List<? extends A> predictions) { this(); if (predictions.size() != groundTruths.size()) { throw new IllegalArgumentException("Predictions and ground truths must have the same length!"); } this.predictions.addAll(predictions); this.groundTruths.addAll(groundTruths); } public void addPair(final E groundTruth, final A prediction) { this.groundTruths.add(groundTruth); this.predictions.add(prediction); } @Override public <E1, A1> PredictionDiff<E1, A1> getCastedView(final Class<E1> expectedClass, final Class<A1> actualClass) { return new PredictionDiff<>(new ListView<E1>(this.groundTruths), new ListView<A1>(this.predictions)); } @Override public int size() { return this.predictions.size(); } @Override public A getPrediction(final int instance) { return this.predictions.get(instance); } @Override public E getGroundTruth(final int instance) { return this.groundTruths.get(instance); } @Override public List<A> getPredictionsAsList() { return Collections.unmodifiableList(this.predictions); } public <T> List<T> getPredictionsAsList(final Class<T> clazz) { return Collections.unmodifiableList(new ListView<T>(this.predictions, clazz)); } @Override public A[] getPredictionsAsArray() { return this.predictions.toArray((A[])Array.newInstance(this.predictionClass, this.predictions.size())); } @Override public List<E> getGroundTruthAsList() { return Collections.unmodifiableList(this.groundTruths); } public <T> List<T> getGroundTruthAsList(final Class<T> clazz) { return Collections.unmodifiableList(new ListView<T>(this.groundTruths, clazz)); } @Override public E[] getGroundTruthAsArray() { return this.groundTruths.toArray((E[])Array.newInstance(this.expectedClass, this.groundTruths.size())); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/SingleRandomSplitClassifierEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.util.Random; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; public class SingleRandomSplitClassifierEvaluator extends MonteCarloCrossValidationEvaluator { public SingleRandomSplitClassifierEvaluator(final ILabeledDataset<?> data, final double trainingPortion, final Random random) { super(data, 1, trainingPortion, random); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/SupervisedLearnerExecutor.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.util.List; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.IPrediction; import org.api4.java.ai.ml.core.evaluation.execution.ILearnerRunReport; import org.api4.java.ai.ml.core.evaluation.execution.ISupervisedLearnerExecutor; import org.api4.java.ai.ml.core.evaluation.execution.LearnerExecutionFailedException; import org.api4.java.ai.ml.core.evaluation.execution.LearnerExecutionInterruptedException; import org.api4.java.ai.ml.core.exception.PredictionException; import org.api4.java.ai.ml.core.exception.TrainingException; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.logging.LoggerUtil; public class SupervisedLearnerExecutor implements ISupervisedLearnerExecutor, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(SupervisedLearnerExecutor.class); @Override public <I extends ILabeledInstance, D extends ILabeledDataset<? extends I>> ILearnerRunReport execute(final ISupervisedLearner<I, D> learner, final D train, final D test) throws LearnerExecutionFailedException, LearnerExecutionInterruptedException { long startTrainTime = System.currentTimeMillis(); try { this.logger.info("Fitting the learner (class: {}) {} with {} instances, each of which with {} attributes", learner.getClass().getName(), learner, train.size(), train.getNumAttributes()); learner.fit(train); } catch (InterruptedException e) { long now = System.currentTimeMillis(); this.logger.info("Training was interrupted after {}ms, sending respective LearnerExecutionInterruptedException.", now - startTrainTime); throw new LearnerExecutionInterruptedException(startTrainTime, now); } catch (TrainingException e) { long now = System.currentTimeMillis(); this.logger.info("Training failed due to an {} after {}ms.", e.getClass().getName(), now - startTrainTime); throw new LearnerExecutionFailedException(startTrainTime, now, e); } long endTrainTime = System.currentTimeMillis(); this.logger.debug("Training finished successfully after {}ms. Now acquiring predictions.", endTrainTime - startTrainTime); try { ILearnerRunReport report = this.getReportForTrainedLearner(learner, train, test, startTrainTime, endTrainTime); long now = System.currentTimeMillis(); this.logger.info("Run report ready after {}ms with {} comparisons of predictions and ground truth.", now - endTrainTime, report.getPredictionDiffList().size()); return report; } catch (InterruptedException e) { long now = System.currentTimeMillis(); this.logger.info("Learner was interrupted during prediction after a runtime of {}ms for training and {}ms for testing ({}ms total walltime).", endTrainTime - startTrainTime, now - endTrainTime, now - startTrainTime); if (Thread.currentThread().isInterrupted()) { this.logger.warn("Observed an InterruptedException while evaluating a learner of type {} ({}) AND the thread is interrupted. This should never happen! Here is the detailed information: {}", learner.getClass(), learner, LoggerUtil.getExceptionInfo(e)); } throw new LearnerExecutionInterruptedException(startTrainTime, endTrainTime, endTrainTime, System.currentTimeMillis()); } catch (PredictionException e) { this.logger.info("Prediction failed with exception {}.", e.getClass().getName()); throw new LearnerExecutionFailedException(startTrainTime, endTrainTime, endTrainTime, System.currentTimeMillis(), e); } } @Override public <I extends ILabeledInstance, D extends ILabeledDataset<? extends I>> ILearnerRunReport execute(final ISupervisedLearner<I, D> learner, final D test) throws LearnerExecutionFailedException { long startTestTime = System.currentTimeMillis(); try { return this.getReportForTrainedLearner(learner, null, test, -1, -1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new LearnerExecutionFailedException(-1, -1, startTestTime, System.currentTimeMillis(), e); } catch (PredictionException e) { throw new LearnerExecutionFailedException(-1, -1, startTestTime, System.currentTimeMillis(), e); } } private <I extends ILabeledInstance, D extends ILabeledDataset<? extends I>> ILearnerRunReport getReportForTrainedLearner(final ISupervisedLearner<I, D> learner, final D train, final D test, final long trainingStartTime, final long trainingEndTime) throws PredictionException, InterruptedException { String previousLoggerName = null; if (learner instanceof ILoggingCustomizable) { previousLoggerName = ((ILoggingCustomizable) learner).getLoggerName(); String tmpLoggerName = this.getLoggerName() + ".learner"; this.logger.debug("Temporarily switching logger of learner {} from {} to {}", learner.getClass(), previousLoggerName, tmpLoggerName); ((ILoggingCustomizable) learner).setLoggerName(tmpLoggerName); } else { this.logger.debug("Evaluated learner {} is not {}, so not customizing its logger.", learner.getClass(), ILoggingCustomizable.class); } long start = System.currentTimeMillis(); List<? extends IPrediction> predictions = learner.predict(test).getPredictions(); long endTestTime = System.currentTimeMillis(); /* create difference table */ TypelessPredictionDiff diff = new TypelessPredictionDiff(); for (int i = 0; i < predictions.size(); i++) { diff.addPair(test.get(i).getLabel(), predictions.get(i)); } if (learner instanceof ILoggingCustomizable) { ((ILoggingCustomizable) learner).setLoggerName(previousLoggerName); } return new LearnerRunReport(train, test, trainingStartTime, trainingEndTime, start, endTestTime, diff); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/TrainPredictionBasedClassifierEvaluator.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.exception.ExceptionUtils; import org.api4.java.ai.ml.classification.IClassifierEvaluator; import org.api4.java.ai.ml.core.dataset.splitter.SplitFailedException; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.execution.IAggregatedPredictionPerformanceMeasure; import org.api4.java.ai.ml.core.evaluation.execution.IDatasetSplitSet; import org.api4.java.ai.ml.core.evaluation.execution.IFixedDatasetSplitSetGenerator; import org.api4.java.ai.ml.core.evaluation.execution.ILearnerRunReport; import org.api4.java.ai.ml.core.evaluation.execution.LearnerExecutionFailedException; import org.api4.java.ai.ml.core.evaluation.execution.LearnerExecutionInterruptedException; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.common.event.IEventEmitter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import ai.libs.jaicore.ml.core.evaluation.evaluator.events.TrainTestSplitEvaluationCompletedEvent; import ai.libs.jaicore.ml.core.evaluation.evaluator.events.TrainTestSplitEvaluationFailedEvent; public class TrainPredictionBasedClassifierEvaluator implements IClassifierEvaluator, ILoggingCustomizable, IEventEmitter<Object> { private Logger logger = LoggerFactory.getLogger(TrainPredictionBasedClassifierEvaluator.class); private final IFixedDatasetSplitSetGenerator<ILabeledDataset<? extends ILabeledInstance>> splitGenerator; private final SupervisedLearnerExecutor executor = new SupervisedLearnerExecutor(); private final IAggregatedPredictionPerformanceMeasure metric; private final EventBus eventBus = new EventBus(); private boolean hasListeners; public TrainPredictionBasedClassifierEvaluator(final IFixedDatasetSplitSetGenerator<ILabeledDataset<?>> splitGenerator, final IAggregatedPredictionPerformanceMeasure<?, ?> metric) { super(); this.splitGenerator = splitGenerator; this.metric = metric; } @Override public Double evaluate(final ISupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> learner) throws InterruptedException, ObjectEvaluationFailedException { try { long evaluationStart = System.currentTimeMillis(); this.logger.info("Using {} to split the given data into two folds.", this.splitGenerator.getClass().getName()); IDatasetSplitSet<ILabeledDataset<? extends ILabeledInstance>> splitSet = this.splitGenerator.nextSplitSet(); if (splitSet.getNumberOfFoldsPerSplit() != 2) { throw new IllegalStateException("Number of folds for each split should be 2 but is " + splitSet.getNumberOfFoldsPerSplit() + "! Split generator: " + this.splitGenerator); } int n = splitSet.getNumberOfSplits(); List<ILearnerRunReport> reports = new ArrayList<>(n); for (int i = 0; i < n; i++) { List<ILabeledDataset<? extends ILabeledInstance>> folds = splitSet.getFolds(i); this.logger.debug("Executing learner {} on folds of sizes {} (train) and {} (test) using {}.", learner, folds.get(0).size(), folds.get(1).size(), this.executor.getClass().getName()); ILearnerRunReport report; try { report = this.executor.execute(learner, folds.get(0), folds.get(1)); this.logger.trace("Obtained report. Training times was {}ms, testing time {}ms. Ground truth vector: {}, prediction vector: {}. Pipeline: {}", report.getTrainEndTime() - report.getTrainStartTime(), report.getTestEndTime() - report.getTestStartTime(), report.getPredictionDiffList().getGroundTruthAsList(), report.getPredictionDiffList().getPredictionsAsList(), learner); } catch (LearnerExecutionInterruptedException e) { this.logger.info("Received interrupt of training in iteration #{} after a total evaluation time of {}ms. Sending an event over the bus and forwarding the exception.", i + 1, System.currentTimeMillis() - evaluationStart); ILabeledDataset<?> train = folds.get(0); ILabeledDataset<?> test = folds.get(1); ILearnerRunReport failReport = new LearnerRunReport(train, test, e.getTrainTimeStart(), e.getTrainTimeEnd(), e.getTestTimeStart(), e.getTestTimeEnd(), e); reports.add(failReport); this.eventBus.post(new TrainTestSplitEvaluationFailedEvent<>(learner, reports)); throw e; } catch (LearnerExecutionFailedException e) { // cannot be merged with the above clause, because then the only common supertype is "Exception", which does not have these methods this.logger.info("Catching {} in iteration #{} after a total evaluation time of {}ms. Sending an event over the bus and forwarding the exception.", e.getClass().getName(), i + 1, System.currentTimeMillis() - evaluationStart); ILabeledDataset<?> train = folds.get(0); ILabeledDataset<?> test = folds.get(1); ILearnerRunReport failReport = new LearnerRunReport(train, test, e.getTrainTimeStart(), e.getTrainTimeEnd(), e.getTestTimeStart(), e.getTestTimeEnd(), e); reports.add(failReport); this.eventBus.post(new TrainTestSplitEvaluationFailedEvent<>(learner, reports)); throw e; } if (this.hasListeners) { this.eventBus.post(new TrainTestSplitEvaluationCompletedEvent<>(learner, report)); } reports.add(report); } this.logger.debug("Compute metric ({}) for the diff of predictions and ground truth.", this.metric.getClass().getName()); double score = this.metric.loss(reports.stream().map(ILearnerRunReport::getPredictionDiffList).collect(Collectors.toList())); this.logger.info("Computed value for metric {} of {} executions. Metric value is: {}. Pipeline: {}", this.metric, n, score, learner); return score; } catch (LearnerExecutionFailedException | SplitFailedException e) { this.logger.debug("Failed to evaluate the learner {}. Exception: {}", learner, ExceptionUtils.getStackTrace(e)); throw new ObjectEvaluationFailedException(e); } } public IFixedDatasetSplitSetGenerator<ILabeledDataset<? extends ILabeledInstance>> getSplitGenerator() { return this.splitGenerator; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); if (this.splitGenerator instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.splitGenerator).setLoggerName(name + ".splitgen"); this.logger.trace("Setting logger of split generator {} to {}.splitgen", this.splitGenerator.getClass().getName(), name); } else { this.logger.trace("Split generator {} is not configurable for logging, so not configuring it.", this.splitGenerator.getClass().getName()); } this.executor.setLoggerName(name + ".executor"); this.logger.trace("Setting logger of learner executor {} to {}.executor", this.executor.getClass().getName(), name); } @Override public void registerListener(final Object listener) { this.eventBus.register(listener); this.hasListeners = true; } public IAggregatedPredictionPerformanceMeasure getMetric() { return this.metric; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/TypelessPredictionDiff.java
package ai.libs.jaicore.ml.core.evaluation.evaluator; import java.util.List; /** * This is a helper class with which one can create a prediction diff object without caring about the types of ground truths and predictions. * * Using the getCastedView method, one can later (in a place where the concrete types are known) get a more specific variant. * * @author Felix Mohr * */ public class TypelessPredictionDiff extends PredictionDiff<Object, Object> { public TypelessPredictionDiff() { super(); } public TypelessPredictionDiff(final List<?> groundTruths, final List<?> predictions) { super(groundTruths, predictions); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/events/MCCVSplitEvaluationEvent.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.events; import org.api4.java.ai.ml.classification.IClassifier; import org.api4.java.common.event.IEvent; public class MCCVSplitEvaluationEvent implements IEvent { private final IClassifier classifier; private final int numInstancesUsedForTraining; private final int numInstancesUsedForValidation; private final int splitEvaluationTime; private final double observedScore; public MCCVSplitEvaluationEvent(final IClassifier classifier, final int numInstancesUsedForTraining, final int numInstancesUsedForValidation, final int splitEvaluationTime, final double observedScore) { super(); this.classifier = classifier; this.numInstancesUsedForTraining = numInstancesUsedForTraining; this.numInstancesUsedForValidation = numInstancesUsedForValidation; this.splitEvaluationTime = splitEvaluationTime; this.observedScore = observedScore; } public IClassifier getClassifier() { return this.classifier; } public int getSplitEvaluationTime() { return this.splitEvaluationTime; } public double getObservedScore() { return this.observedScore; } public int getNumInstancesUsedForTraining() { return this.numInstancesUsedForTraining; } public int getNumInstancesUsedForValidation() { return this.numInstancesUsedForValidation; } @Override public long getTimestamp() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/events/TrainTestSplitEvaluationCompletedEvent.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.events; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.execution.ILearnerRunReport; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.common.event.IEvent; public class TrainTestSplitEvaluationCompletedEvent<I extends ILabeledInstance, D extends ILabeledDataset<? extends I>> implements IEvent { private final ISupervisedLearner<I, D> learner; private final ILearnerRunReport report; public TrainTestSplitEvaluationCompletedEvent(final ISupervisedLearner<I, D> learner, final ILearnerRunReport report) { super(); this.learner = learner; this.report = report; } public ISupervisedLearner<I, D> getLearner() { return this.learner; } public ILearnerRunReport getReport() { return this.report; } @Override public long getTimestamp() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/events/TrainTestSplitEvaluationFailedEvent.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.events; import java.util.Arrays; import java.util.List; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.execution.ILearnerRunReport; import org.api4.java.ai.ml.core.learner.ISupervisedLearner; import org.api4.java.common.event.IEvent; public class TrainTestSplitEvaluationFailedEvent<I extends ILabeledInstance, D extends ILabeledDataset<? extends I>> implements IEvent { private final ISupervisedLearner<I, D> learner; private final List<ILearnerRunReport> report; public TrainTestSplitEvaluationFailedEvent(final ISupervisedLearner<I, D> learner, final ILearnerRunReport report) { this(learner, Arrays.asList(report)); } public TrainTestSplitEvaluationFailedEvent(final ISupervisedLearner<I, D> learner, final List<ILearnerRunReport> report) { super(); this.learner = learner; this.report = report; } public ISupervisedLearner<I, D> getLearner() { return this.learner; } public ILearnerRunReport getLastReport() { return this.report.get(this.report.size() - 1); } public ILearnerRunReport getFirstReport() { return this.report.get(0); } public int getNumReports() { return this.report.size(); } public List<ILearnerRunReport> getReportList() { return this.report; } @Override public long getTimestamp() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/factory/AMonteCarloCrossValidationBasedEvaluatorFactory.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.factory; import java.util.Random; import org.api4.java.ai.ml.core.IDataConfigurable; import org.api4.java.ai.ml.core.dataset.splitter.IDatasetSplitter; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.IPredictionPerformanceMetricConfigurable; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; import org.api4.java.common.control.IRandomConfigurable; /** * An abstract factory for configuring Monte Carlo cross-validation based evaluators. * * @author mwever * @author fmohr * */ public abstract class AMonteCarloCrossValidationBasedEvaluatorFactory<F extends AMonteCarloCrossValidationBasedEvaluatorFactory<F>> implements ISplitBasedSupervisedLearnerEvaluatorFactory<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>, F>, IRandomConfigurable, IDataConfigurable<ILabeledDataset<? extends ILabeledInstance>>, IPredictionPerformanceMetricConfigurable { private IDatasetSplitter<? extends ILabeledDataset<?>> datasetSplitter; protected Random random; protected int numMCIterations; protected ILabeledDataset<?> data; private double trainFoldSize; private int timeoutForSolutionEvaluation; protected IDeterministicPredictionPerformanceMeasure<?, ?> metric; private boolean cacheSplitSets = false; /** * Standard c'tor. */ protected AMonteCarloCrossValidationBasedEvaluatorFactory() { super(); } /** * Getter for the dataset splitter. * * @return Returns the dataset spliiter. */ @Override public IDatasetSplitter<? extends ILabeledDataset<?>> getDatasetSplitter() { return this.datasetSplitter; } /** * Getter for the number of iterations, i.e. the number of splits considered. * * @return The number of iterations. */ public int getNumMCIterations() { return this.numMCIterations; } /** * Getter for the dataset which is used for splitting. * * @return The original dataset that is being split. */ @Override public ILabeledDataset<?> getData() { return this.data; } /** * Getter for the size of the train fold. * * @return The portion of the training data. */ public double getTrainFoldSize() { return this.trainFoldSize; } /** * Getter for the timeout for evaluating a solution. * * @return The timeout for evaluating a solution. */ public int getTimeoutForSolutionEvaluation() { return this.timeoutForSolutionEvaluation; } public IDeterministicPredictionPerformanceMeasure<?, ?> getMetric() { return this.metric; } /** * Configures the evaluator to use the given dataset splitter. * * @param datasetSplitter * The dataset splitter to be used. * @return The factory object. */ @Override public F withDatasetSplitter(final IDatasetSplitter<? extends ILabeledDataset<?>> datasetSplitter) { this.datasetSplitter = datasetSplitter; return this.getSelf(); } public F withRandom(final Random random) { this.random = random; return this.getSelf(); } /** * Configures the number of monte carlo cross-validation iterations. * * @param numMCIterations * The number of iterations to run. * @return The factory object. */ public F withNumMCIterations(final int numMCIterations) { this.numMCIterations = numMCIterations; return this.getSelf(); } /** * Configures the dataset which is split into train and test data. * * @param data * The dataset to be split. * @return The factory object. */ public F withData(final ILabeledDataset<?> data) { this.data = data; return this.getSelf(); } /** * Configures the portion of the training data relative to the entire dataset size. * * @param trainFoldSize * The size of the training fold (0,1). * @return The factory object. */ public F withTrainFoldSize(final double trainFoldSize) { this.trainFoldSize = trainFoldSize; return this.getSelf(); } /** * Configures a timeout for evaluating a solution. * * @param timeoutForSolutionEvaluation * The timeout for evaluating a solution. * @return The factory object. */ public F withTimeoutForSolutionEvaluation(final int timeoutForSolutionEvaluation) { this.timeoutForSolutionEvaluation = timeoutForSolutionEvaluation; return this.getSelf(); } public abstract F getSelf(); @Override public void setMeasure(final IDeterministicPredictionPerformanceMeasure<?, ?> measure) { this.metric = measure; } @Override public void setData(final ILabeledDataset<? extends ILabeledInstance> data) { this.withData(data); } @Override public void setRandom(final Random random) { this.withRandom(random); } public F withMeasure(final IDeterministicPredictionPerformanceMeasure<?, ?> measure) { this.setMeasure(measure); return this.getSelf(); } public IDeterministicPredictionPerformanceMeasure<?, ?> getMeasure() { return this.metric; } public F withCacheSplitSets(final boolean cacheSplitSets) { this.cacheSplitSets = cacheSplitSets; return this.getSelf(); } public boolean getCacheSplitSets() { return this.cacheSplitSets; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/factory/ExtrapolatedSaturationPointEvaluatorFactory.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.factory; import java.util.List; import java.util.Random; import org.api4.java.ai.ml.core.IDataConfigurable; import org.api4.java.ai.ml.core.dataset.splitter.SplitFailedException; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.IPredictionPerformanceMetricConfigurable; import org.api4.java.ai.ml.core.evaluation.ISupervisedLearnerEvaluator; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; import org.api4.java.common.control.IRandomConfigurable; import ai.libs.jaicore.ml.core.evaluation.evaluator.ExtrapolatedSaturationPointEvaluator; import ai.libs.jaicore.ml.core.filter.FilterBasedDatasetSplitter; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.ASamplingAlgorithm; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.factories.LabelBasedStratifiedSamplingFactory; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.factories.interfaces.ISamplingAlgorithmFactory; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.LearningCurveExtrapolationMethod; public class ExtrapolatedSaturationPointEvaluatorFactory implements ISupervisedLearnerEvaluatorFactory<ILabeledInstance, ILabeledDataset<?>>, IRandomConfigurable, IDataConfigurable<ILabeledDataset<? extends ILabeledInstance>>, IPredictionPerformanceMetricConfigurable { private int[] anchorpoints; private ISamplingAlgorithmFactory<ILabeledDataset<?>, ? extends ASamplingAlgorithm<ILabeledDataset<?>>> subsamplingAlgorithmFactory; private double trainSplitForAnchorpointsMeasurement; private LearningCurveExtrapolationMethod extrapolationMethod; private ILabeledDataset<? extends ILabeledInstance> dataset; private Random random; private IDeterministicPredictionPerformanceMeasure<?, ?> metric; public ExtrapolatedSaturationPointEvaluatorFactory(final int[] anchorpoints, final ISamplingAlgorithmFactory<ILabeledDataset<?>, ? extends ASamplingAlgorithm<ILabeledDataset<?>>> subsamplingAlgorithmFactory, final double trainSplitForAnchorpointsMeasurement, final LearningCurveExtrapolationMethod extrapolationMethod) { super(); this.anchorpoints = anchorpoints; this.subsamplingAlgorithmFactory = subsamplingAlgorithmFactory; this.trainSplitForAnchorpointsMeasurement = trainSplitForAnchorpointsMeasurement; this.extrapolationMethod = extrapolationMethod; } @Override public ISupervisedLearnerEvaluator<ILabeledInstance, ILabeledDataset<?>> getLearnerEvaluator() throws LearnerEvaluatorConstructionFailedException { try { List<ILabeledDataset<?>> split = new FilterBasedDatasetSplitter<>(new LabelBasedStratifiedSamplingFactory<ILabeledDataset<?>>(), .7f, this.random).split(this.dataset); ILabeledDataset<?> train = split.get(0); ILabeledDataset<?> test = split.get(1); return new ExtrapolatedSaturationPointEvaluator(this.anchorpoints, this.subsamplingAlgorithmFactory, train, this.trainSplitForAnchorpointsMeasurement, this.extrapolationMethod, this.random.nextLong(), test, this.metric); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new LearnerEvaluatorConstructionFailedException(e); } catch (SplitFailedException e) { throw new LearnerEvaluatorConstructionFailedException(e); } } @Override public void setData(final ILabeledDataset<? extends ILabeledInstance> data) { this.dataset = data; } @Override public ILabeledDataset<? extends ILabeledInstance> getData() { return this.dataset; } @Override public void setRandom(final Random random) { this.random = random; } @Override public void setMeasure(final IDeterministicPredictionPerformanceMeasure<?, ?> measure) { this.metric = measure; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/factory/ISplitBasedSupervisedLearnerEvaluatorFactory.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.factory; import org.api4.java.ai.ml.core.dataset.splitter.IDatasetSplitter; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; public interface ISplitBasedSupervisedLearnerEvaluatorFactory<I extends ILabeledInstance, D extends ILabeledDataset<? extends I>, F> extends ISupervisedLearnerEvaluatorFactory<I, D> { /** * Sets the dataset spliter to the given dataset splitter. * @param datasetSplitter The dataset splitter to be used for splitting the dataset into train and test folds. * @return The instance of the factory. */ public F withDatasetSplitter(IDatasetSplitter<? extends ILabeledDataset<?>> datasetSplitter); /** * @return The currently configured dataset splitter. */ public IDatasetSplitter<? extends ILabeledDataset<?>> getDatasetSplitter(); }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/factory/ISupervisedLearnerEvaluatorFactory.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.factory; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.ISupervisedLearnerEvaluator; public interface ISupervisedLearnerEvaluatorFactory<I extends ILabeledInstance, D extends ILabeledDataset<? extends I>> { public ISupervisedLearnerEvaluator<I, D> getLearnerEvaluator() throws LearnerEvaluatorConstructionFailedException; }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/factory/LearnerEvaluatorConstructionFailedException.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.factory; @SuppressWarnings("serial") public class LearnerEvaluatorConstructionFailedException extends Exception { public LearnerEvaluatorConstructionFailedException(final Exception e) { super(e); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/factory/LearningCurveExtrapolationEvaluatorFactory.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.factory; import java.util.Random; import org.api4.java.ai.ml.core.IDataConfigurable; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.evaluation.ISupervisedLearnerEvaluator; import org.api4.java.common.control.IRandomConfigurable; import ai.libs.jaicore.ml.core.evaluation.evaluator.LearningCurveExtrapolationEvaluator; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.ASamplingAlgorithm; import ai.libs.jaicore.ml.core.filter.sampling.inmemory.factories.interfaces.ISamplingAlgorithmFactory; import ai.libs.jaicore.ml.functionprediction.learner.learningcurveextrapolation.LearningCurveExtrapolationMethod; public class LearningCurveExtrapolationEvaluatorFactory implements ISupervisedLearnerEvaluatorFactory<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>>, IRandomConfigurable, IDataConfigurable<ILabeledDataset<? extends ILabeledInstance>> { private int[] anchorpoints; private ISamplingAlgorithmFactory<ILabeledDataset<?>, ? extends ASamplingAlgorithm<ILabeledDataset<?>>> subsamplingAlgorithmFactory; private double trainSplitForAnchorpointsMeasurement; private LearningCurveExtrapolationMethod extrapolationMethod; private ILabeledDataset<? extends ILabeledInstance> dataset; private Random random; public LearningCurveExtrapolationEvaluatorFactory(final int[] anchorpoints, final ISamplingAlgorithmFactory<ILabeledDataset<?>, ? extends ASamplingAlgorithm<ILabeledDataset<?>>> subsamplingAlgorithmFactory, final double trainSplitForAnchorpointsMeasurement, final LearningCurveExtrapolationMethod extrapolationMethod) { super(); this.anchorpoints = anchorpoints; this.subsamplingAlgorithmFactory = subsamplingAlgorithmFactory; this.trainSplitForAnchorpointsMeasurement = trainSplitForAnchorpointsMeasurement; this.extrapolationMethod = extrapolationMethod; } @Override public ISupervisedLearnerEvaluator<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>> getLearnerEvaluator() throws LearnerEvaluatorConstructionFailedException { return new LearningCurveExtrapolationEvaluator(this.anchorpoints, this.subsamplingAlgorithmFactory, this.dataset, this.trainSplitForAnchorpointsMeasurement, this.extrapolationMethod, this.random.nextLong()); } @Override public void setData(final ILabeledDataset<? extends ILabeledInstance> data) { this.dataset = data; } @Override public ILabeledDataset<? extends ILabeledInstance> getData() { return this.dataset; } @Override public void setRandom(final Random random) { this.random = random; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/evaluator/factory/MonteCarloCrossValidationEvaluatorFactory.java
package ai.libs.jaicore.ml.core.evaluation.evaluator.factory; import java.util.Objects; import org.api4.java.ai.ml.core.evaluation.execution.IAggregatedPredictionPerformanceMeasure; import ai.libs.jaicore.ml.core.evaluation.AveragingPredictionPerformanceMeasure; import ai.libs.jaicore.ml.core.evaluation.evaluator.MonteCarloCrossValidationEvaluator; /** * Factory for configuring standard Monte Carlo cross-validation evaluators. * The basic performance measure is always averaged over the different runs. * * @author mwever * @author fmohr * */ public class MonteCarloCrossValidationEvaluatorFactory extends AMonteCarloCrossValidationBasedEvaluatorFactory<MonteCarloCrossValidationEvaluatorFactory> { @Override public MonteCarloCrossValidationEvaluator getLearnerEvaluator() { if (this.getTrainFoldSize() <= 0 || this.getTrainFoldSize() >= 1) { throw new IllegalStateException("Train fold size is configured to " + this.getTrainFoldSize() + " but must be strictly greater than 0 and strictly smaller than 1."); } Objects.requireNonNull(this.random, "No random source has been defined for the MCCV."); Objects.requireNonNull(this.data, "No data has been set for the MCCV."); Objects.requireNonNull(this.metric, "No metric has been set for the MCCV."); if (this.numMCIterations <= 0) { throw new IllegalStateException("Cannot create MCCV evaluator due to invalid number of repeats " + this.getNumMCIterations() + ". Set number of repeats to a positive value!"); } IAggregatedPredictionPerformanceMeasure<?, ?> aggMeasure = new AveragingPredictionPerformanceMeasure<>(this.metric); return new MonteCarloCrossValidationEvaluator(this.getCacheSplitSets(), this.data, this.getNumMCIterations(), this.getTrainFoldSize(), this.random, aggMeasure); } @Override public MonteCarloCrossValidationEvaluatorFactory getSelf() { return this; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/experiment/IMultiClassClassificationExperimentConfig.java
package ai.libs.jaicore.ml.core.evaluation.experiment; import java.io.File; import java.util.List; import ai.libs.jaicore.experiments.IExperimentSetConfig; public interface IMultiClassClassificationExperimentConfig extends IExperimentSetConfig { public static final String DATASETS = "datasets"; public static final String ALGORITHMS = "algorithms"; public static final String ALGORITHMMODES = "algorithmmodes"; public static final String SEEDS = "seeds"; public static final String TIMEOUTS_IN_SECONDS = "timeouts"; public static final String MEASURES = "measures"; public static final String DATASETFOLDER = "datasetfolder"; @Key(DATASETS) public List<String> getDatasets(); @Key(ALGORITHMS) public List<String> getAlgorithms(); @Key(ALGORITHMMODES) public List<String> getAlgorithmModes(); @Key(SEEDS) public List<String> getSeeds(); @Key(TIMEOUTS_IN_SECONDS) public List<String> getTimeouts(); @Key(MEASURES) public List<String> getMeasures(); @Key(DATASETFOLDER) public File getDatasetFolder(); }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/experiment/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.core.evaluation.experiment;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/splitsetgenerator/CachingMonteCarloCrossValidationSplitSetGenerator.java
package ai.libs.jaicore.ml.core.evaluation.splitsetgenerator; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.api4.java.ai.ml.core.dataset.splitter.IRandomDatasetSplitter; import org.api4.java.ai.ml.core.dataset.splitter.SplitFailedException; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.evaluation.execution.IDatasetSplitSet; public class CachingMonteCarloCrossValidationSplitSetGenerator<D extends ILabeledDataset<?>> extends MonteCarloCrossValidationSplitSetGenerator<D> { private Map<Integer, IDatasetSplitSet<D>> cache = new HashMap<>(); public CachingMonteCarloCrossValidationSplitSetGenerator(final IRandomDatasetSplitter<D> datasetSplitter, final int repeats, final Random random) { super(datasetSplitter, repeats, random); } @Override public synchronized IDatasetSplitSet<D> nextSplitSet(final D data) throws InterruptedException, SplitFailedException { int hashCode = data.hashCode(); if (!this.cache.containsKey(hashCode)) { this.cache.put(hashCode, super.nextSplitSet(data)); } return this.cache.get(hashCode); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/splitsetgenerator/ConstantSplitSetGenerator.java
package ai.libs.jaicore.ml.core.evaluation.splitsetgenerator; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.ai.ml.core.dataset.IInstance; import org.api4.java.ai.ml.core.dataset.splitter.SplitFailedException; import org.api4.java.ai.ml.core.evaluation.execution.IDatasetSplitSet; import org.api4.java.ai.ml.core.evaluation.execution.IFixedDatasetSplitSetGenerator; import ai.libs.jaicore.ml.core.dataset.splitter.DatasetSplitSet; public class ConstantSplitSetGenerator<I extends IInstance, D extends IDataset<? extends I>> implements IFixedDatasetSplitSetGenerator<D> { private final DatasetSplitSet<D> set; public ConstantSplitSetGenerator(final IDatasetSplitSet<D> set) { this.set = new DatasetSplitSet<>(set); } @Override public int getNumSplitsPerSet() { return this.set.getNumberOfSplits(); } @Override public int getNumFoldsPerSplit() { return this.set.getNumberOfFoldsPerSplit(); } @Override public IDatasetSplitSet<D> nextSplitSet() throws InterruptedException, SplitFailedException { return this.set; } @Override public D getDataset() { throw new UnsupportedOperationException("The dataset has already been composed here."); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/core/evaluation/splitsetgenerator/FixedDataSplitSetGenerator.java
package ai.libs.jaicore.ml.core.evaluation.splitsetgenerator; import org.api4.java.ai.ml.core.dataset.IDataset; import org.api4.java.ai.ml.core.dataset.splitter.SplitFailedException; import org.api4.java.ai.ml.core.evaluation.execution.IDatasetSplitSet; import org.api4.java.ai.ml.core.evaluation.execution.IDatasetSplitSetGenerator; import org.api4.java.ai.ml.core.evaluation.execution.IFixedDatasetSplitSetGenerator; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is an IDatasetSplitSetGenerator that produces splits for one initially fixed dataset. * * It can be used as a split generator in a context where the data are not passed along the usage of the splitter. * * @author Felix Mohr * * @param <D> */ public class FixedDataSplitSetGenerator<D extends IDataset<?>> implements IFixedDatasetSplitSetGenerator<D>, ILoggingCustomizable { private final D data; private final IDatasetSplitSetGenerator<D> generator; private Logger logger = LoggerFactory.getLogger(FixedDataSplitSetGenerator.class); public FixedDataSplitSetGenerator(final D data, final IDatasetSplitSetGenerator<D> generator) { super(); this.data = data; this.generator = generator; } @Override public int getNumSplitsPerSet() { return this.generator.getNumFoldsPerSplit(); } @Override public int getNumFoldsPerSplit() { return this.generator.getNumFoldsPerSplit(); } @Override public IDatasetSplitSet<D> nextSplitSet() throws InterruptedException, SplitFailedException { return this.generator.nextSplitSet(this.data); } @Override public D getDataset() { return this.data; } @Override public String toString() { return "FixedDataSplitSetGenerator [data=" + this.data + ", generator=" + this.generator + "]"; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); if (this.generator instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.generator).setLoggerName(name + ".splitgen"); this.logger.info("Setting logger of base split generator {} to {}.splitgen", this.generator.getClass().getName(), name); } else { this.logger.info("Base split generator {} is not configurable for logging, so not configuring it.", this.generator.getClass().getName()); } } }