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/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/AreaUnderROCCurve.java
package ai.libs.jaicore.ml.classification.loss.dataset; public class AreaUnderROCCurve extends AAreaUnderCurvePerformanceMeasure { public AreaUnderROCCurve(final int positiveClass) { super(positiveClass); } @Override public double getXValue(final int tp, final int fp, final int tn, final int fn) { // false positive rate return (double) fp / (fp + tn); } @Override public double getYValue(final int tp, final int fp, final int tn, final int fn) { // true positive rate return (double) tp / (tp + fn); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/AveragedInstanceLoss.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicInstancePredictionPerformanceMeasure; public class AveragedInstanceLoss extends ASingleLabelClassificationPerformanceMeasure { private IDeterministicInstancePredictionPerformanceMeasure<ISingleLabelClassification, Integer> instanceMeasure; public AveragedInstanceLoss(final IDeterministicInstancePredictionPerformanceMeasure<ISingleLabelClassification, Integer> instanceMeasure) { this.instanceMeasure = instanceMeasure; } @Override public double loss(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return IntStream.range(0, expected.size()).mapToDouble(x -> this.instanceMeasure.loss(expected.get(x), predicted.get(x))).average().getAsDouble(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/EAggregatedClassifierMetric.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; 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.IAggregateFunction; import ai.libs.jaicore.basic.aggregate.reals.Mean; public enum EAggregatedClassifierMetric implements IAggregatedPredictionPerformanceMeasure<Integer, ISingleLabelClassification> { MEAN_ERRORRATE(EClassificationPerformanceMeasure.ERRORRATE, new Mean()); private final IDeterministicPredictionPerformanceMeasure<Integer, ISingleLabelClassification> lossFunction; private final IAggregateFunction<Double> aggregation; private EAggregatedClassifierMetric(final IDeterministicPredictionPerformanceMeasure<Integer, ISingleLabelClassification> lossFunction, final IAggregateFunction<Double> aggregation) { this.lossFunction = lossFunction; this.aggregation = aggregation; } @Override public double loss(final List<List<? extends Integer>> expected, final List<List<? extends ISingleLabelClassification>> predicted) { int n = expected.size(); List<Double> losses = new ArrayList<>(); for (int i = 0; i < n; i++) { losses.add(this.lossFunction.loss(expected.get(i), predicted.get(i))); } return this.aggregation.aggregate(losses); } @Override public double loss(final List<IPredictionAndGroundTruthTable<? extends Integer, ? extends ISingleLabelClassification>> pairTables) { return this.aggregation.aggregate(pairTables.stream().map(this.lossFunction::loss).collect(Collectors.toList())); } @Override public double score(final List<List<? extends Integer>> expected, final List<List<? extends ISingleLabelClassification>> predicted) { return 1 - this.loss(expected, predicted); } @Override public double score(final List<IPredictionAndGroundTruthTable<? extends Integer, ? extends ISingleLabelClassification>> pairTables) { return 1 - this.loss(pairTables); } @Override public IDeterministicPredictionPerformanceMeasure<Integer, ISingleLabelClassification> getBaseMeasure() { return this.lossFunction; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/EClassificationPerformanceMeasure.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import org.api4.java.ai.ml.core.evaluation.IPredictionAndGroundTruthTable; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; public enum EClassificationPerformanceMeasure implements IDeterministicPredictionPerformanceMeasure<Integer, ISingleLabelClassification> { // AREA_ABOVE_ROC, AREA_UNDER_ROC, AVG_COST, CORRECT, CORRELATION_COEFFICIENT, ERROR_RATE, FALSE_NEGATIVE_RATE, FALSE_POSITIVE_RATE, F_MEASURE, INCORRECT, KAPPA, KB_INFORMATION, KB_MEA_INFORMATION, KB_RELATIVE_INFORMATION, // MEAN_ABSOLUTE_ERROR, PCT_CORRECT, PCT_INCORRECT, PRECISION, RELATIVE_ABSOLUTE_ERROR, ROOT_MEAN_SQUARED_ERROR, ROOT_RELATIVE_SQUARED_ERROR, WEIGHTED_AREA_UNDER_ROC, WEIGHTED_FALSE_NEGATIVE_RATE, WEIGHTED_FALSE_POSITIVE_RATE, // WEIGHTED_F_MEASURE, WEIGHTED_PRECISION, WEIGHTED_RECALL, WEIGHTED_TRUE_NEGATIVE_RATE, WEIGHTED_TRUE_POSITIVE_RATE ERRORRATE(new ErrorRate()), TRUE_NEGATIVES_WITH_1_POSITIVE(new TrueNegatives(1)), TRUE_POSITIVES_WITH_1_POSITIVE(new TruePositives(1)), FALSE_NEGATIVES_WITH_1_POSITIVE(new FalseNegatives(1)), FALSE_POSITIVES_WITH_1_POSITIVE(new FalsePositives(1)), PRECISION_WITH_1_POSITIVE(new Precision(1)), RECALL_WITH_1_POSITIVE(new Recall(1)), F1_WITH_1_POSITIVE(new F1Measure(1)); private final IDeterministicPredictionPerformanceMeasure<Integer, ISingleLabelClassification> measure; private EClassificationPerformanceMeasure(final IDeterministicPredictionPerformanceMeasure<Integer, ISingleLabelClassification> measure) { this.measure = measure; } @Override public double loss(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return this.measure.loss(expected, predicted); } @Override public double loss(final IPredictionAndGroundTruthTable<? extends Integer, ? extends ISingleLabelClassification> pairTable) { return this.measure.loss(pairTable); } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return this.measure.score(expected, predicted); } @Override public double score(final IPredictionAndGroundTruthTable<? extends Integer, ? extends ISingleLabelClassification> pairTable) { return this.measure.score(pairTable); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/ErrorRate.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; public class ErrorRate extends ASingleLabelClassificationPerformanceMeasure { public ErrorRate() { /* empty constructor to avoid direct instantiation. Use the enum instead. */ } @Override public double loss(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { this.checkConsistency(expected, predicted); double sumOfZOLoss = 0.0; for (int i = 0; i < expected.size(); i++) { sumOfZOLoss += expected.get(i).equals(predicted.get(i).getPrediction()) ? 0.0 : 1.0; } return sumOfZOLoss / expected.size(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/F1Measure.java
package ai.libs.jaicore.ml.classification.loss.dataset; public class F1Measure extends FMeasure { private static final int BETA = 1; public F1Measure(final int positiveClass) { super(BETA, positiveClass); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/FMeasure.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import ai.libs.jaicore.basic.metric.ConfusionMetrics; public class FMeasure extends ASingleLabelClassificationPerformanceMeasure { private final double beta; private final TruePositives tp; private final FalsePositives fp; private final FalseNegatives fn; public FMeasure(final double beta, final int positiveClass) { this.beta = beta; this.tp = new TruePositives(positiveClass); this.fp = new FalsePositives(positiveClass); this.fn = new FalseNegatives(positiveClass); } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { if (expected.size() != predicted.size()) { throw new IllegalArgumentException("Expected and actual must be of the same length."); } return ConfusionMetrics.getFMeasure(this.beta, (int) this.tp.score(expected, predicted), (int) this.fp.score(expected, predicted), (int) this.fn.score(expected, predicted)); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/FalseNegatives.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; public class FalseNegatives extends ASingleLabelClassificationPerformanceMeasure { private final int positiveClass; public FalseNegatives(final int positiveClass) { this.positiveClass = positiveClass; } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return IntStream.range(0, expected.size()).filter(i -> expected.get(i).equals(this.positiveClass) && !expected.get(i).equals(predicted.get(i).getPrediction())).count(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/FalsePositives.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; public class FalsePositives extends ASingleLabelClassificationPerformanceMeasure { private final int positiveClass; public FalsePositives(final int positiveClass) { this.positiveClass = positiveClass; } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return IntStream.range(0, expected.size()).filter(i -> !expected.get(i).equals(this.positiveClass) && !expected.get(i).equals(predicted.get(i).getPrediction())).count(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/IPredictedClassPerformanceMeasure.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; public interface IPredictedClassPerformanceMeasure { public double loss(List<? extends Integer> expected, List<? extends Integer> predicted); public double score(List<? extends Integer> expected, List<? extends Integer> predicted); }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/Precision.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import ai.libs.jaicore.basic.metric.ConfusionMetrics; public class Precision extends ASingleLabelClassificationPerformanceMeasure { private final TruePositives tp; private final FalsePositives fp; public Precision(final int positiveClass) { this.tp = new TruePositives(positiveClass); this.fp = new FalsePositives(positiveClass); } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return ConfusionMetrics.getPrecision((int) this.tp.score(expected, predicted), (int) this.fp.score(expected, predicted)); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/Recall.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import ai.libs.jaicore.basic.metric.ConfusionMetrics; public class Recall extends ASingleLabelClassificationPerformanceMeasure { private final TruePositives tp; private final FalseNegatives fn; public Recall(final int positiveClass) { this.tp = new TruePositives(positiveClass); this.fn = new FalseNegatives(positiveClass); } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return ConfusionMetrics.getRecall((int) this.tp.score(expected, predicted), (int) this.fn.score(expected, predicted)); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/TrueNegatives.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; public class TrueNegatives extends ASingleLabelClassificationPerformanceMeasure { private final int positiveClass; public TrueNegatives(final int positiveClass) { this.positiveClass = positiveClass; } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return IntStream.range(0, expected.size()).filter(i -> !expected.get(i).equals(this.positiveClass) && expected.get(i).equals(predicted.get(i).getPrediction())).count(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/TruePositives.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; public class TruePositives extends ASingleLabelClassificationPerformanceMeasure { private final int positiveClass; public TruePositives(final int positiveClass) { this.positiveClass = positiveClass; } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { return IntStream.range(0, expected.size()).filter(i -> expected.get(i).equals(this.positiveClass) && expected.get(i).equals(predicted.get(i).getPrediction())).count(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/WeightedAUROC.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import ai.libs.jaicore.basic.Maps; /** * Computes the AUROC weighted by class sizes, that is, it first computes the size of each class, * then computes AUROC in a one-vs-rest fashion and balances the final score proportional to the * size of each class. * * @author mwever */ public class WeightedAUROC extends ASingleLabelClassificationPerformanceMeasure { @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { Map<Integer, Integer> classCountMap = new HashMap<>(); expected.stream().forEach(x -> Maps.increaseCounterInMap(classCountMap, x)); double sum = 0; for (Entry<Integer, Integer> posClassEntry : classCountMap.entrySet()) { sum += new AreaUnderROCCurve(posClassEntry.getKey()).score(expected, predicted) * posClassEntry.getValue(); } return sum / classCountMap.values().stream().mapToInt(x -> x).sum(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/instance/AInstanceMeasure.java
package ai.libs.jaicore.ml.classification.loss.instance; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicInstancePredictionPerformanceMeasure; /** * Abstract class for instance-based measures. * * @author mwever * * @param <E> The type of the expected value. * @param <A> The type of the actual/predicted. */ public class AInstanceMeasure<E, A> implements IDeterministicInstancePredictionPerformanceMeasure<A, E> { @Override public double loss(final E expected, final A predicted) { return 1 - this.score(expected, predicted); } @Override public double score(final E expected, final A predicted) { return 1 - this.loss(expected, predicted); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/instance/CrossEntropyLoss.java
package ai.libs.jaicore.ml.classification.loss.instance; import java.util.Map; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; public class CrossEntropyLoss extends AInstanceMeasure<double[], ISingleLabelClassification> { public static final double DEF_EPSILON = 1E-15; private final double epsilon; public CrossEntropyLoss() { this(DEF_EPSILON); } public CrossEntropyLoss(final double epsilon) { this.epsilon = epsilon; } @Override public double loss(final double[] expected, final ISingleLabelClassification predicted) { Map<Integer, Double> distributionMap = predicted.getClassDistribution(); double[] predictedArr = new double[distributionMap.size()]; IntStream.range(0, distributionMap.size()).forEach(x -> predictedArr[x] = distributionMap.get(x)); return -IntStream.range(0, expected.length).mapToDouble(i -> expected[i] * Math.log(this.minMax(predictedArr[i]))).sum(); } private double minMax(final double value) { return Math.min(1 - this.epsilon, Math.max(value, this.epsilon)); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/instance/JaccardScore.java
package ai.libs.jaicore.ml.classification.loss.instance; import java.util.Collection; import ai.libs.jaicore.basic.sets.SetUtil; public class JaccardScore extends AInstanceMeasure<Collection<Integer>, Collection<Integer>> { @Override public double score(final Collection<Integer> expected, final Collection<Integer> predicted) { return ((double) SetUtil.intersection(expected, predicted).size()) / SetUtil.union(expected, predicted).size(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/instance/LogLoss.java
package ai.libs.jaicore.ml.classification.loss.instance; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; public class LogLoss extends AInstanceMeasure<Integer, ISingleLabelClassification> { private final CrossEntropyLoss cel; public LogLoss() { this.cel = new CrossEntropyLoss(); } public LogLoss(final double epsilon) { this.cel = new CrossEntropyLoss(epsilon); } @Override public double loss(final Integer expected, final ISingleLabelClassification predicted) { double[] expectedArr = new double[predicted.getClassDistribution().size()]; expectedArr[expected] = 1.0; return this.cel.loss(expectedArr, predicted); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/instance/ZeroOneLoss.java
package ai.libs.jaicore.ml.classification.loss.instance; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicInstancePredictionPerformanceMeasure; /** * * @author mwever */ public class ZeroOneLoss implements IDeterministicInstancePredictionPerformanceMeasure<Object, Object> { @Override public double loss(final Object expected, final Object predicted) { return expected.equals(predicted) ? 0.0 : 1.0; } @Override public double score(final Object expected, final Object predicted) { return 1 - this.loss(expected, predicted); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/MultiLabelClassification.java
package ai.libs.jaicore.ml.classification.multilabel; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.ml.core.evaluation.Prediction; public class MultiLabelClassification extends Prediction implements IMultiLabelClassification { private static final double DEFAULT_THRESHOLD = 0.5; private double[] threshold; public MultiLabelClassification(final double[] predicted) { this(predicted, DEFAULT_THRESHOLD); } public MultiLabelClassification(final double[] predicted, final double threshold) { this(predicted, IntStream.range(0, predicted.length).mapToDouble(x -> threshold).toArray()); } public MultiLabelClassification(final double[] predicted, final double[] threshold) { super(predicted); this.threshold = threshold; } @Override public double[] getPrediction() { return (double[]) super.getPrediction(); } public int[] getThresholdedPrediction() { return IntStream.range(0, this.getPrediction().length).map(x -> this.getPrediction()[x] >= this.threshold[x] ? 1 : 0).toArray(); } @Override public int[] getPrediction(final double threshold) { return IntStream.range(0, this.getPrediction().length).map(x -> this.getPrediction()[x] >= threshold ? 1 : 0).toArray(); } @Override public int[] getPrediction(final double[] threshold) { return IntStream.range(0, this.getPrediction().length).map(x -> this.getPrediction()[x] >= threshold[x] ? 1 : 0).toArray(); } @Override public int[] getRelevantLabels(final double threshold) { return IntStream.range(0, this.getPrediction().length).filter(x -> this.getPrediction()[x] >= threshold).toArray(); } @Override public int[] getIrrelevantLabels(final double threshold) { return IntStream.range(0, this.getPrediction().length).filter(x -> this.getPrediction()[x] < threshold).toArray(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/MultiLabelClassificationPredictionBatch.java
package ai.libs.jaicore.ml.classification.multilabel; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassificationPredictionBatch; public class MultiLabelClassificationPredictionBatch implements IMultiLabelClassificationPredictionBatch { private List<? extends IMultiLabelClassification> batch; public MultiLabelClassificationPredictionBatch(final List<? extends IMultiLabelClassification> batch) { this.batch = batch; } public MultiLabelClassificationPredictionBatch(final IMultiLabelClassification[] batch) { this(Arrays.asList(batch)); } @Override public IMultiLabelClassification get(final int index) { return this.batch.get(index); } @Override public int getNumPredictions() { return this.batch.size(); } @Override public List<? extends IMultiLabelClassification> getPredictions() { return this.batch; } @Override public double[][] getPredictionMatrix() { double[][] predictionMatrix = new double[this.batch.size()][]; IntStream.range(0, this.batch.size()).forEach(x -> predictionMatrix[x] = this.batch.get(x).getPrediction()); return predictionMatrix; } @Override public int[][] getThresholdedPredictionMatrix(final double threshold) { int[][] predictionMatrix = new int[this.batch.size()][]; IntStream.range(0, this.batch.size()).forEach(x -> predictionMatrix[x] = this.batch.get(x).getPrediction(threshold)); return predictionMatrix; } @Override public int[][] getThresholdedPredictionMatrix(final double[] threshold) { int[][] predictionMatrix = new int[this.batch.size()][]; IntStream.range(0, this.batch.size()).forEach(x -> predictionMatrix[x] = this.batch.get(x).getPrediction(threshold)); return predictionMatrix; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/package-info.java
package ai.libs.jaicore.ml.classification.multilabel;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/AMultiLabelClassificationMeasure.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import org.api4.java.ai.ml.classification.multilabel.evaluation.loss.IMultiLabelClassificationPredictionPerformanceMeasure; import ai.libs.jaicore.ml.classification.loss.dataset.APredictionPerformanceMeasure; public abstract class AMultiLabelClassificationMeasure extends APredictionPerformanceMeasure<int[], IMultiLabelClassification> implements IMultiLabelClassificationPredictionPerformanceMeasure { private static final double DEFAULT_THRESHOLD = 0.5; private final double threshold; protected AMultiLabelClassificationMeasure(final double threshold) { super(); this.threshold = threshold; } protected AMultiLabelClassificationMeasure() { this(DEFAULT_THRESHOLD); } public double getThreshold() { return this.threshold; } protected double[][] listToRelevanceMatrix(final List<? extends IMultiLabelClassification> classificationList) { double[][] matrix = new double[classificationList.size()][]; IntStream.range(0, classificationList.size()).forEach(x -> matrix[x] = classificationList.get(x).getPrediction()); return matrix; } protected int[][] listToThresholdedRelevanceMatrix(final List<? extends IMultiLabelClassification> classificationList) { int[][] matrix = new int[classificationList.size()][]; IntStream.range(0, classificationList.size()).forEach(x -> matrix[x] = classificationList.get(x).getPrediction(this.threshold)); return matrix; } protected Set<Integer> getThresholdedPredictionAsSet(final IMultiLabelClassification prediction) { return Arrays.stream(prediction.getThresholdedPrediction()).mapToObj(Integer::valueOf).collect(Collectors.toSet()); } protected int[][] listToMatrix(final List<? extends int[]> classificationList) { int[][] matrix = new int[classificationList.size()][]; IntStream.range(0, classificationList.size()).forEach(x -> matrix[x] = classificationList.get(x)); return matrix; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/AThresholdBasedMultiLabelClassificationMeasure.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import org.api4.java.ai.ml.classification.multilabel.evaluation.loss.IMultiLabelClassificationPredictionPerformanceMeasure; import ai.libs.jaicore.ml.classification.loss.dataset.APredictionPerformanceMeasure; public abstract class AThresholdBasedMultiLabelClassificationMeasure extends APredictionPerformanceMeasure<int[], IMultiLabelClassification> implements IMultiLabelClassificationPredictionPerformanceMeasure { private static final double DEFAULT_THRESHOLD = 0.5; private final double threshold; protected AThresholdBasedMultiLabelClassificationMeasure(final double threshold) { super(); this.threshold = threshold; } protected AThresholdBasedMultiLabelClassificationMeasure() { super(); this.threshold = DEFAULT_THRESHOLD; } public double getThreshold() { return this.threshold; } protected double[][] listToRelevanceMatrix(final List<? extends IMultiLabelClassification> classificationList) { double[][] matrix = new double[classificationList.size()][]; IntStream.range(0, classificationList.size()).forEach(x -> matrix[x] = classificationList.get(x).getPrediction()); return matrix; } protected int[][] listToThresholdedRelevanceMatrix(final List<? extends IMultiLabelClassification> classificationList) { int[][] matrix = new int[classificationList.size()][]; IntStream.range(0, classificationList.size()).forEach(x -> matrix[x] = classificationList.get(x).getPrediction(this.threshold)); return matrix; } protected int[][] listToMatrix(final List<? extends int[]> classificationList) { int[][] matrix = new int[classificationList.size()][]; IntStream.range(0, classificationList.size()).forEach(x -> matrix[x] = classificationList.get(x)); return matrix; } protected int[][] transposeMatrix(final int[][] matrix) { int[][] out = new int[matrix[0].length][]; for (int i = 0; i < matrix[0].length; i++) { out[i] = new int[matrix.length]; for (int j = 0; j < matrix.length; j++) { out[i][j] = matrix[j][i]; } } return out; } protected double[][] transposeMatrix(final double[][] matrix) { double[][] out = new double[matrix[0].length][]; for (int i = 0; i < matrix[0].length; i++) { out[i] = new double[matrix.length]; for (int j = 0; j < matrix.length; j++) { out[i][j] = matrix[j][i]; } } return out; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(this.threshold); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } return Double.doubleToLongBits(this.threshold) == Double.doubleToLongBits(((AThresholdBasedMultiLabelClassificationMeasure) obj).threshold); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/AutoMEKAGGPFitnessMeasureLoss.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.Arrays; import java.util.List; import java.util.OptionalDouble; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import org.api4.java.ai.ml.classification.multilabel.evaluation.loss.IMultiLabelClassificationPredictionPerformanceMeasure; /** * Measure combining exact match, hamming loss, f1macroavgL and rankloss. Here * implemented in inverse. * * de Sa, Alex GC, Gisele L. Pappa, and Alex A. Freitas. "Towards a method for automatically selecting and configuring multi-label * classification algorithms." Proceedings of the Genetic and Evolutionary Computation Conference Companion. ACM, 2017. * * @author mwever * */ public class AutoMEKAGGPFitnessMeasureLoss extends AMultiLabelClassificationMeasure { private IMultiLabelClassificationPredictionPerformanceMeasure[] measures; @SuppressWarnings("unchecked") public AutoMEKAGGPFitnessMeasureLoss() { super(); this.measures = new IMultiLabelClassificationPredictionPerformanceMeasure[] { new ExactMatch(), new F1MacroAverageL(), new Hamming(), new RankLoss() }; } @SuppressWarnings("unchecked") public AutoMEKAGGPFitnessMeasureLoss(final double threshold) { super(threshold); this.measures = new IMultiLabelClassificationPredictionPerformanceMeasure[] { new ExactMatch(threshold), new F1MacroAverageL(threshold), new Hamming(threshold), new RankLoss(threshold) }; } @Override public double loss(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { OptionalDouble res = Arrays.stream(this.measures).mapToDouble(x -> x.loss(expected, predicted)).average(); if (res.isPresent()) { return res.getAsDouble(); } else { throw new IllegalStateException("Could not take the average of all base measures"); } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/ExactMatch.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.List; import java.util.stream.IntStream; import org.apache.commons.collections4.SetUtils; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.basic.ArrayUtil; public class ExactMatch extends AMultiLabelClassificationMeasure { public ExactMatch() { super(); } public ExactMatch(final double threshold) { super(threshold); } @Override public double loss(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { this.checkConsistency(expected, predicted); return (double) IntStream.range(0, expected.size()).map(x -> SetUtils.isEqualSet(ArrayUtil.argMax(expected.get(x)), this.getThresholdedPredictionAsSet(predicted.get(x))) ? 0 : 1).sum() / expected.size(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/F1MacroAverageL.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.Arrays; import java.util.List; import java.util.OptionalDouble; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.basic.ArrayUtil; import ai.libs.jaicore.ml.classification.loss.dataset.F1Measure; import ai.libs.jaicore.ml.classification.singlelabel.SingleLabelClassification; public class F1MacroAverageL extends AMultiLabelClassificationMeasure { public F1MacroAverageL(final double threshold) { super(threshold); } public F1MacroAverageL() { super(); } @Override public double score(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { this.checkConsistency(expected, predicted); int[][] expectedMatrix = ArrayUtil.transposeMatrix(this.listToMatrix(expected)); int[][] actualMatrix = ArrayUtil.transposeMatrix(this.listToThresholdedRelevanceMatrix(predicted)); F1Measure loss = new F1Measure(1); OptionalDouble res = IntStream.range(0, expectedMatrix.length).mapToDouble( x -> loss.score(Arrays.stream(expectedMatrix[x]).mapToObj(Integer::valueOf).collect(Collectors.toList()), Arrays.stream(actualMatrix[x]).mapToObj(y -> new SingleLabelClassification(2, y)).collect(Collectors.toList()))) .average(); if (!res.isPresent()) { throw new IllegalStateException("Could not determine average label-wise f measure."); } else { return res.getAsDouble(); } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/F1MicroAverage.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import ai.libs.jaicore.ml.classification.loss.dataset.F1Measure; import ai.libs.jaicore.ml.classification.singlelabel.SingleLabelClassification; public class F1MicroAverage extends AMultiLabelClassificationMeasure { public F1MicroAverage(final double threshold) { super(threshold); } public F1MicroAverage() { super(); } @Override public double score(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { this.checkConsistency(expected, predicted); List<Integer> expectedMatrix = expected.stream().flatMapToInt(Arrays::stream).mapToObj(x -> x).collect(Collectors.toList()); List<ISingleLabelClassification> predictedMatrix = expected.stream().flatMapToInt(Arrays::stream).mapToObj(x -> new SingleLabelClassification(2, x)).collect(Collectors.toList()); F1Measure loss = new F1Measure(1); return loss.score(expectedMatrix, predictedMatrix); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/Hamming.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.basic.ArrayUtil; import ai.libs.jaicore.basic.sets.SetUtil; public class Hamming extends AMultiLabelClassificationMeasure { public Hamming() { super(); } public Hamming(final double threshold) { super(threshold); } @Override public double loss(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { this.checkConsistency(expected, predicted); return (double) IntStream.range(0, expected.size()).map(x -> SetUtil.getDisjointSet(this.getThresholdedPredictionAsSet(predicted.get(x)), ArrayUtil.argMax(expected.get(x))).size()).sum() / (expected.size() * expected.get(0).length); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/InstanceWiseF1.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.Arrays; import java.util.List; import java.util.OptionalDouble; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.ml.classification.loss.dataset.F1Measure; import ai.libs.jaicore.ml.classification.singlelabel.SingleLabelClassification; /** * Instance-wise F1 measure for multi-label classifiers. * * For reference see * Wu, Xi-Zhu; Zhou, Zhi-Hua: A Unified View of Multi-Label Performance Measures (ICML / JMLR 2017) * * @author mwever * */ public class InstanceWiseF1 extends AMultiLabelClassificationMeasure { public InstanceWiseF1(final double threshold) { super(threshold); } public InstanceWiseF1() { super(); } @Override public double score(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { this.checkConsistency(expected, predicted); int[][] expectedMatrix = this.listToMatrix(expected); int[][] actualMatrix = this.listToThresholdedRelevanceMatrix(predicted); F1Measure baseMeasure = new F1Measure(1); OptionalDouble res = IntStream.range(0, expectedMatrix.length) .mapToDouble( x -> baseMeasure.score(Arrays.stream(expectedMatrix[x]).mapToObj(y -> y).collect(Collectors.toList()), Arrays.stream(actualMatrix[x]).mapToObj(y -> new SingleLabelClassification(2, y)).collect(Collectors.toList()))) .average(); if (!res.isPresent() || Double.isNaN(res.getAsDouble())) { throw new IllegalStateException("Could not determine average instance-wise f measure."); } else { return res.getAsDouble(); } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/JaccardScore.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.List; import java.util.OptionalDouble; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.basic.ArrayUtil; public class JaccardScore extends AMultiLabelClassificationMeasure { private ai.libs.jaicore.ml.classification.loss.instance.JaccardScore instanceScorer; public JaccardScore() { super(); } public JaccardScore(final double threshold) { super(threshold); } @Override public double score(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> this.instanceScorer.score(ArrayUtil.argMax(expected.get(x)), this.getThresholdedPredictionAsSet(predicted.get(x)))).average(); if (!res.isPresent()) { throw new IllegalStateException("Could not average the jaccord score."); } else { return res.getAsDouble(); } } @Override public double loss(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { return 1 - this.score(expected, predicted); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/RankLoss.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss; import java.util.List; import java.util.OptionalDouble; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.basic.ArrayUtil; public class RankLoss extends AMultiLabelClassificationMeasure { private static final double DEFAULT_TIE_LOSS = 0.0; private final double tieLoss; public RankLoss() { this(DEFAULT_TIE_LOSS); } /** * Create a Ranking Loss measure instance. * * @param tieLoss The loss [0,1] which is accounted for a tie of the predicted relevant and irrelevant label's relevance score. */ public RankLoss(final double tieLoss) { this.tieLoss = tieLoss; } private double rankingLoss(final int[] expected, final IMultiLabelClassification predicted) { List<Integer> expectedRelevantLabels = ArrayUtil.argMax(expected); List<Integer> expectedIrrelevantLabels = ArrayUtil.argMin(expected); double[] labelRelevance = predicted.getPrediction(); double wrongRankingCounter = 0; for (int expectedRel : expectedRelevantLabels) { for (int expectedIrr : expectedIrrelevantLabels) { double scoreRelLabel = labelRelevance[expectedRel]; double scoreIrrLabel = labelRelevance[expectedIrr]; if (scoreRelLabel == scoreIrrLabel) { wrongRankingCounter += this.tieLoss; } else if (scoreRelLabel < scoreIrrLabel) { wrongRankingCounter += 1.0; } } } return wrongRankingCounter / (expectedRelevantLabels.size() + expectedIrrelevantLabels.size()); } @Override public double loss(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { this.checkConsistency(expected, predicted); OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> this.rankingLoss(expected.get(x), predicted.get(x))).average(); if (res.isPresent()) { return res.getAsDouble(); } else { throw new IllegalStateException("The ranking loss could not be averaged across all the instances."); } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/package-info.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/ChoquisticRelevanceLoss.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.AMultiLabelClassificationMeasure; import ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.choquistic.IMassFunction; public class ChoquisticRelevanceLoss extends AMultiLabelClassificationMeasure { private final IMassFunction measure; public ChoquisticRelevanceLoss(final IMassFunction measure) { super(); this.measure = measure; } public ChoquisticRelevanceLoss(final double threshold, final IMassFunction measure) { super(threshold); this.measure = measure; } /** * Function f to be integrated: f(c_i) = u_i = 1 - | s_i - y_i | * s_i \in [0,1]: label relevance score predicted * y_i \in {0,1}: ground truth * * @param expected * @param predicted * @return */ private double fcrit(final int expected, final double predicted) { return 1 - Math.abs(predicted - expected); } private double instanceLoss(final int[] expected, final double[] predicted) { double sum = 0.0; List<Double> listOfCis = IntStream.range(0, expected.length).mapToObj(i -> this.fcrit(expected[i], predicted[i])).collect(Collectors.toList()); listOfCis.add(0.0); Collections.sort(listOfCis); for (int i = 1; i < listOfCis.size(); i++) { sum += (listOfCis.get(i) - listOfCis.get(i - 1)) * this.measure.mu(IntStream.range(i, listOfCis.size()).mapToObj(listOfCis::get).collect(Collectors.toList()), expected.length); } return sum; } @Override public double loss(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { this.checkConsistency(expected, predicted); DescriptiveStatistics stats = new DescriptiveStatistics(); for (int i = 0; i < expected.size(); i++) { stats.addValue(this.instanceLoss(expected.get(i), predicted.get(i).getPrediction())); } return stats.getMean(); } @Override public double score(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { return 1 - this.loss(expected, predicted); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/OWARelevanceLoss.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.api4.java.ai.ml.classification.multilabel.evaluation.IMultiLabelClassification; import ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.AMultiLabelClassificationMeasure; import ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.owa.IOWAValueFunction; public class OWARelevanceLoss extends AMultiLabelClassificationMeasure { private final IOWAValueFunction valueFunction; public OWARelevanceLoss(final IOWAValueFunction valueFunction) { this.valueFunction = valueFunction; } /** * Function f to be integrated: f(c_i) = u_i = 1 - | s_i - y_i | * s_i \in [0,1]: label relevance score predicted * y_i \in {0,1}: ground truth * * @param expected * @param predicted * @return */ private double fcrit(final int expected, final double predicted) { return 1 - Math.abs(predicted - expected); } private double instanceLoss(final int[] expected, final double[] predicted) { double sum = 0.0; double m = expected.length; List<Double> listOfCis = IntStream.range(0, expected.length).mapToObj(i -> this.fcrit(expected[i], predicted[i])).collect(Collectors.toList()); listOfCis.add(0.0); Collections.sort(listOfCis); for (int i = 1; i < listOfCis.size(); i++) { sum += (this.valueFunction.transform((m - i + 1), m) - this.valueFunction.transform((m - i), m)) * listOfCis.get(i); } return 1 - sum; } @Override public double loss(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { this.checkConsistency(expected, predicted); DescriptiveStatistics stats = new DescriptiveStatistics(); for (int i = 0; i < expected.size(); i++) { stats.addValue(this.instanceLoss(expected.get(i), predicted.get(i).getPrediction())); } return stats.getMean(); } @Override public double score(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> predicted) { return 1 - this.loss(expected, predicted); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/package-info.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/choquistic/HammingMassFunction.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.choquistic; import java.util.Collection; public class HammingMassFunction implements IMassFunction { @Override public double mu(final Collection<Double> cis, final int m) { return (double) cis.size() / m; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/choquistic/IMassFunction.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.choquistic; import java.util.Collection; public interface IMassFunction { public double mu(final Collection<Double> cis, final int m); }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/choquistic/SubsetZeroOneMassFunction.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.choquistic; import java.util.Collection; public class SubsetZeroOneMassFunction implements IMassFunction { @Override public double mu(final Collection<Double> cis, final int m) { if (cis.size() == m) { return 1; } else { return 0; } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/choquistic/package-info.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.choquistic;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/owa/IOWAValueFunction.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.owa; public interface IOWAValueFunction { public double transform(double nominator, double denominator); }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/owa/MoebiusTransformOWAValueFunction.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.owa; import org.apache.commons.math3.util.CombinatoricsUtils; public class MoebiusTransformOWAValueFunction implements IOWAValueFunction { private final int k; public MoebiusTransformOWAValueFunction(final int k) { this.k = k; } @Override public double transform(final double nominator, final double denominator) { if ((int) nominator >= this.k) { return CombinatoricsUtils.binomialCoefficientDouble((int) nominator, this.k) / CombinatoricsUtils.binomialCoefficientDouble((int) denominator, this.k); } else { return 0; } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/owa/PolynomialOWAValueFunction.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.owa; public class PolynomialOWAValueFunction implements IOWAValueFunction { private final double alpha; public PolynomialOWAValueFunction(final double alpha) { this.alpha = alpha; } @Override public double transform(final double nominator, final double denominator) { return Math.pow(nominator / denominator, this.alpha); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/multilabel/evaluation/loss/nonadditive/owa/package-info.java
package ai.libs.jaicore.ml.classification.multilabel.evaluation.loss.nonadditive.owa;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/SingleLabelClassification.java
package ai.libs.jaicore.ml.classification.singlelabel; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import ai.libs.jaicore.basic.ArrayUtil; import ai.libs.jaicore.ml.core.evaluation.Prediction; public class SingleLabelClassification extends Prediction implements ISingleLabelClassification { private double[] labelProbabilities; public SingleLabelClassification(final int numClasses, final int predicted) { super(predicted); this.labelProbabilities = new double[numClasses]; this.labelProbabilities[predicted] = 1.0; } public SingleLabelClassification(final Map<Integer, Double> labelProbabilities) { super(labelWithHighestProbability(labelProbabilities)); this.labelProbabilities = new double[labelProbabilities.size()]; labelProbabilities.entrySet().stream().forEach(x -> this.labelProbabilities[x.getKey()] = x.getValue()); } public SingleLabelClassification(final double[] labelProbabilities) { super(ArrayUtil.argMax(labelProbabilities).get(0)); this.labelProbabilities = labelProbabilities; } @Override public int getIntPrediction() { return (int) super.getPrediction(); } @Override public Integer getPrediction() { return this.getIntPrediction(); } @Override public Integer getLabelWithHighestProbability() { return this.getIntPrediction(); } @Override public Map<Integer, Double> getClassDistribution() { Map<Integer, Double> distributionMap = new HashMap<>(); IntStream.range(0, this.labelProbabilities.length).forEach(x -> distributionMap.put(x, this.labelProbabilities[x])); return distributionMap; } @Override public double getProbabilityOfLabel(final int label) { return this.labelProbabilities[label]; } @Override public Map<Integer, Double> getClassConfidence() { Map<Integer, Double> confidenceMap = new HashMap<>(); IntStream.range(0, this.labelProbabilities.length).forEach(x -> confidenceMap.put(x, this.labelProbabilities[x])); return confidenceMap; } private static int labelWithHighestProbability(final Map<Integer, Double> labelProbabilities) { Entry<Integer, Double> highestProbEntry = null; for (Entry<Integer, Double> entry : labelProbabilities.entrySet()) { if (highestProbEntry == null || highestProbEntry.getValue() < entry.getValue()) { highestProbEntry = entry; } } if (highestProbEntry == null) { throw new IllegalArgumentException("No prediction contained"); } else { return highestProbEntry.getKey(); } } @Override public String toString() { return new StringBuilder().append(this.getPrediction()).append(" ").append(Arrays.toString(this.labelProbabilities)).toString(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/SingleLabelClassificationPredictionBatch.java
package ai.libs.jaicore.ml.classification.singlelabel; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassificationPredictionBatch; public class SingleLabelClassificationPredictionBatch extends ArrayList<ISingleLabelClassification> implements ISingleLabelClassificationPredictionBatch { /** * */ private static final long serialVersionUID = 3575940001172802462L; public SingleLabelClassificationPredictionBatch(final Collection<ISingleLabelClassification> predictions) { this.addAll(predictions); } @Override public int getNumPredictions() { return this.size(); } @Override public List<? extends ISingleLabelClassification> getPredictions() { return this; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/package-info.java
package ai.libs.jaicore.ml.classification.singlelabel;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/learner/ASingleLabelClassifier.java
package ai.libs.jaicore.ml.classification.singlelabel.learner; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassificationPredictionBatch; 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.PredictionException; import ai.libs.jaicore.ml.classification.singlelabel.SingleLabelClassificationPredictionBatch; import ai.libs.jaicore.ml.core.learner.ASupervisedLearner; public abstract class ASingleLabelClassifier extends ASupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>, ISingleLabelClassification, ISingleLabelClassificationPredictionBatch> { protected ASingleLabelClassifier(final Map<String, Object> config) { super(config); } protected ASingleLabelClassifier() { super(); } @Override public ISingleLabelClassificationPredictionBatch predict(final ILabeledInstance[] dTest) throws PredictionException, InterruptedException { List<ISingleLabelClassification> batchList = new LinkedList<>(); for (ILabeledInstance i : dTest) { batchList.add(this.predict(i)); } return new SingleLabelClassificationPredictionBatch(batchList); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/learner/MajorityClassifier.java
package ai.libs.jaicore.ml.classification.singlelabel.learner; import java.util.HashMap; import java.util.Map; import java.util.Objects; import org.api4.java.ai.ml.classification.IClassifier; 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.api4.java.ai.ml.core.evaluation.IPrediction; import org.api4.java.ai.ml.core.evaluation.IPredictionBatch; import org.api4.java.ai.ml.core.exception.PredictionException; import org.api4.java.ai.ml.core.exception.TrainingException; import ai.libs.jaicore.ml.classification.singlelabel.SingleLabelClassification; import ai.libs.jaicore.ml.core.evaluation.PredictionBatch; import ai.libs.jaicore.ml.core.learner.ASupervisedLearner; public class MajorityClassifier extends ASupervisedLearner<ILabeledInstance, ILabeledDataset<? extends ILabeledInstance>, IPrediction, IPredictionBatch> implements IClassifier { private Object majorityLabel; private double[] prediction; @Override public void fit(final ILabeledDataset<? extends ILabeledInstance> dTrain) throws TrainingException, InterruptedException { if (!(dTrain.getLabelAttribute() instanceof ICategoricalAttribute)) { throw new IllegalArgumentException("The label attribute of the given data is of type " + dTrain.getLabelAttribute().getClass() + ", but the " + MajorityClassifier.class.getName() + " can only work with categorical labels."); } Map<Object, Integer> labelCounter = new HashMap<>(); Objects.requireNonNull(dTrain); if (dTrain.isEmpty()) { throw new IllegalArgumentException("Cannot train majority classifier with empty training set."); } for (ILabeledInstance i : dTrain) { labelCounter.put(i.getLabel(), labelCounter.computeIfAbsent(i.getLabel(), t -> 0) + 1); } this.majorityLabel = labelCounter.keySet().stream().max((l1, l2) -> Integer.compare(labelCounter.get(l1), labelCounter.get(l2))).get(); ICategoricalAttribute labelAtt = ((ICategoricalAttribute) dTrain.getLabelAttribute()); this.prediction = new double[labelAtt.getLabels().size()]; this.prediction[labelAtt.getAsAttributeValue(this.majorityLabel).getValue()] = 1.0; } @Override public IPrediction predict(final ILabeledInstance xTest) throws PredictionException, InterruptedException { return new SingleLabelClassification(this.prediction); } @Override public IPredictionBatch predict(final ILabeledInstance[] dTest) throws PredictionException, InterruptedException { IPrediction[] predictions = new IPrediction[dTest.length]; for (int i = 0; i < dTest.length; i++) { predictions[i] = this.predict(dTest[i]); } return new PredictionBatch(predictions); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/learner/package-info.java
package ai.libs.jaicore.ml.classification.singlelabel.learner;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/package-info.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries;
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/dataset/ITimeSeriesDataset.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset; import java.util.Iterator; public interface ITimeSeriesDataset { public Iterator<ITimeSeriesInstance> iterator(); }
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/dataset/ITimeSeriesInstance.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.model.INDArrayTimeseries; import ai.libs.jaicore.ml.core.filter.sampling.IClusterableInstance; public interface ITimeSeriesInstance extends IClusterableInstance, ILabeledInstance, Iterable<INDArrayTimeseries> { }
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/dataset/TimeSeriesDataset.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; 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.ITimeseriesAttribute; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledDataset; import org.api4.java.ai.ml.core.exception.DatasetCreationException; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.attribute.NDArrayTimeseriesAttribute; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.model.INDArrayTimeseries; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.model.NDArrayTimeseries; import ai.libs.jaicore.ml.core.dataset.ADataset; /** * Time Series Dataset. */ public class TimeSeriesDataset extends ADataset<ITimeSeriesInstance> implements ILabeledDataset<ITimeSeriesInstance> { private static final long serialVersionUID = -6819487387561457394L; /** Values of time series variables. */ private List<INDArray> valueMatrices; /** Timestamps of time series variables. */ private List<INDArray> timestampMatrices; /** Target values for the instances. */ private transient List<Object> targets; /** * Creates a TimeSeries dataset. Let `n` be the number of instances. * * @param valueMatrices Values for the time series variables. List of * 2D-Arrays with shape `[n, ?]`. * @param timestampMatrices Timestamps for the time series variables. List of * 2D-Arrays with shape `[n, ?]`. Or `null` if no * timestamps exist for the corresponding time series * variable. The shape of the `i`th index must be equal * to the shape of the `i`th element of * `valueMatrices`. * @param targets Target values for the instances. */ public TimeSeriesDataset(final ILabeledInstanceSchema schema, final List<INDArray> valueMatrices, final List<INDArray> timestampMatrices, final List<Object> targets) { this(schema); for (IAttribute att : schema.getAttributeList()) { if (!(att instanceof ITimeseriesAttribute)) { throw new IllegalArgumentException("The schema contains attributes which are not timeseries"); } } Set<Object> valueInstances = valueMatrices.stream().map(x -> x.shape()[0]).collect(Collectors.toSet()); if (valueInstances.size() > 1) { throw new IllegalArgumentException("The value matrices vary in length i.e. they have different number of instances"); } Set<Object> timestampInstances = timestampMatrices.stream().map(x -> x.shape()[0]).collect(Collectors.toSet()); if (timestampInstances.size() > 1) { throw new IllegalArgumentException("The timestamp matrices vary in length i.e. they have different number of instances"); } valueInstances.addAll(timestampInstances); if (valueInstances.size() > 1) { throw new IllegalArgumentException("There are different number of instances for values and timestamps"); } this.valueMatrices = valueMatrices; this.timestampMatrices = timestampMatrices; this.targets = targets; } public TimeSeriesDataset(final ILabeledInstanceSchema schema) { super(schema); } /** * Add a time series variable to the dataset. * * @param valueMatrix Values for the time series variable to add. 2D-Arrays * with shape `[n, ?]` where `n` is the number of * instances of the dataset. * @param timestampMatrix Timestamps for the time series variable to add. * 2D-Arrays with shape `[n, ?]` where `n` is the number * of instances of the dataset. Or `null` if no timestamp * exists for this time series variable. */ public void add(final String attributeName, final INDArray valueMatrix, final INDArray timestampMatrix) { // Parameter checks. // .. this.valueMatrices.add(valueMatrix); this.timestampMatrices.add(timestampMatrix); this.addAttribute(attributeName, valueMatrix); } /** * Removes the time series variable at a given index. * * @param index * @return * @throws IndexOutOfBoundsException */ @Override public void removeColumn(final int index) { this.valueMatrices.remove(index); this.timestampMatrices.remove(index); this.getInstanceSchema().removeAttribute(index); } /** * Replaces the time series variable at a given index with a new one. * * @param index Index of the time series variable to replace. * @param valueMatrix Values for the time series variable to add. 2D-Arrays * with shape `[n, ?]` where `n` is the number of * instances of the dataset. * @param timestampMatrix Timestamps for the time series variable to add. * 2D-Arrays with shape `[n, ?]` where `n` is the number * of instances of the dataset. Or `null` if no timestamp * exists for this time series variable. * @throws IndexOutOfBoundsException Thrown if `numberOfInstances <= index`. */ public void replace(final int index, final INDArray valueMatrix, final INDArray timestampMatrix) { this.valueMatrices.set(index, valueMatrix); if (timestampMatrix != null && this.timestampMatrices != null && this.timestampMatrices.size() > index) { this.timestampMatrices.set(index, timestampMatrix); } NDArrayTimeseriesAttribute type = this.createAttribute("ts" + index, valueMatrix); this.getInstanceSchema().removeAttribute(index); this.getInstanceSchema().addAttribute(index, type); } public Object getTargets() { return this.targets; } public INDArray getTargetsAsINDArray() { if (this.targets.get(0) instanceof Number) { return Nd4j.create(this.targets.stream().mapToDouble(x -> (Double) x).toArray()); } return null; } public int getNumberOfVariables() { return this.valueMatrices.size(); } public long getNumberOfInstances() { return this.valueMatrices.get(0).shape()[0]; } public INDArray getValues(final int index) { return this.valueMatrices.get(index); } public INDArray getTimestamps(final int index) { return this.timestampMatrices.get(index); } public INDArray getValuesOrNull(final int index) { return this.valueMatrices.size() > index ? this.valueMatrices.get(index) : null; } public INDArray getTimestampsOrNull(final int index) { return this.timestampMatrices != null && this.timestampMatrices.size() > index ? this.timestampMatrices.get(index) : null; } @Override public boolean isEmpty() { return this.valueMatrices.isEmpty(); } public boolean isUnivariate() { return this.valueMatrices.size() == 1; } public boolean isMultivariate() { return this.valueMatrices.size() > 1; } // -- // Intern helper functions. // -- private NDArrayTimeseriesAttribute createAttribute(final String name, final INDArray valueMatrix) { int length = (int) valueMatrix.shape()[1]; return new NDArrayTimeseriesAttribute(name, length); } private void addAttribute(final String name, final INDArray valueMatrix) { NDArrayTimeseriesAttribute type = this.createAttribute(name, valueMatrix); this.getInstanceSchema().addAttribute(type); this.valueMatrices.add(valueMatrix); } // -- // IDataset interface. // -- /** * Iterator for the @{@link}TimeSeriesDataset. Iterates and implicitly creates * the @{link}TimeSeriesInstance. */ class TimeSeriesDatasetIterator implements Iterator<ITimeSeriesInstance> { private int current = 0; @Override public boolean hasNext() { return TimeSeriesDataset.this.getNumberOfInstances() > this.current; } @Override public ITimeSeriesInstance next() { if (!this.hasNext()) { throw new NoSuchElementException(); } return TimeSeriesDataset.this.get(this.current++); } } @Override public TimeSeriesInstance get(final int index) { // Build attribute value as view on the row of the attribute matrix. List<INDArrayTimeseries> attributeValues = new ArrayList<>(); for (int i = 0; i < TimeSeriesDataset.this.valueMatrices.size(); i++) { attributeValues.add(new NDArrayTimeseries(TimeSeriesDataset.this.valueMatrices.get(i).getRow(index))); } // Build target value. Object target = this.targets.get(index); return new TimeSeriesInstance(attributeValues, target); } @Override public Iterator<ITimeSeriesInstance> iterator() { return new TimeSeriesDatasetIterator(); } @Override public TimeSeriesDataset createEmptyCopy() throws DatasetCreationException, InterruptedException { return new TimeSeriesDataset(this.getInstanceSchema()); } @Override public Object[][] getFeatureMatrix() { throw new UnsupportedOperationException(); } @Override public Object[] getLabelVector() { return this.targets.toArray(); } @Override public TimeSeriesDataset createCopy() throws DatasetCreationException, InterruptedException { TimeSeriesDataset copy = this.createEmptyCopy(); for (ITimeSeriesInstance i : this) { copy.add(i); } return copy; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.targets == null) ? 0 : this.targets.hashCode()); result = prime * result + ((this.timestampMatrices == null) ? 0 : this.timestampMatrices.hashCode()); result = prime * result + ((this.valueMatrices == null) ? 0 : this.valueMatrices.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; } TimeSeriesDataset other = (TimeSeriesDataset) obj; if (this.targets == null) { if (other.targets != null) { return false; } } else if (!this.targets.equals(other.targets)) { return false; } if (this.timestampMatrices == null) { if (other.timestampMatrices != null) { return false; } } else if (!this.timestampMatrices.equals(other.timestampMatrices)) { return false; } if (this.valueMatrices == null) { if (other.valueMatrices != null) { return false; } } else if (!this.valueMatrices.equals(other.valueMatrices)) { return false; } return true; } }
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/dataset/TimeSeriesDataset2.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset; import java.util.List; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.ClassMapper; /** * Dataset for time series. * * <p> * The dataset consists of a value matrices and timestamp matrices. In the * univariate case, there exists one value matrix, either with or without a * corresponding timestamp matrix. In the multivariate case there exists * multiple value matrices, each either with or without a corresponding * timestamp matrix. Each value matrix is associated with an integer index. Each * timestamp matrix is associated with an integer index. Two corresponding value * and timestamp matrices are associated with the same index. The dimensions of * two corresponding value and timestamp matrices are assured to be the same. * All value matrices have the same number of rows, but not necessarily the same * number of columns. The <code>i</code>-th row of each matrix corresponds to * the <code>i</code>-th instance of the dataset. * <p> * <p> * The targets contained in this dataset are always integers. The can be mapped * back and forth with the {@link ClassMapper}. Targets are represented as an * integer array. The <code>i</code>-th entry of this array corresponds to the * <code>i</code>-th instance of the dataset. * </p> * * @author fischor */ public class TimeSeriesDataset2 { /** Number of instances contained in the dataset. */ private int numberOfInstances; /** Values of time series variables. */ private List<double[][]> valueMatrices; /** Timestamps of time series variables. */ private List<double[][]> timestampMatrices; /** Target values for the instances. */ private int[] targets; /** States, whether in train (or test) mode. */ private final boolean train; /** * Creates a time series dataset with timestamps for training. Let `n` be the * number of instances. * * @param valueMatrices Values for the time series variables. List of * 2D-Arrays with shape `[n, ?]`. * @param timestampMatrices Timestamps for the time series variables. List of * 2D-Arrays with shape `[n, ?]`. Or `null` if no * timestamps exist for the corresponding time series * variable. The shape of the `i`th index must be equal * to the shape of the `i`th element of * `valueMatrices`. * @param targets Target values for the instances. */ public TimeSeriesDataset2(final List<double[][]> valueMatrices, final List<double[][]> timestampMatrices, final int[] targets) { // Parameter checks. // .. this.numberOfInstances = valueMatrices.get(0).length; this.valueMatrices = valueMatrices; this.timestampMatrices = timestampMatrices; this.targets = targets; this.train = true; } /** * Creates a time series dataset with timestamps for testing. Let `n` be the * number of instances. * * @param valueMatrices Valueso for the time series variables. List of * 2D-Arrays with shape `[n, ?]`. * @param timestampMatrices Timestamps for the time series variables. List of * 2D-Arrays with shape `[n, ?]`. Or `null` if no * timestamps exist for the corresponding time series * variable. The shape of the `i`th index must be equal * to the shape of the `i`th element of * `valueMatrices`. * @param targets Target values for the instances. */ public TimeSeriesDataset2(final List<double[][]> valueMatrices, final List<double[][]> timestampMatrices) { // Parameter checks. // .. this.numberOfInstances = valueMatrices.get(0).length; this.valueMatrices = valueMatrices; this.timestampMatrices = timestampMatrices; this.targets = new int[this.numberOfInstances]; this.train = false; } /** * Creates a time series dataset withot timestamps for training. Let `n` be the * number of instances. * * @param valueMatrices Values for the time series variables. List of * 2D-Arrays with shape `[n, ?]`. * @param timestampMatrices Timestamps for the time series variables. List of * 2D-Arrays with shape `[n, ?]`. Or `null` if no * timestamps exist for the corresponding time series * variable. The shape of the `i`th index must be equal * to the shape of the `i`th element of * `valueMatrices`. * @param targets Target values for the instances. */ public TimeSeriesDataset2(final List<double[][]> valueMatrices, final int[] targets) { // Parameter checks. // .. this(valueMatrices, null, targets); } /** * Creates a time series dataset without timestamps for testing. Let `n` be the * number of instances. * * @param valueMatrices Values for the time series variables. List of 2D-Arrays * with shape `[n, ?]`. * @param targets Target values for the instances. */ public TimeSeriesDataset2(final List<double[][]> valueMatrices) { // Parameter checks. // .. this.numberOfInstances = valueMatrices.get(0).length; this.valueMatrices = valueMatrices; this.timestampMatrices = null; this.targets = new int[this.numberOfInstances]; this.train = false; } /** * Add a time series variable with timestamps to the dataset. * * @param valueMatrix Values for the time series variable to add. 2D-Arrays * with shape `[n, ?]` where `n` is the number of * instances of the dataset. * @param timestampMatrix Timestamps for the time series variable to add. * 2D-Arrays with shape `[n, ?]` where `n` is the number * of instances of the dataset. Or `null` if no timestamp * exists for this time series variable. */ public void add(final double[][] valueMatrix, final double[][] timestampMatrix) { // Parameter checks. // .. this.valueMatrices.add(valueMatrix); this.timestampMatrices.add(timestampMatrix); } /** * Add a time series variable without timestamps to the dataset. * * @param valueMatrix Values for the time series variable to add. 2D-Arrays with * shape `[n, ?]` where `n` is the number of instances of the * dataset. */ public void add(final double[][] valueMatrix) { // Parameter checks. // .. this.valueMatrices.add(valueMatrix); this.timestampMatrices.add(null); } /** * Removes the time series variable at a given index. * * @param index * @throws IndexOutOfBoundsException */ public void remove(final int index) { this.valueMatrices.remove(index); this.timestampMatrices.remove(index); } /** * Replaces the time series variable at a given index with a new one. * * @param index Index of the time series varialbe to replace. * @param valueMatrix Values for the time series variable to add. 2D-Arrays * with shape `[n, ?]` where `n` is the number of * instances of the dataset. * @param timestampMatrix Timestamps for the time series variable to add. * 2D-Arrays with shape `[n, ?]` where `n` is the number * of instances of the dataset. Or `null` if no timestamp * exists for this time series variable. * @throws IndexOutOfBoundsException Thrown if `numberOfInstances <= index`. */ public void replace(final int index, final double[][] valueMatrix, final double[][] timestampMatrix) { this.valueMatrices.set(index, valueMatrix); if (timestampMatrix != null && this.timestampMatrices != null && this.timestampMatrices.size() > index) { this.timestampMatrices.set(index, timestampMatrix); } } /** * Getter for the target values. * * @return The targets. */ public int[] getTargets() { return this.targets; } /** * Returns the number of variables, i.e. the number of value matrices contained * in the dataset. * * @return The number of variables. */ public int getNumberOfVariables() { return this.valueMatrices.size(); } /** * Returns the number of instances contained in the dataset. * * @return The number of instances contained in the dataset. */ public int getNumberOfInstances() { return this.numberOfInstances; } /** * Getter for the value matrix at a specific index. Throws an exception if no * timestamp matrix exists at this index. * * @param index The index of the value matrix. * @return The value matrix at index <code>index</code>. * @throws IndexOutOfBoundsException If there is no value matrix at index * <code>index</code>. */ public double[][] getValues(final int index) { return this.valueMatrices.get(index); } /** * Getter for the timestamp matrix at a specific index. * * @param index The index of the timestamp matrix. * @return The timestamp matrix at index <code>index</code>. * @throws IndexOutOfBoundsException If there is no value timestamp at index * <code>index</code>. */ public double[][] getTimestamps(final int index) { return this.timestampMatrices.get(index); } /** * Getter for the value matrix at a specific index. * * @param index The index of the timestamp matrix. * @return The value matrix at index <code>index</code>. Or <code>null</code>, * if no value matrix exists at index <code>index</code>. */ public double[][] getValuesOrNull(final int index) { return this.valueMatrices.size() > index ? this.valueMatrices.get(index) : null; } /** * Getter for the timestamp matrix at a specific index. * * @param index The index of the timestamp matrix. * @return The timestamp matrix at index <code>index</code>. Or * <code>null</code>, if no timestamp matrix exists at index * <code>index</code>. */ public double[][] getTimestampsOrNull(final int index) { if (this.timestampMatrices == null) { return null; } return this.timestampMatrices.size() > index ? this.timestampMatrices.get(index) : null; } /** * States whether the dataset is empty, i.e. contains no value matrices, or not. * * @return <code>True</code>, if the dataset is empty. <code>False</code>, * otherwise. */ public boolean isEmpty() { return this.valueMatrices.isEmpty(); } /** * States whether the dataset is a univariate dataset, i.e. contains exactly one * value matrix, or not. * * @return <code>True</code>, if the dataset is univariate. <code>False</code>, * otherwise. */ public boolean isUnivariate() { return this.valueMatrices.size() == 1; } /** * States whether the dataset is a univariate dataset, i.e. contains more than * one value matrix, or not. * * @return <code>True</code>, if the dataset is multivariate. * <code>False</code>, otherwise. */ public boolean isMultivariate() { return this.valueMatrices.size() > 1; } /** * States whether the dataset is a training dataset, i.e. contains valid targets * after initialization, or not. * * @return <code>True</code>, if the dataset is a training dataset. * <code>False</code>, otherwise. */ public boolean isTrain() { return this.train; } /** * States whether the dataset is a test dataset, i.e. contains no valid targets * after initialization, or not. * * @return <code>True</code>, if the dataset is a test dataset. * <code>False</code>, otherwise. */ public boolean isTest() { return !this.train; } /** * Getter for {@link TimeSeriesDataset2#valueMatrices}. * * @return the valueMatrices */ public List<double[][]> getValueMatrices() { return this.valueMatrices; } /** * Getter for {@link TimeSeriesDataset2#timestampMatrices}. * * @return the timestampMatrices */ public List<double[][]> getTimestampMatrices() { return this.timestampMatrices; } /** * Setter for {@link TimeSeriesDataset2#valueMatrices}. * * @param valueMatrices the valueMatrices to set */ public void setValueMatrices(final List<double[][]> valueMatrices) { this.valueMatrices = valueMatrices; } /** * Setter for {@link TimeSeriesDataset2#timestampMatrices}. * * @param timestampMatrices the timestampMatrices to set */ public void setTimestampMatrices(final List<double[][]> timestampMatrices) { this.timestampMatrices = timestampMatrices; } /** * Setter for {@link TimeSeriesDataset2#targets}. * * @param targets the targets to set */ public void setTargets(final int[] targets) { this.targets = targets; } }
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/dataset/TimeSeriesFeature.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.MathUtil; /** * Class calculating features (e. g. mean, stddev or slope) on given * subsequences of time series. Used e. g. for {@link TimeSeriesTreeClassifier} * classifier. * * @author Julian Lienen * */ public class TimeSeriesFeature { /** * Feature types used within the time series tree. */ public enum FeatureType { MEAN, STDDEV, SLOPE } /** * Number of features used within the time series tree. */ public static final int NUM_FEATURE_TYPES = FeatureType.values().length; /** * Function calculating all features occurring in {@link FeatureType} at once * using an online calculation approach for mean, standard deviation and the * slope. * * @param vector * The instance's vector which is used to calculate the features * @param t1 * Start of the interval * @param t2 * End of the interval (inclusive) * @param useBiasCorrection * Indicator whether the bias (Bessel's) correction should be used * for the standard deviation calculation * @return Returns an double array of the size * {@link TimeSeriesTreeLearningAlgorithm#NUM_FEATURE_TYPES} storing the * generated feature values. */ public static double[] getFeatures(final double[] vector, final int t1, final int t2, final boolean useBiasCorrection) { double[] result = new double[NUM_FEATURE_TYPES]; if (t1 >= vector.length || t2 >= vector.length) { throw new IllegalArgumentException("Parameters t1 and t2 must be valid indices of the vector."); } if (t1 == t2) { return new double[] { vector[t1], 0d, 0d }; } // Calculate running sums for mean, stddev and slope double xx = 0; double x = 0; double xy = 0; double y = 0; double yy = 0; for (int i = t1; i <= t2; i++) { x += i; y += vector[i]; yy += vector[i] * vector[i]; xx += i * i; xy += i * vector[i]; } double length = t2 - t1 + 1d; // Calculate the mean result[0] = y / length; // Calculate the standard deviation double stddev = (yy / length - ((y / length) * (y / length))); if (useBiasCorrection) { stddev *= length / (length - 1); } stddev = Math.sqrt(stddev); result[1] = stddev; // Calculate slope double divisor = (length * xx - x * x); if (divisor == 0) { throw new IllegalStateException("Divisor is 0, which must not happen!"); } result[2] = (length * xy - x * y) / divisor; return result; } /** * Function calculating the feature specified by the feature type * <code>fType</code> for a given instance <code>vector</code> of the interval * [<code>t1</code>, <code>t2</code>]. * * @param fType * The feature type to be calculated * @param instance * The instance's vector which values are used * @param t1 * Start of the interval * @param t2 * End of the interval (inclusive) * @param useBiasCorrection * Indicator whether the bias (Bessel's) correction should be used * for the standard deviation calculation * @return Returns the calculated feature for the specific instance and interval */ public static double calculateFeature(final FeatureType fType, final double[] vector, final int t1, final int t2, final boolean useBiasCorrection) { switch (fType) { case MEAN: return MathUtil.mean(vector, t1, t2); case STDDEV: return MathUtil.stddev(vector, t1, t2, useBiasCorrection); case SLOPE: return MathUtil.slope(vector, t1, t2); default: throw new UnsupportedOperationException("Feature calculation function with id '" + fType + "' is unknwon."); } } }
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/dataset/TimeSeriesInstance.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset; import java.util.Arrays; import java.util.Iterator; import java.util.List; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.model.INDArrayTimeseries; /** * TimeSeriesInstance */ public class TimeSeriesInstance implements ITimeSeriesInstance { /** Attribute values of the instance. */ private List<INDArrayTimeseries> attributeValues; /** Target value of the instance. */ private Object label; /** * Constructor. * * @param dataset * @param attributeValues * @param targetValue */ public TimeSeriesInstance(final INDArrayTimeseries[] attributeValues, final Object targetValue) { this(Arrays.asList(attributeValues), targetValue); } public TimeSeriesInstance(final List<INDArrayTimeseries> attributeValues, final Object targetValue) { this.attributeValues = attributeValues; this.label = targetValue; } @Override public INDArrayTimeseries getAttributeValue(final int pos) { return this.attributeValues.get(pos); } @Override public Object getLabel() { return this.label; } @Override public Iterator<INDArrayTimeseries> iterator() { return this.attributeValues.iterator(); } @Override public double[] getPoint() { double[] point = new double[this.attributeValues.stream().mapToInt(INDArrayTimeseries::length).sum()]; int i = 0; for (INDArrayTimeseries series : this.attributeValues) { double[] seriesPoint = series.getPoint(); for (int j = 0; j < seriesPoint.length; j++) { point[i++] = seriesPoint[j]; } } return point; } @Override public Object[] getAttributes() { return this.attributeValues.toArray(); } @Override public void removeColumn(final int columnPos) { if (columnPos < this.attributeValues.size() && columnPos >= 0) { this.attributeValues.remove(columnPos); } else { throw new IllegalArgumentException("The index is not valid."); } } @Override public double getPointValue(final int pos) { throw new UnsupportedOperationException("This operation is not supported."); } @Override public void setLabel(final Object label) { this.label = label; } @Override public void setAttributeValue(final int pos, final Object value) { if (!(value instanceof INDArrayTimeseries)) { throw new IllegalArgumentException("The given value is no timeseries."); } this.attributeValues.add((INDArrayTimeseries) value); } @Override public boolean isLabelPresent() { return this.label != null; } }
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/dataset/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/dataset/attribute/ATimeseriesAttribute.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ITimeseries; import org.api4.java.ai.ml.core.dataset.schema.attribute.ITimeseriesAttribute; import ai.libs.jaicore.ml.core.dataset.schema.attribute.AGenericObjectAttribute; /** * * @author mwever * * @param <O> Type of the representation of a timeseries. */ public abstract class ATimeseriesAttribute<O> extends AGenericObjectAttribute<ITimeseries<O>> implements ITimeseriesAttribute<O> { /** * */ private static final long serialVersionUID = -3411560349820853762L; private int length; protected ATimeseriesAttribute(final String name, final int length) { super(name); this.length = length; } /** * Get the length of this time series attribute type. * * @return The length respec. the number of datapoints of this time series * attribute. */ public int getLength() { return this.length; } public void setLength(final int length) { if (length < 0) { throw new IllegalArgumentException("the length has to be greater than or equal to zero."); } this.length = length; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + this.length; 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; } ATimeseriesAttribute other = (ATimeseriesAttribute) obj; return this.length == other.length; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/dataset/attribute/NDArrayTimeseriesAttribute.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ITimeseries; import org.api4.java.ai.ml.core.dataset.schema.attribute.ITimeseriesAttributeValue; import org.api4.java.ai.ml.core.dataset.schema.attribute.NoValidAttributeValueException; import org.nd4j.linalg.api.ndarray.INDArray; /** * Describes a time series type as an 1-NDArray with a fixed length. */ public class NDArrayTimeseriesAttribute extends ATimeseriesAttribute<INDArray> { private static final String MSG_NOTIMPLEMENTED = "Not yet implemented"; /** * */ private static final long serialVersionUID = -9188360800052241944L; public NDArrayTimeseriesAttribute(final String name, final int length) { super(name, length); } /** * Validates whether a INDArray conforms to this time series. An INDArray * confirms to this value, if its rank is 1 and its length equals the length of * this time series. * * @param value The value to validated. * @return Returns true if the given value conforms */ @Override public boolean isValidValue(final Object value) { if (value instanceof ITimeseries<?> && ((ITimeseries<?>) value).getValue() instanceof INDArray) { INDArray castedValue = (INDArray) ((ITimeseries<?>) value).getValue(); return castedValue.rank() == 1 && castedValue.length() == this.getLength(); } return value instanceof NDArrayTimeseriesAttributeValue; } @Override public String getStringDescriptionOfDomain() { return "[NDATS] " + this.getName(); } @Override public ITimeseriesAttributeValue<INDArray> getAsAttributeValue(final Object object) { return new NDArrayTimeseriesAttributeValue(this, this.getValueAsTypeInstance(object)); } @SuppressWarnings("unchecked") @Override protected ITimeseries<INDArray> getValueAsTypeInstance(final Object object) { if (this.isValidValue(object)) { if (object instanceof NDArrayTimeseriesAttributeValue) { return ((NDArrayTimeseriesAttributeValue) object).getValue(); } else { return (ITimeseries<INDArray>) object; } } else { throw new NoValidAttributeValueException(); } } @Override public double toDouble(final Object object) { throw new UnsupportedOperationException(MSG_NOTIMPLEMENTED); } @Override public String serializeAttributeValue(final Object value) { throw new UnsupportedOperationException(MSG_NOTIMPLEMENTED); } @Override public Object deserializeAttributeValue(final String string) { throw new UnsupportedOperationException(MSG_NOTIMPLEMENTED); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/dataset/attribute/NDArrayTimeseriesAttributeValue.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.attribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ITimeseries; import org.api4.java.ai.ml.core.dataset.schema.attribute.ITimeseriesAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.ITimeseriesAttributeValue; import org.nd4j.linalg.api.ndarray.INDArray; public class NDArrayTimeseriesAttributeValue implements ITimeseriesAttributeValue<INDArray> { private ITimeseriesAttribute<?> attribute; private ITimeseries<INDArray> value; public NDArrayTimeseriesAttributeValue(final ITimeseriesAttribute<?> attribute, final ITimeseries<INDArray> value) { this.value = value; this.attribute = attribute; } @Override public ITimeseries<INDArray> getValue() { return this.value; } @Override public ITimeseriesAttribute<?> getAttribute() { return this.attribute; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/dataset
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/dataset/attribute/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.attribute;
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/exception/NoneFittedFilterExeception.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception; import ai.libs.jaicore.ml.core.exception.UncheckedJaicoreMLException; public class NoneFittedFilterExeception extends UncheckedJaicoreMLException { /** * */ private static final long serialVersionUID = 1L; public NoneFittedFilterExeception(final String message, final Throwable cause) { super(message, cause); } public NoneFittedFilterExeception(final String message) { super(message); } }
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/exception/TimeSeriesLengthException.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception; /** * Exception class encapsultes faulty behaviour with length of time series. * * @author fischor */ public class TimeSeriesLengthException extends IllegalArgumentException { private static final long serialVersionUID = 1L; public TimeSeriesLengthException(String message, Throwable cause) { super(message, cause); } public TimeSeriesLengthException(String message) { super(message); } }
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/exception/TimeSeriesLoadingException.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception; /** * Exception thrown when a time series dataset could not be extracted from an * external data source (e. g. a file). * * @author Julian Lienen * */ public class TimeSeriesLoadingException extends Exception { /** * Default generated serial version UID. */ private static final long serialVersionUID = -3825008730451093690L; /** * Constructor using a nested <code>Throwable</code> exception. * * @param message * Individual exception message * @param cause * Nested exception */ public TimeSeriesLoadingException(final String message, final Throwable cause) { super(message, cause); } /** * Standard constructor. * * @param message * Individual exception message */ public TimeSeriesLoadingException(final String message) { super(message); } }
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/filter/AFilter.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; public abstract class AFilter implements IFilter { @Override public TimeSeriesDataset2 fitTransform(final TimeSeriesDataset2 input) { this.fit(input); return this.transform(input); } }
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/filter/IFilter.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception.NoneFittedFilterExeception; public interface IFilter { /** * represents a function working on a dataset by transforming the dataset itself. * * @param input the data set that is to transform * @return the transformt dataset * @throws NoneFittedFilterExeception used if transform is called without fit * @throws IllegalArgumentException used if dataset to transform is empty */ public TimeSeriesDataset2 transform(TimeSeriesDataset2 input); /** * This function transforms only a single instance. * * @param input the to transform instance * @return the transformed instance * @throws NoneFittedFilterExeception */ public double[] transform(double[] input); public double[][] transform(double[][] input); /** * the function computes the needed information for the transform function. * * @param input the dataset that is to transform */ public void fit(TimeSeriesDataset2 input); /** * The function only fits a single instance of the dataset * * @param input The to fit instance */ public void fit(double[] input); public void fit(double[][] input); /** * a utility function to avoid the added effort of calling the fit and transform * function separate * * @param input the dataset that is to be transfromed * @return the transformed dataset * @throws NoneFittedFilterExeception used if transform is called without fit * @throws IllegalArgumentException used if dataset to transform is empty */ public TimeSeriesDataset2 fitTransform(TimeSeriesDataset2 input); /** * the function fit and transforms a single instance * * @param input the to fit and transform instance * @return the transformed instance */ public double[] fitTransform(double[] input); public double[][] fitTransform(double[][] input); }
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/filter/SAX.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter; import java.util.Arrays; import ai.libs.jaicore.basic.transform.vector.PiecewiseAggregateApproximationTransform; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception.NoneFittedFilterExeception; public class SAX implements IFilter { private double[] alphabet; private boolean fitted; private int wordLength; private double[][] lookuptable; private ZTransformer ztransform; private PiecewiseAggregateApproximationTransform paa; public SAX(final double[] alphabet, final int wordLength) { this.ztransform = new ZTransformer(); this.alphabet = alphabet; this.wordLength = wordLength; this.paa = new PiecewiseAggregateApproximationTransform(wordLength); } @Override public TimeSeriesDataset2 transform(final TimeSeriesDataset2 input) { if (!(input instanceof TimeSeriesDataset2)) { throw new IllegalArgumentException("This method only supports TimeSeriesDatasets"); } if (input.isEmpty()) { throw new IllegalArgumentException("This method can not work with an empty dataset."); } if (!this.fitted) { throw new NoneFittedFilterExeception("Fit() must be called before transform()"); } TimeSeriesDataset2 sAXTransformedDataset = new TimeSeriesDataset2(null, null, null); for (int matrix = 0; matrix < input.getNumberOfVariables(); matrix++) { double[][] newMatrix = new double[input.getNumberOfInstances()][this.wordLength]; for (int instance = 0; instance < input.getNumberOfInstances(); instance++) { double[] ppaOfInstance = this.paa.transform(input.getValues(matrix)[instance]); double[] tsasString = new double[this.wordLength]; double[] localLookupTable = this.lookuptable[matrix]; for (int i = 0; i < ppaOfInstance.length; i++) { double ppaValue = ppaOfInstance[i]; boolean valuefound = false; for (int j = 0; j < localLookupTable.length; j++) { if (ppaValue < localLookupTable[j]) { tsasString[i] = this.alphabet[j]; valuefound = true; } } if (!valuefound) { tsasString[i] = this.alphabet[this.alphabet.length - 1]; } } newMatrix[instance] = tsasString; } sAXTransformedDataset.add(newMatrix, null); } return sAXTransformedDataset; } @Override public void fit(final TimeSeriesDataset2 input) { if (!(input instanceof TimeSeriesDataset2)) { throw new IllegalArgumentException("This method only supports Timeseriesdatasets"); } if (input.isEmpty()) { throw new IllegalArgumentException("This method can not work with an empty dataset."); } double[][] maxAndMin = new double[2][input.getNumberOfVariables()]; this.ztransform.fitTransform(input); for (int matrix = 0; matrix < input.getNumberOfVariables(); matrix++) { double[] max = new double[input.getNumberOfInstances()]; double[] min = new double[input.getNumberOfInstances()]; for (int instance = 0; instance < input.getNumberOfInstances(); instance++) { max[instance] = Arrays.stream(input.getValues(matrix)[instance]).max().getAsDouble(); min[instance] = Arrays.stream(input.getValues(matrix)[instance]).min().getAsDouble(); } maxAndMin[0][matrix] = Arrays.stream(max).max().getAsDouble(); maxAndMin[1][matrix] = Arrays.stream(min).min().getAsDouble(); } // filling the lookuptable this.lookuptable = new double[input.getNumberOfVariables()][this.alphabet.length]; for (int matrix = 0; matrix < input.getNumberOfVariables(); matrix++) { double[] localMaxMin = new double[] { maxAndMin[0][matrix], maxAndMin[1][matrix] }; double totalsize = localMaxMin[0] - localMaxMin[1]; double stepsize = totalsize / this.alphabet.length; this.lookuptable[matrix][0] = localMaxMin[1] + stepsize; for (int i = 1; i < this.alphabet.length; i++) { this.lookuptable[matrix][i] = this.lookuptable[matrix][i - 1] + stepsize; } } this.fitted = true; } @Override public TimeSeriesDataset2 fitTransform(final TimeSeriesDataset2 input) { this.fit(input); return this.transform(input); } @Override public double[] transform(final double[] input) { throw new UnsupportedOperationException(); } @Override public void fit(final double[] input) { throw new UnsupportedOperationException(); } @Override public double[] fitTransform(final double[] input) { throw new UnsupportedOperationException(); } @Override public double[][] transform(final double[][] input) { throw new UnsupportedOperationException(); } @Override public void fit(final double[][] input) { throw new UnsupportedOperationException(); } @Override public double[][] fitTransform(final double[][] input) { throw new UnsupportedOperationException(); } }
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/filter/SFA.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception.NoneFittedFilterExeception; /** * @author Helen Beierling * c.f. p. 1511 p. 1510 "The BOSS is concerned with time series classification in the presence of noise" by Patrick Schäfer * This class combines the MCB of finding the bins for a given set of DFT coefficients and SFA * which selects the right letter for a DFT coefficient. */ public class SFA implements IFilter { private static final String MSG_NOEMPTYDS = "This method can not work with an empty dataset."; private static final String MSG_NOSINGLEINSTANCE = "To build a SFA word the full dataset has to be considerd therefore it is not reasonable in this context to perform this operation on a single Instance."; private double[] alphabet; private boolean meanCorrected; private boolean fitted = false; private boolean fittedMatrix = false; private TimeSeriesDataset2 dFTDataset = null; private double[][] dftMatrix = null; private int numberOfDesieredDFTCoefficients; private List<double[][]> lookupTable = new ArrayList<>(); private double[][] lookUpTableMatrix = null; private boolean rekursiv; public void setNumberOfDesieredDFTCoefficients(final int numberOfDesieredDFTCoefficients) { this.numberOfDesieredDFTCoefficients = numberOfDesieredDFTCoefficients; } public void disableRekursiv() { this.rekursiv = false; } public void enableRekursiv() { this.rekursiv = true; } public SFA(final double[] alphabet, final int wordLength) { this.alphabet = alphabet; // The wordlength must be even this.numberOfDesieredDFTCoefficients = wordLength / 2; } @Override public TimeSeriesDataset2 transform(final TimeSeriesDataset2 input) { if (input.isEmpty()) { throw new IllegalArgumentException(MSG_NOEMPTYDS); } if (!this.fitted) { throw new NoneFittedFilterExeception("The filter must be fitted before it can transform."); } List<double[][]> sfaDataset = new ArrayList<>(); // calculate SFA words for every instance and its DFT coefficients for (int matrix = 0; matrix < this.dFTDataset.getNumberOfVariables(); matrix++) { double[][] sfaWords = new double[this.dFTDataset.getNumberOfInstances()][this.numberOfDesieredDFTCoefficients * 2]; for (int instance = 0; instance < this.dFTDataset.getNumberOfInstances(); instance++) { for (int entry = 0; entry < this.numberOfDesieredDFTCoefficients * 2; entry++) { double elem = this.dFTDataset.getValues(matrix)[instance][entry]; // get the lookup table for DFT values of the instance double[] lookup = this.lookupTable.get(matrix)[entry]; // if the DFT coefficient is smaller than the first or larger than the last // or it lays on the border give it first, last or second ,penultimate if (elem < lookup[0]) { sfaWords[instance][entry] = this.alphabet[0]; } else if (elem == lookup[0]) { sfaWords[instance][entry] = this.alphabet[1]; } else if (elem > lookup[this.alphabet.length - 2]) { sfaWords[instance][entry] = this.alphabet[this.alphabet.length - 1]; } else if (elem == lookup[this.alphabet.length - 2]) { sfaWords[instance][entry] = this.alphabet[this.alphabet.length - 1]; } // get alphabet letter for every non extreme coefficient else { for (int i = 1; i < lookup.length; i++) { if (elem <= lookup[i]) { if (elem < lookup[i]) { sfaWords[instance][entry] = this.alphabet[i]; } else if (elem == lookup[i]) { sfaWords[instance][entry] = this.alphabet[i + 1]; } break; } } } } } sfaDataset.add(sfaWords); } return new TimeSeriesDataset2(sfaDataset, null, null); } @Override public void fit(final TimeSeriesDataset2 input) { if (input.isEmpty()) { throw new IllegalArgumentException(MSG_NOEMPTYDS); } if (this.alphabet.length == 0) { throw new IllegalArgumentException("The alphabet size can not be zero."); } this.lookupTable.clear(); DFT dftFilter = new DFT(); dftFilter.setMeanCorrected(this.meanCorrected); // calculates the number of DFT coefficents with wordlength as number of desired DFT coefficients dftFilter.setNumberOfDisieredCoefficients(this.numberOfDesieredDFTCoefficients); if (!this.rekursiv) { this.dFTDataset = dftFilter.fitTransform(input); } else { // Only works for sliding windows. However it is normally used for SFA. this.dFTDataset = dftFilter.rekursivDFT(input); } for (int matrix = 0; matrix < this.dFTDataset.getNumberOfVariables(); matrix++) { // for each part of every coefficient calculate the bins for the alphabet (number of bins == number of letters) double[][] lookUpTable = new double[this.numberOfDesieredDFTCoefficients * 2][this.alphabet.length - 1]; for (int coeficient = 0; coeficient < this.numberOfDesieredDFTCoefficients * 2; coeficient++) { // get the columns of the DFT dataset double[] toBin = new double[input.getNumberOfInstances()]; for (int instances = 0; instances < this.dFTDataset.getNumberOfInstances(); instances++) { toBin[instances] = this.dFTDataset.getValues(matrix)[instances][coeficient]; } // Sort ascending // If the number of instances is equal to the number of bins the breakpoints are set to this values Arrays.sort(toBin); if (toBin.length == this.alphabet.length - 1) { lookUpTable[coeficient] = Arrays.copyOf(toBin, this.alphabet.length - 1); } // If the number of instances is greater than the number of bins then the breakpoints are set // in the way that all coefficients are spread equally over the bins else { int splitValue = (int) Math.round(toBin.length / (double) this.alphabet.length); for (int alphabetLetter = 1; alphabetLetter < this.alphabet.length; alphabetLetter++) { lookUpTable[coeficient][alphabetLetter - 1] = toBin[alphabetLetter * splitValue]; } } } this.lookupTable.add(lookUpTable); } this.fitted = true; } @Override public TimeSeriesDataset2 fitTransform(final TimeSeriesDataset2 input) { this.fit(input); return this.transform(input); } @Override public double[] transform(final double[] input) { throw new UnsupportedOperationException(MSG_NOSINGLEINSTANCE); } @Override public void fit(final double[] input) { throw new UnsupportedOperationException(MSG_NOSINGLEINSTANCE); } @Override public double[] fitTransform(final double[] input) { throw new UnsupportedOperationException(MSG_NOSINGLEINSTANCE); } @Override public double[][] transform(final double[][] input) { if (input.length == 0) { throw new IllegalArgumentException(MSG_NOEMPTYDS); } if (!this.fittedMatrix) { throw new NoneFittedFilterExeception("The filter must be fitted before it can transform."); } double[][] sfaMatrix = new double[this.dftMatrix.length][this.numberOfDesieredDFTCoefficients * 2]; for (int instance = 0; instance < this.dftMatrix.length; instance++) { for (int entry = 0; entry < this.numberOfDesieredDFTCoefficients * 2; entry++) { double elem = this.dftMatrix[instance][entry]; // get the lookup table for DFT values of the instance double[] lookup = this.lookUpTableMatrix[entry]; // if the DFT coefficient is smaller than the first or larger than the last // or it lays on the border give it first, last or second ,penultimate if (elem < lookup[0]) { sfaMatrix[instance][entry] = this.alphabet[0]; } if (elem == lookup[0]) { sfaMatrix[instance][entry] = this.alphabet[1]; } if (elem > lookup[this.alphabet.length - 2]) { sfaMatrix[instance][entry] = this.alphabet[this.alphabet.length - 1]; } if (elem == lookup[this.alphabet.length - 2]) { sfaMatrix[instance][entry] = this.alphabet[this.alphabet.length - 1]; } // get alphabet letter for every non extrem coefficient else { for (int i = 1; i < lookup.length - 2; i++) { if (elem > lookup[i]) { sfaMatrix[instance][entry] = this.alphabet[i]; } if (elem == lookup[i]) { sfaMatrix[instance][entry] = this.alphabet[i + 1]; } } } } } return sfaMatrix; } /* * Can not be called in the fit dataset method because it needs its own DFT- * Filter and for the dataset an overall Filter is needed. */ @Override public void fit(final double[][] input) { if (input.length == 0) { throw new IllegalArgumentException(MSG_NOEMPTYDS); } if (this.alphabet.length == 0) { throw new IllegalArgumentException("The alphabet size can not be zero."); } DFT dftFilterMatrix = new DFT(); // calculates the number of DFT coefficents with wordlength as number of desired DFT coefficients dftFilterMatrix.setNumberOfDisieredCoefficients(this.numberOfDesieredDFTCoefficients); if (!this.rekursiv) { this.dftMatrix = dftFilterMatrix.fitTransform(input); } else { this.dftMatrix = dftFilterMatrix.rekursivDFT(input); } this.lookUpTableMatrix = new double[this.numberOfDesieredDFTCoefficients * 2][this.alphabet.length - 1]; for (int coeficient = 0; coeficient < this.numberOfDesieredDFTCoefficients * 2; coeficient++) { // get the columns of the DFT dataset double[] toBin = new double[input.length]; for (int instances = 0; instances < input.length; instances++) { toBin[instances] = this.dftMatrix[instances][coeficient]; } // Sort ascending // If the number of instances is equal to the number of bins the breakpoints are set to this values Arrays.sort(toBin); if (toBin.length == this.alphabet.length - 1) { this.lookUpTableMatrix[coeficient] = Arrays.copyOf(toBin, this.alphabet.length - 1); } // If the number of instances is greater than the number of bins then the breakpoints are set // in the way that all coefficients are spread equally over the bins else { int splitValue = (int) Math.round(toBin.length / (double) this.alphabet.length); for (int alphabetLetter = 0; alphabetLetter < this.alphabet.length - 1; alphabetLetter++) { this.lookUpTableMatrix[coeficient][alphabetLetter] = toBin[alphabetLetter + splitValue]; } } } this.fittedMatrix = true; } @Override public double[][] fitTransform(final double[][] input) { this.fit(input); return this.transform(input); } }
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/filter/SlidingWindowBuilder.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter; import java.util.ArrayList; import java.util.Arrays; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception.NoneFittedFilterExeception; /** * @author Helen Beierling * This class cuts an instance or a set of instances into a number of smaller instances which are * typically saved in an matrix per instance and the matrices in a list. * c.f. p.1508 "The BOSS is concerned with time series classification in the presence of noise" by Patrick Schaefer */ public class SlidingWindowBuilder implements IFilter { private static final String MSG_SPECIALFIT = "This is done by the special fit and transform because this mehtod must return a new dataset not a double array."; private boolean fitted = false; private boolean fittedMatrix = false; private int defaultWindowSize = 20; private ArrayList<double[][]> blownUpDataset = new ArrayList<>(); private double[][] blownUpMatrix = null; public void setDefaultWindowSize(final int defaultWindowSize) { this.defaultWindowSize = defaultWindowSize; } public int getDefaultWindowSize() { return this.defaultWindowSize; } @Override public TimeSeriesDataset2 transform(final TimeSeriesDataset2 input) { if (input.isEmpty()) { throw new IllegalArgumentException("The input dataset can not be empty"); } if (!this.fitted) { throw new NoneFittedFilterExeception("The fit method must be called before transformning"); } return new TimeSeriesDataset2(this.blownUpDataset, null, null); } @Override // Results in a list of matrices where each instance has its own matrix. // Therefore the structure of the matrices are lost if this method is used. public void fit(final TimeSeriesDataset2 input) { for (int matrix = 0; matrix < input.getNumberOfVariables(); matrix++) { ArrayList<double[][]> newMatrices = new ArrayList<>(); for (double[] instance : input.getValues(matrix)) { double[][] newMatrix = new double[(instance.length - this.defaultWindowSize)][this.defaultWindowSize]; for (int entry = 0; entry < instance.length - this.defaultWindowSize; entry++) { double[] tmp = Arrays.copyOfRange(instance, entry, entry + this.defaultWindowSize); newMatrix[entry] = tmp; } newMatrices.add(newMatrix); } this.blownUpDataset = newMatrices; } this.fitted = true; } /** * This is an extra fit method because it does not return a double[] array even though it gets * a double [] as input as it would be defined in the . * * @param instance that has to be transformed * @return the tsdataset that results from one instance which consists of * one matrix with each row represents one part of the instance from i to i+ window length for i < n- window length */ public TimeSeriesDataset2 specialFitTransform(final double[] instance) { if (instance.length == 0) { throw new IllegalArgumentException("The input instance can not be empty"); } if (instance.length < this.defaultWindowSize) { throw new IllegalArgumentException("The input instance can not be smaller than the windowsize"); } double[][] newMatrix = new double[instance.length - this.defaultWindowSize + 1][this.defaultWindowSize]; for (int entry = 0; entry <= instance.length - (this.defaultWindowSize); entry++) { newMatrix[entry] = Arrays.copyOfRange(instance, entry, entry + this.defaultWindowSize); } ArrayList<double[][]> newDataset = new ArrayList<>(); newDataset.add(newMatrix); return new TimeSeriesDataset2(newDataset); } @Override public TimeSeriesDataset2 fitTransform(final TimeSeriesDataset2 input) { this.fit(input); return this.transform(input); } /* * This operation is unsupported because it would result in one stream of new instances in one array. */ @Override public double[] transform(final double[] input) { throw new UnsupportedOperationException(MSG_SPECIALFIT); } /* * This method is unsupported because the corresponding transform operation is * not useful */ @Override public void fit(final double[] input) { throw new UnsupportedOperationException(MSG_SPECIALFIT); } @Override public double[] fitTransform(final double[] input) { throw new UnsupportedOperationException(MSG_SPECIALFIT); } @Override public double[][] transform(final double[][] input) { if (input.length == 0) { throw new IllegalArgumentException("The input matrix can not be empty"); } if (!this.fittedMatrix) { throw new NoneFittedFilterExeception("The fit mehtod must be called before transformning"); } return this.blownUpMatrix; } @Override // Does not return a list of matrices but a bigger matrix where the new created instances are getting stacked // if there is a instance of size n than the first n-window length rows are the sliced instance. public void fit(final double[][] input) { if (input.length == 0) { throw new IllegalArgumentException("The input matrix can not be empty"); } // This is the buffer for the new matrix that gets created from a single instance. this.blownUpMatrix = new double[input.length * (input[0].length - this.defaultWindowSize)][this.defaultWindowSize]; for (int instance = 0; instance < input.length; instance++) { for (int entry = 0; entry < input[instance].length - this.defaultWindowSize; entry++) { // Every entry in the new matrix is equal to a copy of the original instance from // entry i to entry i plus window length. this.blownUpMatrix[instance + (entry)] = Arrays.copyOfRange(input[instance], entry, entry + this.defaultWindowSize); } } this.fittedMatrix = true; } @Override public double[][] fitTransform(final double[][] input) { this.fit(input); return this.transform(input); } }
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/filter/ZTransformer.java
/** * */ package ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter; import java.util.ArrayList; import java.util.List; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception.NoneFittedFilterExeception; /** * @author Helen Beierling * This class normalizes the mean of an instance to be zero and the deviation to be one. * s.https://jmotif.github.io/sax-vsm_site/morea/algorithm/znorm.html * one loop: https://www.strchr.com/standard_deviation_in_one_pass?allcomments=1 * * XXX: Duplicates functionality in ai.libs.jaicore.basic.transform.vector.ZTransform */ public class ZTransformer extends AFilter { private double mean; private double deviation; private List<double[][]> ztransformedDataset = new ArrayList<>(); // To get a unbiased estimate for the variance the intermediated results are // divided by n-1 instead of n(Number of samples of Population) private boolean basselCorrected = true; private boolean fitted = false; private boolean fittedInstance = false; private boolean fittedMatrix = false; public void setBasselCorrected(final boolean basselCorrected) { this.basselCorrected = basselCorrected; } /* (non-Javadoc) * @see jaicore.ml.tsc.filter.IFilter#transform(jaicore.ml.core.dataset.IDataset) */ @Override public TimeSeriesDataset2 transform(final TimeSeriesDataset2 input) { if (input.isEmpty()) { throw new IllegalArgumentException("This method can not work with an empty dataset."); } if (!this.fitted) { throw new NoneFittedFilterExeception("The fit method must be called before the transform method."); } for (int matrix = 0; matrix < input.getNumberOfVariables(); matrix++) { this.ztransformedDataset.add(this.fitTransform(input.getValues(matrix))); this.fittedMatrix = false; } this.fitted = false; return new TimeSeriesDataset2(this.ztransformedDataset); } @Override public void fit(final TimeSeriesDataset2 input) { if (input.isEmpty()) { throw new IllegalArgumentException("This method can not work with an empty dataset."); } this.fitted = true; } @Override public TimeSeriesDataset2 fitTransform(final TimeSeriesDataset2 input) { this.fit(input); return this.transform(input); } @Override public double[] transform(final double[] input) { if (!this.fittedInstance) { throw new NoneFittedFilterExeception("The fit method must be called before the transfom method is called"); } if (input.length == 0) { throw new IllegalArgumentException("The to transform instance can not be empty"); } double[] ztransform = new double[input.length]; for (int entry = 0; entry < input.length; entry++) { if (this.deviation != 0) { ztransform[entry] = (entry - this.mean) / this.deviation; } } this.fittedInstance = false; return ztransform; } @Override public void fit(final double[] input) { double sumSq = 0.0; double sumMean = 0.0; double numberOfEntrys = input.length; if (numberOfEntrys == 0) { throw new IllegalArgumentException("The to transform instance can not be empty."); } for (int entry = 0; entry < input.length; entry++) { sumSq = sumSq + Math.pow(input[entry], 2); sumMean = sumMean + input[entry]; } this.mean = sumMean / numberOfEntrys; double variance = (1 / numberOfEntrys) * (sumSq) - Math.pow(this.mean, 2); if (this.basselCorrected) { double tmp = (numberOfEntrys / (numberOfEntrys - 1)); this.deviation = Math.sqrt(tmp * variance); } else { this.deviation = Math.sqrt(variance); } this.fittedInstance = true; } @Override public double[] fitTransform(final double[] input) { this.fit(input); return this.transform(input); } @Override public double[][] transform(final double[][] input) { if (!this.fittedMatrix) { throw new NoneFittedFilterExeception("The fit method must be called first."); } double[][] ztransformedMatrix = new double[input.length][input[0].length]; for (int instance = 0; instance < input.length; instance++) { ztransformedMatrix[instance] = this.fitTransform(input[instance]); this.fittedInstance = false; } this.fittedMatrix = false; return ztransformedMatrix; } @Override public void fit(final double[][] input) { this.fittedMatrix = true; } @Override public double[][] fitTransform(final double[][] input) { this.fit(input); return this.transform(input); } }
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/learner/ASimplifiedTSCLearningAlgorithm.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner; import java.util.Iterator; import java.util.NoSuchElementException; import org.api4.java.algorithm.events.IAlgorithmEvent; import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig; import ai.libs.jaicore.basic.algorithm.AAlgorithm; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; public abstract class ASimplifiedTSCLearningAlgorithm<T, C extends ASimplifiedTSClassifier<T>> extends AAlgorithm<TimeSeriesDataset2, C> { protected ASimplifiedTSCLearningAlgorithm(final IOwnerBasedAlgorithmConfig config, final C classifier, final TimeSeriesDataset2 input) { super(config, input); this.classifier = classifier; // this is the classifier that is being trained (and outputted in the end) } /** * The model which is maintained during algorithm calls */ private final C classifier; public C getClassifier() { return this.classifier; } /** * {@inheritDoc} */ @Override public void registerListener(final Object listener) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ @Override public IAlgorithmEvent nextWithException() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ @Override public Iterator<IAlgorithmEvent> iterator() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ @Override public boolean hasNext() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ @Override public IAlgorithmEvent next() { throw new NoSuchElementException("Cannot enumerate on this algorithm"); } /** * {@inheritDoc} */ @Override public void cancel() { throw new UnsupportedOperationException(); } }
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/learner/ASimplifiedTSClassifier.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner; import java.util.List; import org.api4.java.ai.ml.core.exception.PredictionException; import org.api4.java.ai.ml.core.exception.TrainingException; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.ClassMapper; /** * Simplified batch-learning time series classifier which can be trained and * used as a predictor. Uses <code>algorithm</code> to train the model * parameters (if necessary). * * @author Julian Lienen * */ public abstract class ASimplifiedTSClassifier<T> { /** * Class mapper object used to encode and decode predicted values if String * values are used as classes. Can be null if the predicted values are not * mapped to String values. */ protected ClassMapper classMapper; /** * Variable indicating whether the classifier has been trained. */ protected boolean trained; public ASimplifiedTSClassifier() { } /** * Performs a prediction based on the given univariate double[] instance * representation and returns the result. * * @param univInstance Univariate instance given by a double vector of time * series values used for the prediction * @return Returns the result of the prediction * @throws PredictionException If something fails during the prediction process. */ public abstract T predict(final double[] univInstance) throws PredictionException; /** * Performs a prediction based on the given multivariate list of double[] * instance representation and returns the result. * * @param multivInstance Multivariate instance given by a list of multiple * double[] time series used for the prediction * @return Returns the result of the prediction * @throws PredictionException If something fails during the prediction process. */ public T predict(final List<double[]> multivInstance) throws PredictionException { throw new PredictionException("Can't predict on multivariate data yet."); } /** * Performs predictions based on the given instances in the given dataset. * * @param dataset The {@link TimeSeriesDataset2} for which predictions should be * made. * @return Returns the result of the predictions * @throws PredictionException If something fails during the prediction process */ public abstract List<T> predict(final TimeSeriesDataset2 dataset) throws PredictionException; public abstract <U extends ASimplifiedTSClassifier<T>> ASimplifiedTSCLearningAlgorithm<T, U> getLearningAlgorithm(final TimeSeriesDataset2 dataset); /** * Trains the simplified time series classifier model using the given * {@link TimeSeriesDataset2}. * * @param dataset The {@link TimeSeriesDataset2} which should be used for the * training. * @throws TrainingException If something fails during the training process. */ public final void train(final TimeSeriesDataset2 dataset) throws InterruptedException, TrainingException { // Set model which is trained ASimplifiedTSCLearningAlgorithm<T, ? extends ASimplifiedTSClassifier<T>> algorithm = this.getLearningAlgorithm(dataset); // Set input data from which the model should learn try { // Train algorithm.call(); this.trained = true; } catch (InterruptedException e) { throw e; } catch (Exception e) { throw new TrainingException("Could not train model " + this.getClass().getSimpleName(), e); } } /** * Getter for the property <code>classMapper</code>. * * @return Returns the actual class mapper or null if no mapper is stored */ public ClassMapper getClassMapper() { return this.classMapper; } /** * Setter for the property <code>classMapper</code>. * * @param classMapper The class mapper to be set */ public void setClassMapper(final ClassMapper classMapper) { this.classMapper = classMapper; } /** * @return the trained */ public boolean isTrained() { return this.trained; } protected double[][] checkWhetherPredictionIsPossible(final TimeSeriesDataset2 dataset) throws PredictionException { // Parameter checks. if (!this.isTrained()) { throw new PredictionException("Model has not been built before!"); } if (dataset == null || dataset.isEmpty()) { throw new IllegalArgumentException("Dataset to be predicted must not be null or empty!"); } double[][] testInstances = dataset.getValuesOrNull(0); if (testInstances == null) { throw new PredictionException("Can't predict on empty dataset."); } return testInstances; } }
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/learner/ATSCAlgorithm.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset; /** * Abstract algorithm class which is able to take {@link TimeSeriesDataset} * objects and builds {@link ATimeSeriesClassificationModel} instances specified by the generic * parameter <CLASSIFIER>. * * @author Julian Lienen * * @param <Y> * The type of the target that the <CLASSIFIER> to be trained * @param <V> * The value type of the target that the <CLASSIFIER> to be trained * predicts. * @param <D> * The type of the time series data set used to learn from and * predict batches. * @param <C> * The time series classifier which is modified and returned as * algorithm result. */ public abstract class ATSCAlgorithm<Y, D extends TimeSeriesDataset, C extends ATimeSeriesClassificationModel<Y, D>> implements IAlgorithm<TimeSeriesDataset, C> { /** * The model which is maintained during algorithm calls */ protected C model; /** * The {@link TimeSeriesDataset} object used for maintaining the * <code>model</code>. */ protected D input; /** * Setter for the model to be maintained. * * @param model * The {@link ATimeSeriesClassificationModel} model which is maintained during * algorithm calls. */ @SuppressWarnings("unchecked") public <T extends ATimeSeriesClassificationModel<Y, D>> void setModel(final T model) { this.model = (C) model; } /** * Setter for the data set input used during algorithm calls. * * @param input * The {@link TimeSeriesDataset} object (or a subtype) used for the * model maintenance */ public void setInput(final D input) { this.input = input; } /** * Getter for the data set input used during algorithm calls. */ @Override public D getInput() { return this.input; } }
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/learner/ATimeSeriesClassificationModel.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassificationPredictionBatch; import org.api4.java.ai.ml.core.exception.TrainingException; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.ITimeSeriesInstance; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset; import ai.libs.jaicore.ml.core.learner.ASupervisedLearner; /** * Time series classifier which can be trained and used as a predictor. Uses * <code>algorithm</code> to train the model parameters (if necessary). * * @author Julian Lienen * * @param <L> * The attribute type of the target. * @param <V> * The value type of the target attribute. * @param <D> * The type of the time series data set used to learn from and * predict batches. */ public abstract class ATimeSeriesClassificationModel<L, D extends TimeSeriesDataset> extends ASupervisedLearner<ITimeSeriesInstance, D, ISingleLabelClassification, ISingleLabelClassificationPredictionBatch> { /** * The algorithm object used for the training of the classifier. */ protected ATSCAlgorithm<L, D, ? extends ATimeSeriesClassificationModel<L, D>> algorithm; /** * Constructor for a time series classifier. * * @param algorithm * The algorithm object used for the training of the classifier */ public ATimeSeriesClassificationModel(final ATSCAlgorithm<L, D, ? extends ATimeSeriesClassificationModel<L, D>> algorithm) { this.algorithm = algorithm; } /** * {@inheritDoc ABatchLearner#train(jaicore.ml.core.dataset.IDataset)} */ @Override public void fit(final D dataset) throws InterruptedException, TrainingException { // Set model which is trained this.algorithm.setModel(this); // Set input data from which the model should learn this.algorithm.setInput(dataset); try { // Train this.algorithm.call(); } catch (InterruptedException e) { throw e; } catch (Exception e) { throw new TrainingException("Could not train model " + this.getClass().getSimpleName(), e); } } /** * Getter for the model's training algorithm object. * * @return The model's training algorithm */ public ATSCAlgorithm<L, D, ? extends ATimeSeriesClassificationModel<L, D>> getAlgorithm() { return this.algorithm; } /** * Sets the training algorithm for the classifier. * * @param algorithm * The algorithm object used to maintain the model's parameters. */ public void setAlgorithm(final ATSCAlgorithm<L, D, ? extends ATimeSeriesClassificationModel<L, D>> algorithm) { this.algorithm = algorithm; } }
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/learner/BOSSClassifier.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.aeonbits.owner.ConfigCache; import org.api4.java.ai.ml.core.exception.PredictionException; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter.SFA; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter.SlidingWindowBuilder; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter.ZTransformer; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner.BOSSLearningAlgorithm.IBossAlgorithmConfig; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.HistogramBuilder; /** * @author Helen Beierling * This class predicts labels for instances by cutting the instance into pieces and calculate for every piece the DFT values and * assigns them to the corresponding letter to form the SFA words of that piece and afterwards creating a histogram for which the * distance is calculated to all histograms of the training data and the label of the nearest one is returned as prediction. */ public class BOSSClassifier extends ASimplifiedTSClassifier<Integer> { private TimeSeriesDataset2 trainingData; // --------------------------------------------------------------- // All variables needed for the to predict instance and for the BOSS Algorithm or calculated by it . private final IBossAlgorithmConfig config; private List<Map<Integer, Integer>> univirateHistograms; // --------------------------------------------------------------- // All needed for every predict. private SlidingWindowBuilder slide = new SlidingWindowBuilder(); private HistogramBuilder histoBuilder = new HistogramBuilder(); private ZTransformer znorm = new ZTransformer(); public BOSSClassifier(final int windowLength, final int alphabetSize, final double[] alphabet, final int wordLength, final boolean meanCorrected) { this.config = ConfigCache.getOrCreate(IBossAlgorithmConfig.class); this.config.setProperty(IBossAlgorithmConfig.K_WINDOW_SIZE, "" + windowLength); this.config.setProperty(IBossAlgorithmConfig.K_ALPHABET_SIZE, "" + alphabetSize); this.config.setProperty(IBossAlgorithmConfig.K_ALPHABET, "" + alphabet); this.config.setProperty(IBossAlgorithmConfig.K_WORDLENGTH, "" + wordLength); this.config.setProperty(IBossAlgorithmConfig.K_MEANCORRECTED, "" + meanCorrected); this.slide.setDefaultWindowSize(this.config.windowSize()); } public BOSSClassifier(final IBossAlgorithmConfig config) { this.config = config; // This is the same window size as used for the training samples this.slide.setDefaultWindowSize(config.windowSize()); } public List<Map<Integer, Integer>> getUnivirateHistograms() { return this.univirateHistograms; } public void setTrainingData(final TimeSeriesDataset2 trainingData) { this.trainingData = trainingData; } public void setHistogramUnivirate(final List<Map<Integer, Integer>> histograms) { this.univirateHistograms = histograms; } @Override public Integer predict(final double[] univInstance) throws PredictionException { SFA sfa = new SFA(this.config.alphabet(), this.config.wordLength()); // create windows for test instance an there for a small dataset with // windows as instances. TimeSeriesDataset2 tmp = this.slide.specialFitTransform(univInstance); // need to call a new fit for each predict because each window gets z normalized by its own. // c.f.p. 1509 "The BOSS is concerned with time series classification in the presence of noise by Patrick Schaefer" for (int instance = 0; instance < tmp.getValues(0).length; instance++) { tmp.getValues(0)[instance] = this.znorm.fitTransform(tmp.getValues(0)[instance]); } TimeSeriesDataset2 tmpznormedsfaTransformed = sfa.fitTransform(tmp); Map<Integer, Integer> histogram = this.histoBuilder.histogramForInstance(tmpznormedsfaTransformed); // Calculate distance for all histograms for all instances in the training set. // Remember index of histogram with minimum distance in list because it corresponds to the // instance that produced that histogram with minimum distance. int indexOFminDistInstance = 0; double minDist = Double.MAX_VALUE; for (int i = 0; i < this.univirateHistograms.size(); i++) { double dist = this.getBossDistance(histogram, this.univirateHistograms.get(i)); if (dist < minDist) { minDist = dist; indexOFminDistInstance = i; } } // return the target of that instance that had the minimum distance. return this.trainingData.getTargets()[indexOFminDistInstance]; } @Override public Integer predict(final List<double[]> multivInstance) throws PredictionException { // The BOSS classifier only supports predictions for univariate instances. throw new UnsupportedOperationException("The BOSS classifier is a univariat classifer"); } @Override public List<Integer> predict(final TimeSeriesDataset2 dataset) throws PredictionException { // For a list of instances a list of predictions are getting created and the list is than returned. List<Integer> predictions = new ArrayList<>(); for (double[][] matrix : dataset.getValueMatrices()) { for (double[] instance : matrix) { predictions.add(this.predict(instance)); } } return predictions; } /** * @param a The distance starting point histogram. * @param b The distance destination histogram. * @return The distance between Histogram a and b. * * The distance itself is calculated as 0 if the word does appear in "b" but not in "a" and * if the word exists in "a" but not in "b" it is the word count of "a" squared. For the "normal" case * where the word exists in "a" and "b" the distance is word count of "a" minus "b" and the result gets * squared for each word and summed up over the whole histogram. * Therefore the two histograms do not need to be of the same size and the distance of "a" to "b" must not * be equal to the distance of "b" to "a". * c.f. p. 1516 "The BOSS is concerned with time series classification in the presence of noise by Patrick Schaefer" */ private double getBossDistance(final Map<Integer, Integer> a, final Map<Integer, Integer> b) { double result = 0; for (Entry<Integer, Integer> entry : a.entrySet()) { int key = entry.getKey(); int val = entry.getValue(); if (b.containsKey(key)) { result += (Math.pow(val - (double) b.get(key), 2)); } else { result += Math.pow(val, 2); } } return result; } @Override public BOSSLearningAlgorithm getLearningAlgorithm(final TimeSeriesDataset2 dataset) { return new BOSSLearningAlgorithm(this.config, this, dataset); } }
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/learner/BOSSEnsembleClassifier.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.api4.java.ai.ml.core.exception.PredictionException; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; /* This class is just a sketch for the BOSS ensemble classifier it assumes that the grid * of the parameters window size and word length is already computed * and that the best ones according to a percentage of the best combination are already chosen * and put into the delivered HashMap. * cf.p.1520 * "The BOSS is concerned with time series classification in the presence of noise by Patrick Schaefer" */ public class BOSSEnsembleClassifier extends ASimplifiedTSClassifier<Integer> { private ArrayList<BOSSClassifier> ensemble = new ArrayList<>(); public BOSSEnsembleClassifier(final Map<Integer, Integer> windowLengthsandWordLength, final int alphabetSize, final double[] alphabet, final boolean meanCorrected) { for (Entry<Integer, Integer> lengthPair : windowLengthsandWordLength.entrySet()) { this.ensemble.add(new BOSSClassifier(lengthPair.getKey(), alphabetSize, alphabet, lengthPair.getValue(), meanCorrected)); } } /* * In the empirical observations as described in paper: * "The BOSS is concerned with time series classification in the presence of noise Patrick Schaefer" p.1519, * showed that most of * the time a alphabet size of 4 works best. */ public BOSSEnsembleClassifier(final Map<Integer, Integer> windowLengthsandWordLength, final double[] alphabet, final boolean meanCorrected) { this(windowLengthsandWordLength, 4, alphabet, meanCorrected); } @Override public Integer predict(final double[] univInstance) throws PredictionException { HashMap<Integer, Integer> labelCount = new HashMap<>(); int votedLabel = 0; int maxNumberOfVotes = Integer.MIN_VALUE; for (BOSSClassifier boss : this.ensemble) { Integer label = boss.predict(univInstance); if (labelCount.containsKey(label)) { labelCount.put(label, labelCount.get(label) + 1); if (labelCount.get(label) > maxNumberOfVotes) { votedLabel = label; maxNumberOfVotes = labelCount.get(label); } } else { labelCount.put(label, 1); if (labelCount.get(label) > maxNumberOfVotes) { votedLabel = label; maxNumberOfVotes = labelCount.get(label); } } } return votedLabel; } @Override public Integer predict(final List<double[]> multivInstance) throws PredictionException { throw new UnsupportedOperationException("The BOSS-Esamble Classifier is an univirate classifier."); } @Override public List<Integer> predict(final TimeSeriesDataset2 dataset) throws PredictionException { ArrayList<Integer> predicts = new ArrayList<>(); for (double[][] matrix : dataset.getValueMatrices()) { for (double[] instance : matrix) { predicts.add(this.predict(instance)); } } return predicts; } @Override public <U extends ASimplifiedTSClassifier<Integer>> ASimplifiedTSCLearningAlgorithm<Integer, U> getLearningAlgorithm(final TimeSeriesDataset2 dataset) { throw new UnsupportedOperationException(); } }
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/learner/BOSSLearningAlgorithm.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.api4.java.algorithm.events.IAlgorithmEvent; import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter.SFA; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter.SlidingWindowBuilder; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.filter.ZTransformer; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.HistogramBuilder; /** * @author Helen Beierling * This class calculates all needed informations for the BOSS classifier. A fitted SFA and all * histograms for the training samples. */ public class BOSSLearningAlgorithm extends ASimplifiedTSCLearningAlgorithm<Integer, BOSSClassifier> { public interface IBossAlgorithmConfig extends IOwnerBasedAlgorithmConfig { public static final String K_WINDOW_SIZE = "boss.windowsize"; public static final String K_ALPHABET_SIZE = "boss.alphabetsize"; public static final String K_ALPHABET = "boss.alphabet"; public static final String K_WORDLENGTH = "boss.wordlength"; public static final String K_MEANCORRECTED = "boss.meancorrected"; /** * The size of the sliding window that is used over each instance and splits it into multiple * smaller instances. */ @Key(K_WINDOW_SIZE) public int windowSize(); /** * The alphabet size determines the number of Bins for the SFA Histograms. Four was determined empirical * as an optimal value for the alphabet size. * cf.p. 1519 "The BOSS is concerned with time series classification in the presence of noise by Patrick Schäfer" * */ @Key(K_ALPHABET_SIZE) @DefaultValue("4") public int alphabetSize(); /** * The alphabet consists of doubles representing letters and defines each word. */ @Key(K_ALPHABET) public double[] alphabet(); /** * The word length determines the number of used DFT-coefficients. Where the DFT-coefficients are * half the word length. */ @Key(K_WORDLENGTH) public int wordLength(); /** * If mean corrected is set to true than the first DFT coefficient is dropped to normalize the mean. * c.f.p. 1519 "The BOSS is concerned with time series classification in the presence of noise by Patrick Schäfer" */ @Key(K_MEANCORRECTED) public boolean meanCorrected(); } /** * The list contains the list of Histograms in which every matrix of the multivariate dataset results in. */ private List<ArrayList<HashMap<Integer, Integer>>> multivirateHistograms = new ArrayList<>(); /** * Constians the histograms of one matrix for each instance one. Where the keys are the words which are double value * sequences converted to an integer hash code and the values are the corresponding word counts. */ private ArrayList<HashMap<Integer, Integer>> histograms = new ArrayList<>(); // This class assumes that the optimal proportion of word length to window size is determined elsewhere and the corresponding // drop of SFA words. public BOSSLearningAlgorithm(final IBossAlgorithmConfig config, final BOSSClassifier classifier, final TimeSeriesDataset2 data) { super(config, classifier, data); } @Override public IAlgorithmEvent nextWithException() { return null; } @Override public BOSSClassifier call() { this.multivirateHistograms.clear(); IBossAlgorithmConfig config = (IBossAlgorithmConfig) this.getConfig(); HistogramBuilder histoBuilder = new HistogramBuilder(); SFA sfa = new SFA(config.alphabet(), config.wordLength()); /* calculates the lookup table for the alphabet for the whole input dataset. */ SlidingWindowBuilder slide = new SlidingWindowBuilder(); slide.setDefaultWindowSize(config.windowSize()); TimeSeriesDataset2 data = this.getInput(); for (int matrix = 0; matrix < data.getNumberOfVariables(); matrix++) { this.histograms.clear(); for (int instance = 0; instance < data.getNumberOfInstances(); instance++) { /* * Every instance results in an own histogram there for has its own HashMap of * the the from key: word value: count of word. */ /* * By the special fit transform an instance is transformed to a dataset. This * is done because every instance creates a list of new smaller instances when * split into sliding windows. */ TimeSeriesDataset2 tmp = slide.specialFitTransform(data.getValues(matrix)[instance]); /* The from one instance resulting dataset is z-normalized. */ ZTransformer znorm = new ZTransformer(); for (int i = 0; i < tmp.getValues(0).length; i++) { tmp.getValues(0)[i] = znorm.fitTransform(tmp.getValues(0)[i]); } // The SFA words for that dataset are computed using the precomputed MCB quantisation intervals TimeSeriesDataset2 tmpTransformed = sfa.fitTransform(tmp); // The occurring SFA words of the instance are getting counted with a parallel numerosity reduction. Map<Integer, Integer> histogram = histoBuilder.histogramForInstance(tmpTransformed); // Each instance in the dataset has its own histogram so the original dataset results in a list of histograms. this.histograms.add(new HashMap<>(histogram)); } // In the case of a multivariate dataset each matrix would have a list of histograms which than results // in a list of lists of histograms. // The Boss classifier however can not handle multivariate datasets. this.multivirateHistograms.add(this.histograms); } // In the end all calculated and needed algortihms are set for the classifier. BOSSClassifier model = this.getClassifier(); model.setTrainingData(this.getInput()); return model; } }
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/learner/package-info.java
/** * This package contains classifier implementations for time series classification problems. */ /** * @author Julian * */ package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/learner
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/learner/neighbors/NearestNeighborClassifier.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner.neighbors; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.PriorityQueue; import org.aeonbits.owner.ConfigCache; import org.api4.java.ai.ml.core.exception.PredictionException; import org.api4.java.common.metric.IDistanceMetric; import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig; 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.learner.ASimplifiedTSClassifier; /** * K-Nearest-Neighbor classifier for time series. * * Given an integer <code>k</code>, a distance measure <code>d</code> ({@link ai.libs.jaicore.ml.tsc.distances}), a training set of time series <code>TRAIN = {(x, y)}</code> and a test time series <code>T</code> (or a set of test time * series). * <p> * The set of k nearest neighbors <code>NN</code> for <code>T</code> is a subset (or equal) of <code>TRAIN</code> with cardinality <code>k</code> such that for all <code>(T, S)</code> with <code>S</code> in <code>TRAIN\NN</code> holds * <code>d(S, T) >= max_{T' in NN} d(S, T')</code>. * </p> * From the labels of the instances in <code>NN</code> the label for <code>T</code> is aggregated, e.g. via majority vote. * * @author fischor */ public class NearestNeighborClassifier extends ASimplifiedTSClassifier<Integer> { /** * Votes types that describe how to aggregate the prediciton for a test instance on its nearest neighbors found. */ public enum VoteType { /** * Majority vote with @see NearestNeighborClassifier#voteMajority. */ MAJORITY, /** * Weighted stepwise vote with @see NearestNeighborClassifier#voteWeightedStepwise. */ WEIGHTED_STEPWISE, /** * Weighted proportional to distance vote with @see NearestNeighborClassifier#voteWeightedProportionalToDistance. */ WEIGHTED_PROPORTIONAL_TO_DISTANCE, } /** * Comparator class for the nearest neighbor priority queues, used for the nearest neighbor calculation. Sorts pairs of <code>(Integer: targetClass, Double: distance)</code> for nearest neigbors by distance ascending. */ private static class NearestNeighborComparator implements Comparator<Pair<Integer, Double>> { @Override public int compare(final Pair<Integer, Double> o1, final Pair<Integer, Double> o2) { return -1 * o1.getY().compareTo(o2.getY()); } } /** * Singleton comparator instance for the nearest neighbor priority queues, used for the nearest neighbor calculation. */ protected static final NearestNeighborComparator nearestNeighborComparator = new NearestNeighborComparator(); /** Number of neighbors. */ private int k; /** Distance measure. */ private IDistanceMetric distanceMeasure; /** Type of the voting. */ private VoteType voteType; /** Value matrix containing the time series instances. Set by algorithm. */ protected double[][] values; /** * Timestamp matrix containing the timestamps of the instances. Set by the algorihm. */ protected double[][] timestamps; /** Target values for the instances. Set by the algorithm. */ protected int[] targets; /** * Creates a k nearest neighbor classifier. * * @param k * The number of nearest neighbors. * @param distanceMeasure * Distance measure for calculating the distances between every pair of train and test instances. * @param voteType * Vote type to use to aggregate the the classes of the the k nearest neighbors into a single class prediction. */ public NearestNeighborClassifier(final int k, final IDistanceMetric distanceMeasure, final VoteType voteType) { // Parameter checks. if (distanceMeasure == null) { throw new IllegalArgumentException("Distance measure must not be null"); } if (voteType == null) { throw new IllegalArgumentException("Vote type must not be null."); } // Set attributes. this.distanceMeasure = distanceMeasure; this.k = k; this.voteType = voteType; } /** * Creates a k nearest neighbor classifier using majority vote. * * @param k * The number of nearest neighbors. * @param distanceMeasure * Distance measure for calculating the distances between every pair of train and test instances. */ public NearestNeighborClassifier(final int k, final IDistanceMetric distanceMeasure) { this(k, distanceMeasure, VoteType.MAJORITY); } /** * Creates a 1 nearest neighbor classifier using majority vote. * * @param distanceMeasure * Distance measure for calculating the distances between every pair of train and test instances. */ public NearestNeighborClassifier(final IDistanceMetric distanceMeasure) { this(1, distanceMeasure, VoteType.MAJORITY); } /** * Predicts on univariate instance. * * @param univInstance * The univariate instance. * @return Class prediction for the instance. */ @Override public Integer predict(final double[] univInstance) throws PredictionException { if (univInstance == null) { throw new IllegalArgumentException("Instance to predict must not be null."); } return this.calculatePrediction(univInstance); } /** * Predicts on a dataset. * * @param dataset * The dataset. * @return List of class predicitons for each instance of the dataset. */ @Override public List<Integer> predict(final TimeSeriesDataset2 dataset) throws PredictionException { double[][] testInstances = this.checkWhetherPredictionIsPossible(dataset); // Calculate predictions. ArrayList<Integer> predictions = new ArrayList<>(dataset.getNumberOfInstances()); for (double[] testInstance : testInstances) { int prediction = this.calculatePrediction(testInstance); predictions.add(prediction); } return predictions; } /** * Calculates predicition on a single test instance. * * @param testInstance * The test instance (not null assured within class). * @return */ protected int calculatePrediction(final double[] testInstance) { // Determine the k nearest neighbors for the test instance. PriorityQueue<Pair<Integer, Double>> nearestNeighbors = this.calculateNearestNeigbors(testInstance); // Vote on determined neighbors to create prediction and return prediction. return this.vote(nearestNeighbors); } /** * Determine the k nearest neighbors for a test instance. * * @param testInstance * The time series to determine the k nearest neighbors for. * @return Queue of the k nearest neighbors as pairs (class, distance). */ protected PriorityQueue<Pair<Integer, Double>> calculateNearestNeigbors(final double[] testInstance) { int numberOfTrainInstances = this.values.length; // Priority queue of (class, distance)-pairs for nearest neigbors, sorted by // distance ascending. PriorityQueue<Pair<Integer, Double>> nearestNeighbors = new PriorityQueue<>(nearestNeighborComparator); // Calculate the k nearest neighbors. for (int i = 0; i < numberOfTrainInstances; i++) { double d = this.distanceMeasure.distance(testInstance, this.values[i]); Pair<Integer, Double> neighbor = new Pair<>(this.targets[i], d); nearestNeighbors.add(neighbor); if (nearestNeighbors.size() > this.k) { nearestNeighbors.poll(); } } return nearestNeighbors; } /** * Performs a vote on the nearest neighbors found. Delegates the vote according to the vote type. * * @param nearestNeighbors * Priority queue of (class, distance)-pairs for nearest neigbors, sorted by distance ascending. (Not null assured within class) * @return Result of the vote, i.e. the predicted class. */ protected int vote(final PriorityQueue<Pair<Integer, Double>> nearestNeighbors) { switch (this.voteType) { case WEIGHTED_STEPWISE: return this.voteWeightedStepwise(nearestNeighbors); case WEIGHTED_PROPORTIONAL_TO_DISTANCE: return this.voteWeightedProportionalToDistance(nearestNeighbors); case MAJORITY: default: return this.voteMajority(nearestNeighbors); } } /** * Performs a vote with stepwise weights 1, 2, .., k on the set nearest neighbors found. * * @param nearestNeighbors * Priority queue of (class, distance)-pairs for nearest neigbors, sorted by distance ascending. (Not null assured within class) * @return Result of the vote, i.e. the predicted class. */ protected int voteWeightedStepwise(final PriorityQueue<Pair<Integer, Double>> nearestNeighbors) { // Voting. HashMap<Integer, Integer> votes = new HashMap<>(); int weight = 1; while (!nearestNeighbors.isEmpty()) { Pair<Integer, Double> neighbor = nearestNeighbors.poll(); Integer targetClass = neighbor.getX(); Integer currentVotesOnTargetClass = votes.get(targetClass); if (currentVotesOnTargetClass == null) { votes.put(targetClass, weight); } else { votes.put(targetClass, currentVotesOnTargetClass + weight); } weight++; } // Return most voted target (class that got most weights). Integer maxWeightOfVotes = Integer.MIN_VALUE; Integer mostVotedTargetClass = -1; for (Entry<Integer, Integer> entry : votes.entrySet()) { int targetClass = entry.getKey(); int votedWeightsForTargetClass = entry.getValue(); if (votedWeightsForTargetClass > maxWeightOfVotes) { maxWeightOfVotes = votedWeightsForTargetClass; mostVotedTargetClass = targetClass; } } return mostVotedTargetClass; } /** * Performs a vote with weights proportional to the distance on the set nearest neighbors found. * * @param nearestNeighbors * Priority queue of (class, distance)-pairs for nearest neigbors, sorted by distance ascending. (Not null assured within class) * @return Result of the vote, i.e. the predicted class. */ protected int voteWeightedProportionalToDistance(final PriorityQueue<Pair<Integer, Double>> nearestNeighbors) { // Voting. HashMap<Integer, Double> votes = new HashMap<>(); for (Pair<Integer, Double> neighbor : nearestNeighbors) { Integer targetClass = neighbor.getX(); double distance = neighbor.getY(); Double currentVotesOnTargetClass = votes.get(targetClass); if (currentVotesOnTargetClass == null) { votes.put(targetClass, 1.0 / distance); } else { votes.put(targetClass, currentVotesOnTargetClass + 1.0 / distance); } } // Return most voted target (class that got most weights). Double maxWeightOfVotes = Double.MIN_VALUE; Integer mostVotedTargetClass = -1; for (Entry<Integer, Double> entry : votes.entrySet()) { int targetClass = entry.getKey(); double votedWeightsForTargetClass = entry.getValue(); if (votedWeightsForTargetClass > maxWeightOfVotes) { maxWeightOfVotes = votedWeightsForTargetClass; mostVotedTargetClass = targetClass; } } return mostVotedTargetClass; } /** * Performs a majority vote on the set nearest neighbors found. * * @param nearestNeighbors * Priority queue of (class, distance)-pairs for nearest neigbors, sorted by distance ascending. (Not null assured within class) * @return Result of the vote, i.e. the predicted class. */ protected int voteMajority(final PriorityQueue<Pair<Integer, Double>> nearestNeighbors) { // Voting. HashMap<Integer, Integer> votes = new HashMap<>(); for (Pair<Integer, Double> neighbor : nearestNeighbors) { Integer targetClass = neighbor.getX(); Integer currentVotesOnTargetClass = votes.get(targetClass); if (currentVotesOnTargetClass == null) { votes.put(targetClass, 1); } else { votes.put(targetClass, currentVotesOnTargetClass + 1); } } // Return most voted target. Integer maxNumberOfVotes = Integer.MIN_VALUE; Integer mostVotedTargetClass = -1; for (Entry<Integer, Integer> entry : votes.entrySet()) { int targetClass = entry.getKey(); int numberOfVotesForTargetClass = entry.getValue(); if (numberOfVotesForTargetClass > maxNumberOfVotes) { maxNumberOfVotes = numberOfVotesForTargetClass; mostVotedTargetClass = targetClass; } } return mostVotedTargetClass; } /** * Sets the value matrix. * * @param values */ protected void setValues(final double[][] values) { if (values == null) { throw new IllegalArgumentException("Values must not be null"); } this.values = values; } /** * Sets the timestamps. * * @param timestamps */ protected void setTimestamps(final double[][] timestamps) { this.timestamps = timestamps; } /** * Sets the targets. * * @param targets */ protected void setTargets(final int[] targets) { if (targets == null) { throw new IllegalArgumentException("Targets must not be null"); } this.targets = targets; } /** * Getter for the k value, @see #k. * * @return k */ public int getK() { return this.k; } /** * Getter for the vote type. @see #voteType. * * @return The vote type. */ public VoteType getVoteType() { return this.voteType; } /** * Getter for the distance measure. @see #distanceMeasure. * * @return */ public IDistanceMetric getDistanceMeasure() { return this.distanceMeasure; } @Override public NearestNeighborLearningAlgorithm getLearningAlgorithm(final TimeSeriesDataset2 dataset) { return new NearestNeighborLearningAlgorithm(ConfigCache.getOrCreate(IOwnerBasedAlgorithmConfig.class), this, dataset); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/learner
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/learner/neighbors/NearestNeighborLearningAlgorithm.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner.neighbors; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner.ASimplifiedTSCLearningAlgorithm; /** * Training algorithm for the nearest neighbors classifier. * * This algorithm just delegates the value matrix, timestamps and targets to the * classifier. * * @author fischor */ public class NearestNeighborLearningAlgorithm extends ASimplifiedTSCLearningAlgorithm<Integer, NearestNeighborClassifier> { protected NearestNeighborLearningAlgorithm(final IOwnerBasedAlgorithmConfig config, final NearestNeighborClassifier classifier, final TimeSeriesDataset2 input) { super(config, classifier, input); } @Override public NearestNeighborClassifier call() throws AlgorithmException { TimeSeriesDataset2 dataset = this.getInput(); if (dataset == null) { throw new AlgorithmException("No input data set."); } if (dataset.isMultivariate()) { throw new UnsupportedOperationException("Multivariate datasets are not supported."); } // Retrieve data from dataset. double[][] values = dataset.getValuesOrNull(0); // Check data. if (values == null) { throw new AlgorithmException("Empty input data set."); } int[] targets = dataset.getTargets(); if (targets == null) { throw new AlgorithmException("Empty targets."); } // Update model. NearestNeighborClassifier model = this.getClassifier(); model.setValues(values); model.setTimestamps(dataset.getTimestampsOrNull(0)); model.setTargets(targets); return model; } @Override public IAlgorithmEvent nextWithException() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/learner
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/learner/neighbors/ShotgunEnsembleClassifier.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner.neighbors; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.aeonbits.owner.ConfigCache; import org.api4.java.ai.ml.core.exception.PredictionException; import org.api4.java.common.metric.IDistanceMetric; import ai.libs.jaicore.basic.metric.ShotgunDistance; 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.learner.ASimplifiedTSClassifier; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner.neighbors.ShotgunEnsembleLearnerAlgorithm.IShotgunEnsembleLearnerConfig; /** * Implementation of Shotgun Ensemble Classifier as published in "Towards Time * Series Classfication without Human Preprocessing" by Patrick Schäfer (2014). * * The Shotgun Classifier is based 1-NN and the Shotgun Distance. * * The Shotgun Ensemble Algorithm {@link ShotgunEnsembleAlgoritm} determines for * specific window lengths the number of correct predicitions on the training * data using the leave-one-out technique. The <code>bestScore</code> is the * highest number of correct predicitions over all window lengths. Given a * <code>factor</code> in <code>(0,1]</code>, the window lengths where * <code>correct * factor > bestScore</code> are used in an ensemble of Shotgun * Classifiers to create an overall predicition. * * @author fischor */ public class ShotgunEnsembleClassifier extends ASimplifiedTSClassifier<Integer> { /** * Factor used to determine whether or not to include a window length into the * overall predicition. */ protected double factor; /** Value matrix containing the time series instances. Set by algorithm. */ protected double[][] values; /** Target values for the instances. Set by the algorithm. */ protected int[] targets; /** * The nearest neighbor classifier used for prediction. Set by the algorithm. */ protected NearestNeighborClassifier nearestNeighborClassifier; /** * The Shotgun Distance used by the {@link #nearestNeighborClassifier}. Set by * the algorithm. */ protected ShotgunDistance shotgunDistance; /** * Holds pairs of (number of correct predictions, window length) obtained in * training phase. */ protected ArrayList<Pair<Integer, Integer>> windows; /** * The best score. States the highest number of correct predicitions for every * window length used in training phase (leave-one-out). */ protected int bestScore; private final IShotgunEnsembleLearnerConfig config; /** * Creates a Shotgun Ensemble classifier. * * @param algorithm The training algorithm. * @param factor Factor used to determine whether or not to include a window * length into the overall predicition. */ public ShotgunEnsembleClassifier(final int minWindowLength, final int maxWindowLength, final boolean meanNormalization, final double factor) { super(); this.config = ConfigCache.getOrCreate(IShotgunEnsembleLearnerConfig.class); if (minWindowLength < 1) { throw new IllegalArgumentException("The parameter minWindowLength must be greater equal to 1."); } if (maxWindowLength < 1) { throw new IllegalArgumentException("The parameter maxWindowLength must be greater equal to 1."); } if (minWindowLength > maxWindowLength) { throw new IllegalAccessError("The parameter maxWindowsLength must be greater equal to parameter minWindowLength"); } this.config.setProperty(IShotgunEnsembleLearnerConfig.K_WINDOWLENGTH_MIN, "" + minWindowLength); this.config.setProperty(IShotgunEnsembleLearnerConfig.K_WINDOWLENGTH_MAX, "" + maxWindowLength); this.config.setProperty(IShotgunEnsembleLearnerConfig.K_MEANNORMALIZATION, "" + meanNormalization); if ((factor <= 0) || (factor > 1)) { throw new IllegalArgumentException("The parameter factor must be in (0,1]"); } this.factor = factor; } /** * Calculates predicitions for a test instance using 1NN with Shotgun Distance * and different window lengths. * * @param testInstance The test instance. * @return Map of (window length, prediciton) pairs. * @throws PredictionException */ protected Map<Integer, Integer> calculateWindowLengthPredictions(final double[] testInstance) throws PredictionException { // Map holding (windowLength, predicition for instance) pairs. Map<Integer, Integer> windowLengthPredicitions = new HashMap<>(); for (Pair<Integer, Integer> window : this.windows) { int correct = window.getX(); int windowLength = window.getY(); this.shotgunDistance.setWindowLength(windowLength); if (correct > this.bestScore * this.factor) { int prediction = this.nearestNeighborClassifier.predict(testInstance); windowLengthPredicitions.put(windowLength, prediction); } } return windowLengthPredicitions; } /** * Returns the most frequent predicition given a Map of (window length, * prediciton) pairs. * * @param windowLengthPredicitions Map of (window length, prediciton) pairs. * @return The most frequent predicition. */ protected Integer mostFrequentLabelFromWindowLengthPredicitions(final Map<Integer, Integer> windowLengthPredicitions) { // Count frequency for labels. Map<Integer, Integer> labelFrequencyMap = new HashMap<>(); for (Integer label : windowLengthPredicitions.values()) { if (labelFrequencyMap.containsKey(label)) { labelFrequencyMap.put(label, labelFrequencyMap.get(label) + 1); } else { labelFrequencyMap.put(label, 1); } } // Return most frequent label. int topFrequency = -1; int mostFrequentLabel = 0; for (Entry<Integer, Integer> entry : labelFrequencyMap.entrySet()) { int label = entry.getKey(); int labelFrequency = entry.getValue(); if (labelFrequency > topFrequency) { topFrequency = labelFrequency; mostFrequentLabel = label; } } return mostFrequentLabel; } /** * Calculates predicitions for a test dataset using 1NN with Shotgun Distance * and different window lengths. * * @param dataset The dataset to predict for. * @return Map of (window length, predicitions) pairs. * @throws PredictionException */ protected Map<Integer, List<Integer>> calculateWindowLengthPredictions(final TimeSeriesDataset2 dataset) throws PredictionException { // Map holding (windowLength, prediction for dataset) pairs. Map<Integer, List<Integer>> windowLengthPredicitions = new HashMap<>(); for (Pair<Integer, Integer> window : this.windows) { int correct = window.getX(); int windowLength = window.getY(); this.shotgunDistance.setWindowLength(windowLength); if (correct > this.bestScore * this.factor) { List<Integer> predictions = this.nearestNeighborClassifier.predict(dataset); windowLengthPredicitions.put(windowLength, predictions); } } return windowLengthPredicitions; } /** * Returns for each instance the most frequent predicitions as contained in a * Map of (window length, list of prediciton for each instance) pairs. * * @param windowLengthPredicitions Map of (window length, list of prediciton for * each instance) pairs. * @return The most frequent predicition for each instace. */ protected List<Integer> mostFrequentLabelsFromWindowLengthPredicitions(final Map<Integer, List<Integer>> windowLengthPredicitions) { // Return most frequent label for each instance. int numberOfInstances = windowLengthPredicitions.values().iterator().next().size(); List<Integer> predicitions = new ArrayList<>(numberOfInstances); for (int i = 0; i < numberOfInstances; i++) { // Map holding (windowLength, predicition for instance) pairs. Map<Integer, Integer> windowLabelsForInstance = new HashMap<>(); for (Entry<Integer, List<Integer>> entry : windowLengthPredicitions.entrySet()) { int windowLength = entry.getKey(); int predictionForWindowLength = entry.getValue().get(i); windowLabelsForInstance.put(windowLength, predictionForWindowLength); } int mostFrequentLabelForInstance = this.mostFrequentLabelFromWindowLengthPredicitions(windowLabelsForInstance); predicitions.add(mostFrequentLabelForInstance); } return predicitions; } /** * Predicts on univariate instance. * * @param univInstance The univariate instance. * @return Class prediction for the instance. */ @Override public Integer predict(final double[] univInstance) throws PredictionException { if (univInstance == null) { throw new IllegalArgumentException("Instance to predict must not be null."); } Map<Integer, Integer> windowLengthPredicitions = this.calculateWindowLengthPredictions(univInstance); return this.mostFrequentLabelFromWindowLengthPredicitions(windowLengthPredicitions); } /** * Predicts on a dataset. * * @param dataset The dataset. * @return List of class predicitons for each instance of the dataset. */ @Override public List<Integer> predict(final TimeSeriesDataset2 dataset) throws PredictionException { this.checkWhetherPredictionIsPossible(dataset); Map<Integer, List<Integer>> windowLengthPredicitions = this.calculateWindowLengthPredictions(dataset); return this.mostFrequentLabelsFromWindowLengthPredicitions(windowLengthPredicitions); } /** * Sets the value matrix. * * @param values */ protected void setValues(final double[][] values) { if (values == null) { throw new IllegalArgumentException("Values must not be null"); } this.values = values; } /** * Sets the targets. * * @param targets */ protected void setTargets(final int[] targets) { if (targets == null) { throw new IllegalArgumentException("Targets must not be null"); } this.targets = targets; } /** * Sets the windows and also retreives and sets the @see #bestScore from these * windows. * * @param windows @see #windows */ protected void setWindows(final ArrayList<Pair<Integer, Integer>> windows) { this.windows = windows; // Best score. int tBestScore = -1; for (Pair<Integer, Integer> window : windows) { int correct = window.getX(); if (correct > tBestScore) { tBestScore = correct; } } this.bestScore = tBestScore; } /** * Sets the nearest neighbor classifier, {@link #nearestNeighborClassifier}. * * @param nearestNeighborClassifier */ protected void setNearestNeighborClassifier(final NearestNeighborClassifier nearestNeighborClassifier) { IDistanceMetric distanceMeasure = nearestNeighborClassifier.getDistanceMeasure(); if (!(distanceMeasure instanceof ShotgunDistance)) { throw new IllegalArgumentException("The nearest neighbor classifier must use a ShotgunDistance as dsitance measure."); } else { this.shotgunDistance = (ShotgunDistance) distanceMeasure; } this.nearestNeighborClassifier = nearestNeighborClassifier; } @Override public ShotgunEnsembleLearnerAlgorithm getLearningAlgorithm(final TimeSeriesDataset2 dataset) { return new ShotgunEnsembleLearnerAlgorithm(this.config, this, dataset); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/learner
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/learner/neighbors/ShotgunEnsembleLearnerAlgorithm.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.learner.neighbors; import java.util.ArrayList; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig; import ai.libs.jaicore.basic.metric.ShotgunDistance; 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.learner.ASimplifiedTSCLearningAlgorithm; /** * Implementation of Shotgun Ensemble Algorihm as published in "Towards Time * Series Classfication without Human Preprocessing" by Patrick Schäfer (2014). * * Given a maximal window length <code>maxWindowLength</code> and a minumum * window length <code>minWindowLength</code>, the Shotgun Ensemble algorithm * determines for each of the window lengths form <code>maxWindowLength</code> * downto <code>minWindowLength</code> the number of correct predicitions on the * training data using the leave-one-out technique. * * @author fischor */ public class ShotgunEnsembleLearnerAlgorithm extends ASimplifiedTSCLearningAlgorithm<Integer, ShotgunEnsembleClassifier> { public interface IShotgunEnsembleLearnerConfig extends IOwnerBasedAlgorithmConfig { public static final String K_WINDOWLENGTH_MIN = "windowlength.min"; public static final String K_WINDOWLENGTH_MAX = "windowlength.max"; public static final String K_MEANNORMALIZATION = "meannormalization"; @Key(K_WINDOWLENGTH_MIN) public int windowSizeMin(); @Key(K_WINDOWLENGTH_MAX) public int windowSizeMax(); @Key(K_MEANNORMALIZATION) @DefaultValue("false") public boolean meanNormalization(); } public ShotgunEnsembleLearnerAlgorithm(final IShotgunEnsembleLearnerConfig config, final ShotgunEnsembleClassifier classifier, final TimeSeriesDataset2 dataset) { super(config, classifier, dataset); } @Override public IAlgorithmEvent nextWithException() { throw new UnsupportedOperationException(); } @Override public IShotgunEnsembleLearnerConfig getConfig() { return (IShotgunEnsembleLearnerConfig) super.getConfig(); } @Override public ShotgunEnsembleClassifier call() throws AlgorithmException { TimeSeriesDataset2 dataset = this.getInput(); if (dataset == null) { throw new AlgorithmException("No input data set."); } if (dataset.isMultivariate()) { throw new UnsupportedOperationException("Multivariate datasets are not supported."); } // Retrieve data from dataset. double[][] values = dataset.getValuesOrNull(0); // Check data. if (values == null) { throw new AlgorithmException("Empty input data set."); } int[] targets = dataset.getTargets(); if (targets == null) { throw new AlgorithmException("Empty targets."); } // Holds pairs of (number of correct predictions, window length). ArrayList<Pair<Integer, Integer>> scores = new ArrayList<>(); for (int windowLength = this.getConfig().windowSizeMax(); windowLength >= this.getConfig().windowSizeMin(); windowLength--) { int correct = 0; // 1-NN with Leave-One-Out CV. ShotgunDistance shotgunDistance = new ShotgunDistance(windowLength, this.getConfig().meanNormalization()); for (int i = 0; i < values.length; i++) { // Predict for i-th instance. double minDistance = Double.MAX_VALUE; int instanceThatMinimizesDistance = -1; for (int j = 0; j < values.length; j++) { if (i != j) { double distance = shotgunDistance.distance(values[i], values[j]); if (distance < minDistance) { minDistance = distance; instanceThatMinimizesDistance = j; } } } // Check, if Leave-One-Out prediction for i-th was correct. if (targets[i] == targets[instanceThatMinimizesDistance]) { correct++; } } scores.add(new Pair<>(correct, windowLength)); } // Update model. NearestNeighborClassifier nearestNeighborClassifier = new NearestNeighborClassifier(new ShotgunDistance(this.getConfig().windowSizeMax(), this.getConfig().meanNormalization())); try { nearestNeighborClassifier.train(dataset); } catch (Exception e) { throw new AlgorithmException("Cant train nearest neighbor classifier.", e); } ShotgunEnsembleClassifier model = this.getClassifier(); model.setWindows(scores); model.setNearestNeighborClassifier(nearestNeighborClassifier); return model; } }
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/model/INDArrayTimeseries.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.model; import org.api4.java.ai.ml.core.dataset.schema.attribute.ITimeseries; import org.nd4j.linalg.api.ndarray.INDArray; public interface INDArrayTimeseries extends ITimeseries<INDArray> { public int length(); public double[] getPoint(); }
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/model/NDArrayTimeseries.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.model; import org.nd4j.linalg.api.ndarray.INDArray; import ai.libs.jaicore.basic.sets.ElementDecorator; public class NDArrayTimeseries extends ElementDecorator<INDArray> implements INDArrayTimeseries { public NDArrayTimeseries(final INDArray element) { super(element); } @Override public INDArray getValue() { return this.getElement(); } @Override public int length() { return (int) this.getElement().length(); } @Override public double[] getPoint() { return this.getElement().toDoubleVector(); } }
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/model/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.classification.singlelabel.timeseries.model;
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/quality/FStat.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.quality; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; /** * F-Stat quality measure performing a analysis of variance according to chapter * 3.2 of the original paper. It analyzes the ratio of the variability between * the group of instances within a class to the variability within the class * groups. * * @author Julian Lienen * */ public class FStat implements IQualityMeasure { /** * Generated serial version UID. */ private static final long serialVersionUID = 6991529180002046551L; /** * {@inheritDoc} */ @Override public double assessQuality(final List<Double> distances, final int[] classValues) { // Order class distances HashMap<Integer, List<Double>> classDistances = new HashMap<>(); for (int i = 0; i < distances.size(); i++) { if (!classDistances.containsKey(classValues[i])) { classDistances.put(classValues[i], new ArrayList<>()); } classDistances.get(classValues[i]).add(distances.get(i)); } int numClasses = classDistances.size(); // Calculate class and overall means HashMap<Integer, Double> classMeans = new HashMap<>(); for (Entry<Integer, List<Double>> entry : classDistances.entrySet()) { Integer clazz = entry.getKey(); classMeans.put(clazz, entry.getValue().stream().mapToDouble(a -> a).average().getAsDouble()); } double completeMean = distances.stream().mapToDouble(a -> a).average().getAsDouble(); double denominator = 0; // Calculate actual F score double result = 0; for (Entry<Integer, Double> entry : classMeans.entrySet()) { Integer clazz = entry.getKey(); double mean = entry.getValue(); result += Math.pow(mean - completeMean, 2); for (Double dist : classDistances.get(clazz)) { denominator += Math.pow(dist - mean, 2); } } result /= numClasses - 1; denominator /= distances.size() - numClasses; if (denominator == 0) { throw new IllegalArgumentException("Given arguments yield a 0 " + denominator); } result /= denominator; return result; } }
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/quality/IQualityMeasure.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.quality; import java.io.Serializable; import java.util.List; /** * Interface for a quality measure assessing distances of instances to a * shapelet given the corresponding class values. This functional interface is * used within the Shapelet Transform approach to assess shapelet candidates. * * @author Julian Lienen * */ public interface IQualityMeasure extends Serializable { /** * Computes a quality score based on the distances of each instance to the * shapelet and the corresponding <code>classValues</code>. * * @param distances * List of distances storing the distance of each instance to a * shapelet * @param classValues * The class values of the instances * @return Returns the calculated quality score */ public double assessQuality(final List<Double> distances, final int[] classValues); }
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/shapelets/Shapelet.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Implementation of a shapelet, i. e. a specific subsequence of a time series * representing a characteristic shape. * * @author Julian Lienen * */ public class Shapelet { /** * The data vector of the shapelet. */ private double[] data; /** * The start index of the shapelet in the origin time series. */ private int startIndex; /** * The length of the shapelet. */ private int length; /** * The instance index which is assigned when extracting the shapelet from a * given time series. */ private int instanceIndex; /** * The quality determined by an assessment function. */ private double determinedQuality; /** * Constructs a shapelet specified by the given parameters. * * @param data * See {@link Shapelet#data} * @param startIndex * See {@link Shapelet#startIndex} * @param length * See {@link Shapelet#length} * @param instanceIndex * See {@link Shapelet#instanceIndex} * @param determinedQuality * See {@link Shapelet#determinedQuality} */ public Shapelet(final double[] data, final int startIndex, final int length, final int instanceIndex, final double determinedQuality) { this.data = data; this.startIndex = startIndex; this.length = length; this.instanceIndex = instanceIndex; this.determinedQuality = determinedQuality; } /** * Constructs a shapelet specified by the given parameters. * * @param data * See {@link Shapelet#data} * @param startIndex * See {@link Shapelet#startIndex} * @param length * See {@link Shapelet#length} * @param instanceIndex * See {@link Shapelet#instanceIndex} */ public Shapelet(final double[] data, final int startIndex, final int length, final int instanceIndex) { this.data = data; this.startIndex = startIndex; this.length = length; this.instanceIndex = instanceIndex; } /** * Getter for {@link Shapelet#data}. * * @return Return the shapelet's data vector */ public double[] getData() { return this.data; } /** * Getter for {@link Shapelet#length}. * * @return Returns the shapelet's length */ public int getLength() { return this.length; } /** * Getter for {@link Shapelet#startIndex}. * * @return Returns the shapelet's start index. */ public int getStartIndex() { return this.startIndex; } /** * Getter for {@link Shapelet#instanceIndex}. * * @return Returns the shapelet's instance index. */ public int getInstanceIndex() { return this.instanceIndex; } /** * Getter for {@link Shapelet#determinedQuality}. * * @return Returns the shapelet's determined quality. */ public double getDeterminedQuality() { return this.determinedQuality; } /** * Setter for {@link Shapelet#determinedQuality}. * * @param determinedQuality * The new value to be set */ public void setDeterminedQuality(final double determinedQuality) { this.determinedQuality = determinedQuality; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(this.data); long temp; temp = Double.doubleToLongBits(this.determinedQuality); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + this.instanceIndex; result = prime * result + this.length; result = prime * result + this.startIndex; return result; } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (obj instanceof Shapelet) { Shapelet other = (Shapelet) obj; if (this.data == null && other.getData() != null || this.data != null && other.getData() == null) { return false; } return (this.data == null && other.getData() == null || Arrays.equals(this.data, other.getData())) && this.length == other.getLength() && this.determinedQuality == other.determinedQuality && this.instanceIndex == other.instanceIndex; } return super.equals(obj); } /** * {@inheritDoc} */ @Override public String toString() { return "Shapelet [data=" + Arrays.toString(this.data) + ", startIndex=" + this.startIndex + ", length=" + this.length + ", instanceIndex=" + this.instanceIndex + ", determinedQuality=" + this.determinedQuality + "]"; } /** * Function sorting a list of shapelets in place by the length (ascending). * * @param shapelets * The list to be sorted in place. */ public static void sortByLengthAsc(final List<Shapelet> shapelets) { shapelets.sort((s1, s2) -> Integer.compare(s1.getLength(), s2.getLength())); } /** * Returns the shapelet with the highest quality in the given list * <code>shapelets</code>. * * @param shapelets * The list of shapelets which is evaluated * @return Returns the shapelet with the highest determined quality */ public static Shapelet getHighestQualityShapeletInList(final List<Shapelet> shapelets) { return Collections.max(shapelets, (s1, s2) -> (-1) * Double.compare(s1.getDeterminedQuality(), s2.getDeterminedQuality())); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/shapelets
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/shapelets/search/AMinimumDistanceSearchStrategy.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets.search; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets.Shapelet; /** * Abstract class for minimum distance search strategies. Subclasses implement * functionality to find the minimum distance between a given {@link Shapelet} * object and a time series. * * @author Julian Lienen * */ public abstract class AMinimumDistanceSearchStrategy { /** * Indicator whether Bessel's correction should be used within any distance * calculation; */ protected boolean useBiasCorrection; /** * Constructor. * * @param useBiasCorrection * See {@link AMinimumDistanceSearchStrategy#useBiasCorrection} */ public AMinimumDistanceSearchStrategy(final boolean useBiasCorrection) { this.useBiasCorrection = useBiasCorrection; } /** * Function returning the minimum distance among all subsequences of the given * <code>timeSeries</code> to the <code>shapelet</code>'s data. * * @param shapelet * The shapelet to be compared to all subsequences * @param timeSeries * The time series which subsequences are compared to the shapelet's * data * @return Return the minimum distance among all subsequences */ public abstract double findMinimumDistance(final Shapelet shapelet, final double[] timeSeries); }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/shapelets
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/shapelets/search/EarlyAbandonMinimumDistanceSearchStrategy.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets.search; import java.util.List; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets.Shapelet; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.MathUtil; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.TimeSeriesUtil; /** * Class implementing a search strategy used for finding the minimum distance of * a {@link Shapelet} object to a time series. The approach uses early * abandoning as described in algorithm 2 in the paper 'Jason Lines, Luke M. * Davis, Jon Hills, and Anthony Bagnall. 2012. A shapelet transform for time * series classification. In Proceedings of the 18th ACM SIGKDD international * conference on Knowledge discovery and data mining (KDD '12). ACM, New York, * NY, USA, 289-297.'. * * @author Julian Lienen * */ public class EarlyAbandonMinimumDistanceSearchStrategy extends AMinimumDistanceSearchStrategy { /** * Standard constructor. * * @param useBiasCorrection * See {@link AMinimumDistanceSearchStrategy#useBiasCorrection} */ public EarlyAbandonMinimumDistanceSearchStrategy(final boolean useBiasCorrection) { super(useBiasCorrection); } /** * Optimized function returning the minimum distance among all subsequences of * the given <code>timeSeries</code> to the <code>shapelet</code>'s data. This * function implements the algorithm 2 mentioned in the original paper. It * performs the similarity search with online normalization and early abandon. * * @param shapelet * The shapelet to be compared to all subsequences * @param timeSeries * The time series which subsequences are compared to the shapelet's * data * @return Return the minimum distance among all subsequences */ @Override public double findMinimumDistance(final Shapelet shapelet, final double[] timeSeries) { double length = shapelet.getLength(); int m = timeSeries.length; // Order normalized shapelet values final double[] sPrimeVector = shapelet.getData(); final List<Integer> aVector = TimeSeriesUtil.sortIndexes(sPrimeVector, false); // descending final double[] fVector = TimeSeriesUtil.zNormalize(TimeSeriesUtil.getInterval(timeSeries, 0, shapelet.getLength()), this.useBiasCorrection); // Online normalization double p = 0; double q = 0; p = MathUtil.sum(TimeSeriesUtil.getInterval(timeSeries, 0, shapelet.getLength())); for (int i = 0; i < length; i++) { q += timeSeries[i] * timeSeries[i]; } double b = MathUtil.singleSquaredEuclideanDistance(sPrimeVector, fVector); for (int i = 1; i <= m - length; i++) { double ti = timeSeries[i - 1]; double til = timeSeries[i - 1 + shapelet.getLength()]; p -= ti; q -= ti * ti; p += til; q += til * til; double xBar = p / length; double s = q / (length) - xBar * xBar; if (s < 0.000000001d) { s = 0d; } else { s = Math.sqrt((this.useBiasCorrection ? (length / (length - 1d)) : 1d) * s); } int j = 0; double d = 0d; // Early abandon while (j < length && d < b) { final double normVal = (s == 0.0 ? 0d : (timeSeries[i + aVector.get(j)] - xBar) / s); final double diff = sPrimeVector[aVector.get(j)] - normVal; d += diff * diff; j++; } if (j == length && d < b) { b = d; } } return b / length; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/shapelets
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/shapelets/search/ExhaustiveMinimumDistanceSearchStrategy.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets.search; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets.Shapelet; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.MathUtil; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.util.TimeSeriesUtil; /** * Class implementing a search strategy used for finding the minimum distance of * a {@link Shapelet} object to a time series. The approach uses an exhaustive * search as described in the paper 'Jason Lines, Luke M. Davis, Jon Hills, and * Anthony Bagnall. 2012. A shapelet transform for time series classification. * In Proceedings of the 18th ACM SIGKDD international conference on Knowledge * discovery and data mining (KDD '12). ACM, New York, NY, USA, 289-297.'. * * @author Julian Lienen * */ public class ExhaustiveMinimumDistanceSearchStrategy extends AMinimumDistanceSearchStrategy { /** * Standard constructor. * * @param useBiasCorrection * See {@link AMinimumDistanceSearchStrategy#useBiasCorrection} */ public ExhaustiveMinimumDistanceSearchStrategy(final boolean useBiasCorrection) { super(useBiasCorrection); } /** * Function returning the minimum distance among all subsequences of the given * <code>timeSeries</code> to the <code>shapelet</code>'s data. * * @param shapelet * The shapelet to be compared to all subsequences * @param timeSeries * The time series which subsequences are compared to the shapelet's * data * @return Return the minimum distance among all subsequences */ @Override public double findMinimumDistance(final Shapelet shapelet, final double[] timeSeries) { final int l = shapelet.getLength(); final int n = timeSeries.length; double min = Double.MAX_VALUE; double[] normalizedShapeletData = shapelet.getData(); // Reference implementation uses i < n-l => Leads sometimes to a better performance for (int i = 0; i <= n - l; i++) { double tmpED = MathUtil.singleSquaredEuclideanDistance(normalizedShapeletData, TimeSeriesUtil.zNormalize(TimeSeriesUtil.getInterval(timeSeries, i, i + l), this.useBiasCorrection)); if (tmpED < min) { min = tmpED; } } return min / l; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/shapelets
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/singlelabel/timeseries/shapelets/search/package-info.java
/** * This package contains search strategies applied to * {@link ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets.Shapelet} objects. * * @author Julian Lienen * */ package ai.libs.jaicore.ml.classification.singlelabel.timeseries.shapelets.search;
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/ClassMapper.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.util; import java.util.List; /** * Class mapper used for predictions of String objects which are internally * predicted by time series classifiers as ints. * * @author Julian Lienen * */ public class ClassMapper { /** * Stored class values which indices are used to map integers to strings. */ private List<String> classValues; /** * Constructor using a list of String value to realize the mapping * * @param classValues * String values used for the mapping. The values are identified by * the given indices in the given list */ public ClassMapper(final List<String> classValues) { this.classValues = classValues; } /** * Maps a String value to an integer value based on the <code>value</code>'s * position in the <code>classValues</code>. * * @param value * The value to be looked up * @return Returns the mapped index or -1 if not stored */ public int map(final String value) { return this.classValues.indexOf(value); } /** * Maps an integer value to a string based on the position <code>index</code> in * the <code>classValues</code>. * * @param index * The index used for the lookup * @return Returns the given string at the position <code>index</code> */ public String map(final int index) { return this.classValues.get(index); } /** * Getter for the <code>classValues</code>. * * @return Returns the stored class values */ public List<String> getClassValues() { return classValues; } /** * Setter for the <code>classValues</code>. * * @param classValues * The class values to be set. */ public void setClassValues(final List<String> classValues) { this.classValues = classValues; } }
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/HistogramBuilder.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.util; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; /** * @author Helen Beierling * This class is used to compute Histograms for the found sfa words. * This includes a numerosity reduction. * (in form of double sequences which are used as key by using the Arrays class HashCode which are Integer). * c.f. p. 1514 "The BOSS is concerned with time series classification in the presence of noise" by Patrick Schaefer */ public class HistogramBuilder { private Map<Integer, Integer> histogram = new HashMap<>(); public Map<Integer, Integer> histogramForInstance(final TimeSeriesDataset2 blownUpSingleInstance) { this.histogram.clear(); double[] lastWord = null; // The blown up instance contains only one matrix. for (double[] d : blownUpSingleInstance.getValues(0)) { if (this.histogram.containsKey(Arrays.hashCode(d))) { /* * To the histogramm suczessiv duplicates are not added because of numerosity reduction. * c.f.p.1514 * "The BOSS is concerned with time series classification in the presence of noise by Patrick Schaefer" */ if (!Arrays.equals(d, lastWord)) { this.histogram.replace(Arrays.hashCode(d), this.histogram.get(Arrays.hashCode(d)) + 1); } } else { this.histogram.put(Arrays.hashCode(d), 1); } lastWord = d; } return this.histogram; } }
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/MathUtil.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.util; import java.util.stream.DoubleStream; /** * Utility class consisting of mathematical utility functions. * * @author Julian Lienen * */ public class MathUtil { private MathUtil() { /* no instantiation desired */ } /** * Function to calculate the sigmoid for the given value <code>z</code>. * * @param z * Parameter z * @return Returns the sigmoid for the parameter <code>z</code>. */ public static double sigmoid(final double z) { return 1 / (1 + Math.exp((-1) * z)); } /** * Sums the values of the given <code>array</code>. * * @param array * The array to be summed * @return Returns the sum of the values */ public static double sum(final double[] array) { return DoubleStream.of(array).sum(); } /** * Computes the single squared Euclidean distance between two vectors. * * @param vector1 * First argument vector * @param vector2 * Second argument vector * @return Returns the single squared Euclidean distance between two vectors */ public static double singleSquaredEuclideanDistance(final double[] vector1, final double[] vector2) { if (vector1.length != vector2.length) { throw new IllegalArgumentException("The lengths of of both vectors must match!"); } double distance = 0; for (int i = 0; i < vector1.length; i++) { distance += Math.pow(vector1[i] - vector2[i], 2); } return distance; } /** * Simple Manhattan distance (sum of the absolute differences between the * vectors' elements) implementation for arrays of Integer. * * @param a * First argument vector * @param b * Second argument vector * @return Returns the Manhattan distance of the two given vectors */ public static double intManhattanDistance(final int[] a, final int[] b) { double result = 0; for (int j = 0; j < a.length; j++) { result += Math.abs(a[j] - b[j]); } return result; } /** * Function calculating the mean of the interval [t1, t2 (inclusive)] of the * given <code>vector</code>. * * @param vector * Vector which is used for the calculation * @param t1 * Interval start * @param t2 * Interval end (inclusive) * @return Returns the mean of the vector's interval [t1, t2 (inclusive)] */ public static double mean(final double[] vector, final int t1, final int t2) { checkIntervalParameters(vector, t1, t2); double result = 0; for (int i = t1; i <= t2; i++) { result += vector[i]; } return result / (t2 - t1 + 1); } /** * Function calculating the standard deviation of the interval [t1, t2 * (inclusive)] of the given <code>vector</code>. * * @param vector * Vector which is used for the calculation * @param t1 * Interval start * @param t2 * Interval end (inclusive) * @param useBiasCorrection * Indicator whether the bias (Bessel's) correction should be used * @return Returns the standard deviation of the vector's interval [t1, t2 * (inclusive)] */ public static double stddev(final double[] vector, final int t1, final int t2, final boolean useBiasCorrection) { checkIntervalParameters(vector, t1, t2); if (t1 == t2) { return 0.0d; } double mean = mean(vector, t1, t2); double result = 0; for (int i = t1; i <= t2; i++) { result += Math.pow(vector[i] - mean, 2); } return Math.sqrt(result / (t2 - t1 + (useBiasCorrection ? 0 : 1))); } /** * Function calculating the slope of the interval [t1, t2 (inclusive)] of the * given <code>vector</code>. * * @param vector * Vector which is used for the calculation * @param t1 * Interval start * @param t2 * Interval end (inclusive) * @return Returns the slope of the vector's interval [t1, t2 (inclusive)] */ public static double slope(final double[] vector, final int t1, final int t2) { checkIntervalParameters(vector, t1, t2); if (t2 == t1) { return 0d; } double xx = 0; double x = 0; double xy = 0; double y = 0; for (int i = t1; i <= t2; i++) { x += i; y += vector[i]; xx += i * i; xy += i * vector[i]; } // Calculate slope int length = t2 - t1 + 1; double denominator = (length * xx - x * x); if (denominator == 0) { throw new IllegalArgumentException("Given arguments yield a 0 " + denominator); } return (length * xy - x * y) / denominator; } /** * Checks the parameters <code>t1</code> and </code>t2</code> for validity given * the <code>vector</code> * * @param vector * Value vector * @param t1 * Interval start * @param t2 * Interval end (inclusive) */ private static void checkIntervalParameters(final double[] vector, final int t1, final int t2) { if (t1 >= vector.length || t2 >= vector.length) { throw new IllegalArgumentException("Parameters t1 and t2 must be valid indices of the vector!"); } if (t2 < t1) { throw new IllegalArgumentException("End index t2 of the interval must be greater equals start index t1!"); } } /** * Calculates the index of the maximum value in the given <code>array</code> * (argmax). * * @param array * Array to be checked. Must not be null or empty * @return Returns the index of the maximum value */ public static int argmax(final int[] array) { if (array == null || array.length == 0) { throw new IllegalArgumentException("Given parameter 'array' must not be null or empty for argmax."); } int maxValue = array[0]; int index = 0; for (int i = 1; i < array.length; i++) { if (array[i] > maxValue) { maxValue = array[i]; index = i; } } return index; } }
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/SimplifiedTimeSeriesLoader.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.util; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.exception.TimeSeriesLoadingException; /** * Time series loader class which provides functionality to read datasets from * files storing into simplified, more efficient time series datasets. * * @author Julian Lienen * */ public class SimplifiedTimeSeriesLoader { private SimplifiedTimeSeriesLoader() { /* avoid instantiation */ } /** * Log4j logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(SimplifiedTimeSeriesLoader.class); /** * Default charset used when extracting from files. */ public static final String DEFAULT_CHARSET = "UTF-8"; /** * Prefix indicating an attribute declaration row in arff files. */ private static final String ARFF_ATTRIBUTE_PREFIX = "@attribute"; /** * Delimiter in value enumerations in arff files. */ private static final String ARFF_VALUE_DELIMITER = ","; /** * Flag indicating the start of the data block in arff files. */ private static final String ARFF_DATA_FLAG = "@data"; /** * Loads a univariate time series dataset from the given arff file. Assumes the * class attribute to be the last among the declared attributes in the file. * * @param arffFile * The arff file which is read * @return Returns a pair consisting of an univariate TimeSeriesDataset object * and a list of String objects containing the class values. * @throws TimeSeriesLoadingException * Throws an exception when the TimeSeriesDataset could not be * created from the given file. */ @SuppressWarnings("unchecked") public static Pair<TimeSeriesDataset2, ClassMapper> loadArff(final File arffFile) throws TimeSeriesLoadingException { if (arffFile == null) { throw new IllegalArgumentException("Parameter 'arffFile' must not be null!"); } Object[] tsTargetClassNames = loadTimeSeriesWithTargetFromArffFile(arffFile); ArrayList<double[][]> matrices = new ArrayList<>(); matrices.add((double[][]) tsTargetClassNames[0]); ClassMapper cm = null; if (tsTargetClassNames[2] != null) { cm = new ClassMapper((List<String>) tsTargetClassNames[2]); } return new Pair<>(new TimeSeriesDataset2(matrices, new ArrayList<>(), (int[]) tsTargetClassNames[1]), cm); } /** * Loads a multivariate time series dataset from multiple arff files (each for * one series). The arff files must share the same targets among all series. * Assumes the class attribute to be the last among the declared attributes in * the file. * * @param arffFiles * A sequence of arff files each containing one time series per * instance * @return Returns a multivariate TimeSeriesDataset object * @throws TimeSeriesLoadingException * Throws an exception when the TimeSeriesDataset could not be * created from the given files. */ @SuppressWarnings("unchecked") public static Pair<TimeSeriesDataset2, ClassMapper> loadArffs(final File... arffFiles) throws TimeSeriesLoadingException { if (arffFiles == null) { throw new IllegalArgumentException("Parameter 'arffFiles' must not be null!"); } final List<double[][]> matrices = new ArrayList<>(); int[] target = null; List<String> classNames = null; for (final File arffFile : arffFiles) { Object[] tsTargetClassNames = loadTimeSeriesWithTargetFromArffFile(arffFile); if (classNames == null && tsTargetClassNames[2] != null) { classNames = (List<String>) tsTargetClassNames[2]; } else { // Check whether the same class names are used among all of the time series List<String> furtherClassNames = (List<String>) tsTargetClassNames[2]; if ((classNames != null && furtherClassNames == null) || (furtherClassNames != null && !furtherClassNames.equals(classNames))) { throw new TimeSeriesLoadingException("Could not load multivariate time series with different targets. Target values have to be stored in each " + "time series arff file and must be equal!"); } } if (target == null) { target = (int[]) tsTargetClassNames[1]; } else { // Check whether the same targets are used among all of the time series int[] furtherTarget = (int[]) tsTargetClassNames[1]; if (furtherTarget == null || target.length != furtherTarget.length || !Arrays.equals(target, furtherTarget)) { throw new TimeSeriesLoadingException("Could not load multivariate time series with different targets. Target values have to be stored in each " + "time series arff file and must be equal!"); } } // Check for same instance length if (!matrices.isEmpty() && ((double[][]) tsTargetClassNames[0]).length != matrices.get(0).length) { throw new TimeSeriesLoadingException("All time series must have the same first dimensionality (number of instances)."); } matrices.add((double[][]) tsTargetClassNames[0]); } ClassMapper cm = null; if (classNames != null) { cm = new ClassMapper(classNames); } return new Pair<>(new TimeSeriesDataset2(matrices, new ArrayList<>(), target), cm); } /** * Extracting the time series and target matrices from a given arff file. * Assumes the class attribute to be the last among the declared attributes in * the file. * * @param arffFile * The arff file to be parsed * @return Returns an object consisting of three elements: 1. The time series * value matrix (double[][]), 2. the target value matrix (int[]) and 3. * a list of the class value strings (List<String>) * @throws TimeSeriesLoadingException * Throws an exception when the matrices could not be extracted from * the given arff file */ private static Object[] loadTimeSeriesWithTargetFromArffFile(final File arffFile) throws TimeSeriesLoadingException { double[][] matrix = null; int[] targetMatrix = null; int numEmptyDataRows = 0; List<String> targetValues = null; boolean stringAttributes = false; try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(arffFile), StandardCharsets.UTF_8))) { int attributeCount = 0; int lineCounter = 0; int numInstances = 0; final int fileLinesCount = countFileLines(arffFile); boolean targetSet = false; boolean readData = false; String line; String lastLine = ""; while ((line = br.readLine()) != null) { if (!readData) { lineCounter++; // Set target values if (!targetSet && line.equals("") && lastLine.startsWith(ARFF_ATTRIBUTE_PREFIX)) { String targetString = lastLine.substring(lastLine.indexOf('{') + 1, lastLine.length() - 1); targetValues = Arrays.asList(targetString.split(ARFF_VALUE_DELIMITER)); if (!SetUtil.doesStringCollectionOnlyContainNumbers(targetValues)) { stringAttributes = true; } targetSet = true; } // Count attributes if (line.startsWith(ARFF_ATTRIBUTE_PREFIX)) { attributeCount++; } if (line.startsWith(ARFF_DATA_FLAG)) { readData = true; numInstances = fileLinesCount - lineCounter + 1; matrix = new double[numInstances][targetSet ? attributeCount - 1 : attributeCount]; targetMatrix = new int[numInstances]; lineCounter = 0; if (!targetSet) { LOGGER.warn("No target has been set before reading data."); } } } else { if (!line.equals("")) { // Read the data String[] values = line.split(ARFF_VALUE_DELIMITER); double[] dValues = new double[targetSet ? values.length - 1 : values.length]; for (int i = 0; i < values.length - 1; i++) { dValues[i] = Double.parseDouble(values[i]); } matrix[lineCounter] = dValues; if (targetSet) { targetMatrix[lineCounter] = targetValues.indexOf(values[values.length - 1]); } } lineCounter++; } lastLine = line; } // Update empty data rows numEmptyDataRows = numInstances - lineCounter; if (matrix == null) { throw new IllegalStateException("Matrix is null, which it should not be at this point!"); } // Due to efficiency reasons, the matrices are narrowed afterwards to eliminate // empty data rows if (numEmptyDataRows > 0) { int endIndex = matrix.length - numEmptyDataRows; matrix = getInterval(matrix, 0, endIndex); targetMatrix = getInterval(targetMatrix, 0, endIndex); } Object[] result = new Object[3]; result[0] = matrix; result[1] = targetMatrix; result[2] = stringAttributes ? targetValues : null; return result; } catch (UnsupportedEncodingException e) { throw new TimeSeriesLoadingException("Could not load time series dataset due to unsupported encoding.", e); } catch (FileNotFoundException e) { throw new TimeSeriesLoadingException(String.format("Could not locate time series dataset file '%s'.", arffFile.getPath()), e); } catch (IOException e) { throw new TimeSeriesLoadingException("Could not load time series dataset due to IOException.", e); } } /** * Function returning a submatrix of the given <code>matrix</code>. The * submatrix is specified by the indices <code>begin</code> and * </code>end</code> (exclusive). Only the rows within this interval are copied * into the result matrix. * * @param matrix * The matrix from which the submatrix is extracted * @param begin * Begin index of the rows to be extracted * @param end * Exclusive end index of the rows to be extracted * @return Returns the specified submatrix */ private static double[][] getInterval(final double[][] matrix, final int begin, final int end) { if (begin < 0 || begin > matrix.length - 1) { throw new IllegalArgumentException("The begin index must be valid!"); } if (end < 1 || end > matrix.length) { throw new IllegalArgumentException("The end index must be valid!"); } final double[][] result = new double[end - begin][]; for (int i = 0; i < end - begin; i++) { result[i] = matrix[i + begin]; } return result; } /** * Function returning an interval as subarray of the given <code>array</code>. * The interval is specified by the indices <code>begin</code> and * </code>end</code> (exclusive). * * @param array * The array from which the interval is extracted * @param begin * Begin index of the interval * @param end * Exclusive end index of the interval * @return Returns the specified interval as a subarray */ private static int[] getInterval(final int[] array, final int begin, final int end) { if (begin < 0 || begin > array.length - 1) { throw new IllegalArgumentException("The begin index must be valid!"); } if (end < 1 || end > array.length) { throw new IllegalArgumentException("The end index must be valid!"); } final int[] result = new int[end - begin]; for (int i = 0; i < end - begin; i++) { result[i] = array[i + begin]; } return result; } /** * Counts the lines of the given File object in a very efficient way (thanks to * https://stackoverflow.com/a/453067). * * @param filename * File which lines of code are counted * @return Returns the number of file lines * @throws IOException * Throws exception when the given file could not be read */ public static int countFileLines(final File file) throws IOException { try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { byte[] c = new byte[1024]; int readChars = is.read(c); if (readChars == -1) { // bail out if nothing to read return 0; } // make it easy for the optimizer to tune this loop int count = 0; while (readChars == 1024) { for (int i = 0; i < 1024; i++) { if (c[i] == '\n') { ++count; } } readChars = is.read(c); } // count remaining characters while (readChars != -1) { for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; } } readChars = is.read(c); } return count == 0 ? 1 : count; } } }
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/TSLearningProblem.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.util; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset2; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.quality.IQualityMeasure; public class TSLearningProblem { private final IQualityMeasure qualityMeasure; private final TimeSeriesDataset2 dataset; public TSLearningProblem(final IQualityMeasure qualityMeasure, final TimeSeriesDataset2 dataset) { super(); this.qualityMeasure = qualityMeasure; this.dataset = dataset; } public IQualityMeasure getQualityMeasure() { return this.qualityMeasure; } public TimeSeriesDataset2 getDataset() { return this.dataset; } }
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/TimeSeriesBatchLoader.java
package ai.libs.jaicore.ml.classification.singlelabel.timeseries.util; import ai.libs.jaicore.ml.classification.singlelabel.timeseries.dataset.TimeSeriesDataset; /** * BatchLoader */ public class TimeSeriesBatchLoader { public TimeSeriesBatchLoader(TimeSeriesDataset dataset, int batchSize, boolean shuffle) { } }