repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
tsml-java
tsml-java-master/src/main/java/tsml/transformers/HOG1D.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import org.apache.commons.lang3.ArrayUtils; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import java.util.ArrayList; import java.util.Arrays; /** * This class is to calculate the HOG1D transform of a dataframe of time series * data. Works by splitting the time series num_intervals times, and calculate a * histogram of gradients within each interval. * * @author Vincent Nicholson * */ public class HOG1D implements Transformer { private int numIntervals; private int numBins; private double scalingFactor; public HOG1D() { this.numIntervals = 2; this.numBins = 8; this.scalingFactor = 0.1; } public HOG1D(int numIntervals, int numBins, double scalingFactor) { this.numIntervals = numIntervals; this.numBins = numBins; this.scalingFactor = scalingFactor; } public int getNumIntervals() { return this.numIntervals; } public void setNumIntervals(int numIntervals) { this.numIntervals = numIntervals; } public int getNumBins() { return this.numBins; } public void setNumBins(int numBins) { this.numBins = numBins; } public double getScalingFactor() { return scalingFactor; } public void setScalingFactor(double scalingFactor) { this.scalingFactor = scalingFactor; } @Override public Instance transform(Instance inst) { double[] data = inst.toDoubleArray(); // remove class attribute if needed double[] temp; int c = inst.classIndex(); if (c >= 0) { temp = new double[data.length - 1]; System.arraycopy(data, 0, temp, 0, c); // assumes class attribute is in last index data = temp; } checkParameters(data.length); double[] gradients = getHOG1Ds(data); // Now in DWT form, extract out the terms and set the attributes of new instance Instance newInstance; int numAtts = gradients.length; if (inst.classIndex() >= 0) newInstance = new DenseInstance(numAtts + 1); else newInstance = new DenseInstance(numAtts); // Copy over the values into the Instance for (int j = 0; j < numAtts; j++) newInstance.setValue(j, gradients[j]); // Set the class value if (inst.classIndex() >= 0) newInstance.setValue(newInstance.numAttributes() - 1, inst.classValue()); return newInstance; } /** * Private function for getting the histogram of gradients of a time series. * * @param inst - the time series to be transformed. * @return the transformed inst. */ private double[] getHOG1Ds(double[] inst) { double[][] hog1Ds = new double[this.numIntervals][]; // Split inst into intervals double[][] intervals = getIntervals(inst); // Extract a histogram of gradients for each interval for (int i = 0; i < intervals.length; i++) { hog1Ds[i] = getHOG1D(intervals[i]); } // Concatenate the HOG1Ds together double[] out = new double[] {}; for (int i = hog1Ds.length - 1; i > -1; i--) { out = ArrayUtils.addAll(hog1Ds[i], out); } return out; } /** * Private function for splitting a time series into approximately equal * intervals. * * @param inst * @return */ private double[][] getIntervals(double[] inst) { int numElementsRemaining = inst.length; int numIntervalsRemaining = this.numIntervals; int startIndex = 0; double[][] intervals = new double[this.numIntervals][]; for (int i = 0; i < this.numIntervals; i++) { int intervalSize = (int) Math.ceil(numElementsRemaining / numIntervalsRemaining); double[] interval = Arrays.copyOfRange(inst, startIndex, startIndex + intervalSize); intervals[i] = interval; numElementsRemaining -= intervalSize; numIntervalsRemaining--; startIndex = startIndex + intervalSize; } return intervals; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i =0; for(TimeSeries ts : inst){ out[i++] = getHOG1Ds(ts.toValueArray()); } return new TimeSeriesInstance(out, inst.getLabelIndex()); } /** * Private method to calculate the HOG of a particular interval. * * @param t - an interval. * @return */ private double[] getHOG1D(double[] t) { // Pad t on either ends just once. double[] paddedT = ArrayUtils.addAll(new double[] { t[0] }, t); paddedT = ArrayUtils.addAll(paddedT, new double[] { t[t.length - 1] }); // Calculate the gradients over every element in t. double[] gradients = new double[t.length]; for (int i = 1; i < gradients.length + 1; i++) { gradients[(i - 1)] = scalingFactor * 0.5 * (paddedT[(i + 1)] - paddedT[(i - 1)]); } // Then, calculate the orientations given the gradients double[] orientations = new double[gradients.length]; for (int i = 0; i < gradients.length; i++) { orientations[i] = Math.toDegrees(Math.atan(gradients[i])); } double[] histBins = new double[this.numBins]; // Calculate the bin boundaries double inc = 180.0 / (double) this.numBins; double current = -90.0; for (int i = 0; i < histBins.length; i++) { histBins[i] = current + inc; current += inc; } // Create the histogram double[] histogram = new double[this.numBins]; for (int i = 0; i < orientations.length; i++) { for (int j = 0; j < histogram.length; j++) { if (orientations[i] <= histBins[j]) { histogram[j] += 1; break; } } } return histogram; } @Override public Instances determineOutputFormat(Instances inputFormat) throws IllegalArgumentException { // If the class index exists. if (inputFormat.classIndex() >= 0) { if (inputFormat.classIndex() != inputFormat.numAttributes() - 1) { throw new IllegalArgumentException("cannot handle class values not at end"); } } ArrayList<Attribute> attributes = new ArrayList<>(); // Create a list of attributes for (int i = 0; i < numBins * numIntervals; i++) { attributes.add(new Attribute("HOG1D_" + i)); } // Add the class attribute (if it exists) if (inputFormat.classIndex() >= 0) { attributes.add(inputFormat.classAttribute()); } Instances result = new Instances("HOG1D" + inputFormat.relationName(), attributes, inputFormat.numInstances()); // Set the class attribute (if it exists) if (inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } return result; } private void checkParameters(int timeSeriesLength) { if (this.numIntervals < 1) { throw new IllegalArgumentException("numIntervals must be greater than zero."); } if (this.numIntervals > timeSeriesLength) { throw new IllegalArgumentException("numIntervals cannot be longer than the time series length."); } if (this.numBins < 1) { throw new IllegalArgumentException("numBins must be greater than zero."); } } /** * Main class for testing. * * @param args */ public static void main(String[] args) { Instances data = createData(new double[] { 4, 6, 10, 12, 8, 6, 5, 5 }); // test bad numIntervals // has to be greater than 0. // cannot be higher than the time series length int[] badNumIntervals = new int[] { -1, 0, -99999999, 9 }; for (int badNumInterval : badNumIntervals) { try { HOG1D h = new HOG1D(badNumInterval, 8, 0.1); h.transform(data); System.out.println("Test failed."); } catch (IllegalArgumentException e) { System.out.println("Test passed."); } } // test good numIntervals int[] goodNumIntervals = new int[] { 2, 4, 8 }; for (int goodNumInterval : goodNumIntervals) { try { HOG1D h = new HOG1D(goodNumInterval, 8, 0.1); h.transform(data); System.out.println("Test passed."); } catch (IllegalArgumentException e) { System.out.println("Test failed."); } } // test bad numBins // Cannot be less than 1 int[] badNumBins = new int[] { 0, -5, -999, -687 }; for (int badNumBin : badNumBins) { try { HOG1D h = new HOG1D(2, badNumBin, 0.1); h.transform(data); System.out.println("Test failed."); } catch (IllegalArgumentException e) { System.out.println("Test passed."); } } // test good numBins int[] goodNumBins = new int[] { 1, 5, 12, 200 }; for (int goodNumBin : goodNumBins) { try { HOG1D h = new HOG1D(2, goodNumBin, 0.1); h.transform(data); System.out.println("Test passed."); } catch (IllegalArgumentException e) { System.out.println("Test failed."); } } // test output HOG1D h = new HOG1D(); Instances out = h.transform(data); double[] outArr = out.get(0).toDoubleArray(); System.out.println(Arrays.equals(outArr, new double[] { 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0 })); data = createData(new double[] { -5, 2.5, 1, 3, 10, -1.5, 6, 12, -3, 0.2 }); out = h.transform(data); outArr = out.get(0).toDoubleArray(); System.out.println(Arrays.equals(outArr, new double[] { 0.0, 0.0, 0.0, 0.0, 4.0, 1.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 2.0, 1.0, 0.0, 0.0 })); // test dimensions (test that output is always of length numBins*numIntervals) h = new HOG1D(6, 30, 0.1); out = h.transform(data); System.out.println(out.get(0).toDoubleArray().length == 6 * 30); } /** * Function to create data for testing purposes. * * @return */ private static Instances createData(double[] data) { // Create the attributes ArrayList<Attribute> atts = new ArrayList<>(); for (int i = 0; i < data.length; i++) { atts.add(new Attribute("test_" + i)); } Instances newInsts = new Instances("Test_dataset", atts, 1); // create the test data createInst(data, newInsts); return newInsts; } /** * private function for creating an instance from a double array. Used for * testing purposes. * * @param arr * @return */ private static void createInst(double[] arr, Instances dataset) { Instance inst = new DenseInstance(arr.length); for (int i = 0; i < arr.length; i++) { inst.setValue(i, arr[i]); } inst.setDataset(dataset); dataset.add(inst); } }
12,497
34.810888
119
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/HashTransformer.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import java.util.Arrays; import java.util.List; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; /** * Purpose: transforms a set of instances into a set of hashed instances. This * allows them to reliably be cached. * <p> * Contributors: goastler, abostrom */ public class HashTransformer implements Transformer { @Override public Instances determineOutputFormat(final Instances inputFormat) { return inputFormat; } @Override public Instances transform(Instances inst) { hashInstances(inst); return inst; } @Override public Instance transform(Instance inst) { return inst.dataset() != null ? hashInstanceAndDataset(inst) : hashInstance(inst); } public static class HashedDenseInstance extends DenseInstance { private int id; public HashedDenseInstance(Instance instance) { super(instance); setDataset(instance.dataset()); if (instance instanceof HashedDenseInstance) { id = ((HashedDenseInstance) instance).id; } else { rebuildId(); } } private void rebuildId() { id = Arrays.hashCode(m_AttValues); } @Override public int hashCode() { return id; } @Override public boolean equals(Object o) { boolean result = false; if (o instanceof HashedDenseInstance) { HashedDenseInstance other = (HashedDenseInstance) o; result = other.id == id; } return result; } @Override public Object copy() { return new HashedDenseInstance(this); } @Override protected void forceDeleteAttributeAt(int position) { rebuildId(); super.forceDeleteAttributeAt(position); } @Override protected void forceInsertAttributeAt(int position) { rebuildId(); super.forceInsertAttributeAt(position); } @Override public Instance mergeInstance(Instance inst) { rebuildId(); return super.mergeInstance(inst); } } public static void hashInstances(List<Instance> instances) { for (int i = 0; i < instances.size(); i++) { Instance instance = instances.get(i); if (!(instance instanceof HashedDenseInstance)) { HashedDenseInstance indexedInstance = hashInstance(instance); instances.set(i, indexedInstance); } } } public static HashedDenseInstance hashInstance(Instance instance) { if (!(instance instanceof HashedDenseInstance)) { instance = new HashedDenseInstance(instance); } return (HashedDenseInstance) instance; } public static Instance hashInstanceAndDataset(Instance instance) { if (instance instanceof HashedDenseInstance) { hashInstances(instance.dataset()); return instance; } Instances dataset = instance.dataset(); int index = dataset.indexOf(instance); hashInstances(dataset); return dataset.get(index); } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { //TimeSeriesInstance are already hashable out of the box. //this is just so that it plays nicely with other code. return inst; } @Override public TimeSeriesInstances transform(TimeSeriesInstances data) { //TimeSeriesInstance are already hashable out of the box. //this is just so that it plays nicely with other code. return data; } }
4,665
29.298701
90
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Hilbert.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.io.File; import java.io.IOException; import experiments.data.DatasetLoading; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import weka.core.*; /* * copyright: Anthony Bagnall * @author Aaron Bostrom * */ public class Hilbert implements Transformer { public Instances determineOutputFormat(Instances inputFormat) throws IllegalArgumentException { FastVector<Attribute> atts = new FastVector<>(); for (int i = 0; i < inputFormat.numAttributes() - 1; i++) { // Add to attribute list String name = "Hilbert" + i; atts.addElement(new Attribute(name)); } // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); FastVector<String> vals = new FastVector<>(target.numValues()); for (int i = 0; i < target.numValues(); i++) vals.addElement(target.value(i)); atts.addElement(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); Instances result = new Instances("Hilbert" + inputFormat.relationName(), atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } return result; } @Override public Instances transform(Instances data) { // for k=1 to n: f_k = sum_{i=1}^n f_i cos[(k-1)*(\pi/n)*(i-1/2)] // Assumes the class attribute is in the last one for simplicity Instances result = determineOutputFormat(data); for (Instance inst : data) result.add(transform(inst)); return result; } @Override public Instance transform(Instance inst) { int n = inst.numAttributes() - 1; Instance newInst = new DenseInstance(inst.numAttributes()); for (int k = 0; k < n; k++) { double fk = 0; for (int i = 0; i < n; i++) { if (i != k) fk += inst.value(i) / (k - i); } newInst.setValue(k, fk); } newInst.setValue(inst.classIndex(), inst.classValue()); return newInst; } public static void main(String[] args) throws IOException { String localPath = "src/main/java/experiments/data/tsc/"; // path for testing. String datasetName = "ChinaTown"; Instances train = DatasetLoading .loadData(localPath + datasetName + File.separator + datasetName + "_TRAIN.ts"); Instances test = DatasetLoading .loadData(localPath + datasetName + File.separator + datasetName + "_TEST.ts"); Hilbert hTransform = new Hilbert(); Instances out_train = hTransform.transform(train); Instances out_test = hTransform.transform(test); System.out.println(out_train.toString()); System.out.println(out_test.toString()); } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int index = 0; for (TimeSeries ts : inst) { int n = ts.getSeriesLength(); out[index] = new double[n]; for (int k = 0; k < n; k++) { double fk = 0; for (int i = 0; i < n; i++) { if (i != k) fk += ts.getValue(i) / (k - i); } out[index][k] = fk; } } return new TimeSeriesInstance(out, inst.getLabelIndex()); } }
3,881
31.898305
109
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Indexer.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import akka.util.Index; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import org.junit.Assert; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import java.io.Serializable; import java.util.Arrays; import java.util.Enumeration; import java.util.Objects; public class Indexer extends BaseTrainableTransformer { public static Instances index(Instances data) { new Indexer().fit(data); return data; } public Indexer() { setHashInsteadOfIndex(false); reset(); } private int index; private boolean hashInsteadOfIndex; @Override public void reset() { super.reset(); index = -1; } public int size() { return index + 1; } @Override public void fit(final Instances data) { super.fit(data); boolean missingIndices = false; if (!hashInsteadOfIndex) { for (final Instance instance : data) { if (instance instanceof IndexedInstance) { index = Math.max(index, ((IndexedInstance) instance).getIndex()); } else { missingIndices = true; } } } if (missingIndices) { for (int i = 0; i < data.size(); i++) { final Instance instance = data.get(i); int index; if (hashInsteadOfIndex) { index = Arrays.hashCode(instance.toDoubleArray()); } else { index = ++this.index; } final IndexedInstance indexedInstance = new IndexedInstance(instance, index); data.set(i, indexedInstance); } } } @Override public Instance transform(final Instance inst) { return new IndexedInstance(inst, -1); } public Instance transform(final IndexedInstance inst) { return inst; } @Override public Instances determineOutputFormat(final Instances data) throws IllegalArgumentException { return new Instances(data, data.size()); } public boolean isHashInsteadOfIndex() { return hashInsteadOfIndex; } public void setHashInsteadOfIndex(final boolean hashInsteadOfIndex) { this.hashInsteadOfIndex = hashInsteadOfIndex; } public static class IndexedInstance implements Instance, Serializable { public IndexedInstance(Instance instance, int index) { setIndex(index); setInstance(instance); } public IndexedInstance(IndexedInstance indexedInstance) { this((Instance) indexedInstance.instance.copy(), indexedInstance.index); } private int index; private Instance instance; public Instance getInstance() { return instance; } public void setInstance(final Instance instance) { Assert.assertNotNull(instance); this.instance = instance; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof IndexedInstance)) { return false; } final IndexedInstance that = (IndexedInstance) o; return index == that.index; } @Override public int hashCode() { return index; } public int getIndex() { return index; } public void setIndex(final int index) { this.index = index; } @Override public Attribute attribute(final int index) { return instance.attribute(index); } @Override public Attribute attributeSparse(final int indexOfIndex) { return instance.attributeSparse(indexOfIndex); } @Override public Attribute classAttribute() { return instance.classAttribute(); } @Override public int classIndex() { return instance.classIndex(); } @Override public boolean classIsMissing() { return instance.classIsMissing(); } @Override public double classValue() { return instance.classValue(); } @Override public Instances dataset() { return instance.dataset(); } @Override public void deleteAttributeAt(final int position) { instance.deleteAttributeAt(position); } @Override public Enumeration enumerateAttributes() { return instance.enumerateAttributes(); } @Override public boolean equalHeaders(final Instance inst) { return instance.equalHeaders(inst); } @Override public String equalHeadersMsg(final Instance inst) { return instance.equalHeadersMsg(inst); } @Override public boolean hasMissingValue() { return instance.hasMissingValue(); } @Override public int index(final int position) { return instance.index(position); } @Override public void insertAttributeAt(final int position) { instance.insertAttributeAt(position); } @Override public boolean isMissing(final int attIndex) { return instance.isMissing(attIndex); } @Override public boolean isMissingSparse(final int indexOfIndex) { return instance.isMissingSparse(indexOfIndex); } @Override public boolean isMissing(final Attribute att) { return instance.isMissing(att); } @Override public Instance mergeInstance(final Instance inst) { return instance.mergeInstance(inst); } @Override public int numAttributes() { return instance.numAttributes(); } @Override public int numClasses() { return instance.numClasses(); } @Override public int numValues() { return instance.numValues(); } @Override public void replaceMissingValues(final double[] array) { instance.replaceMissingValues(array); } @Override public void setClassMissing() { instance.setClassMissing(); } @Override public void setClassValue(final double value) { instance.setClassValue(value); } @Override public void setClassValue(final String value) { instance.setClassValue(value); } @Override public void setDataset(final Instances instances) { instance.setDataset(instances); } @Override public void setMissing(final int attIndex) { instance.setMissing(attIndex); } @Override public void setMissing(final Attribute att) { instance.setMissing(att); } @Override public void setValue(final int attIndex, final double value) { instance.setValue(attIndex, value); } @Override public void setValueSparse(final int indexOfIndex, final double value) { instance.setValueSparse(indexOfIndex, value); } @Override public void setValue(final int attIndex, final String value) { instance.setValue(attIndex, value); } @Override public void setValue(final Attribute att, final double value) { instance.setValue(att, value); } @Override public void setValue(final Attribute att, final String value) { instance.setValue(att, value); } @Override public void setWeight(final double weight) { instance.setWeight(weight); } @Override public Instances relationalValue(final int attIndex) { return instance.relationalValue(attIndex); } @Override public Instances relationalValue(final Attribute att) { return instance.relationalValue(att); } @Override public String stringValue(final int attIndex) { return instance.stringValue(attIndex); } @Override public String stringValue(final Attribute att) { return instance.stringValue(att); } @Override public double[] toDoubleArray() { return instance.toDoubleArray(); } @Override public String toStringNoWeight(final int afterDecimalPoint) { return instance.toStringNoWeight(afterDecimalPoint); } @Override public String toStringNoWeight() { return instance.toStringNoWeight(); } @Override public String toStringMaxDecimalDigits(final int afterDecimalPoint) { return instance.toStringMaxDecimalDigits(afterDecimalPoint); } @Override public String toString(final int attIndex, final int afterDecimalPoint) { return instance.toString(attIndex, afterDecimalPoint); } @Override public String toString(final int attIndex) { return instance.toString(attIndex); } @Override public String toString(final Attribute att, final int afterDecimalPoint) { return instance.toString(att, afterDecimalPoint); } @Override public String toString(final Attribute att) { return instance.toString(att); } @Override public double value(final int attIndex) { return instance.value(attIndex); } @Override public double valueSparse(final int indexOfIndex) { return instance.valueSparse(indexOfIndex); } @Override public double value(final Attribute att) { return instance.value(att); } @Override public double weight() { return instance.weight(); } @Override public IndexedInstance copy() { return new IndexedInstance(this); } @Override public String toString() { return "IndexedInstance{" + "index=" + index + ", instance=" + instance + '}'; } } @Override public void fit(TimeSeriesInstances data) { // TODO Auto-generated method stub } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { // TODO Auto-generated method stub return null; } }
11,634
26.05814
98
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/IntervalTransform.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import experiments.data.DatasetLoading; import org.junit.Assert; import tsml.classifiers.distance_based.utils.collections.intervals.IntInterval; import tsml.classifiers.distance_based.utils.collections.intervals.IntervalInstance; import tsml.data_containers.TimeSeriesInstance; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import java.util.ArrayList; public class IntervalTransform implements Transformer { private IntInterval interval; private boolean deepCopyInstances; private Instances header; public IntervalTransform() { this(new IntInterval(0, 0)); } public IntervalTransform(IntInterval interval) { setInterval(interval); setDeepCopyInstances(false); } @Override public Instance transform(Instance inst) { if (deepCopyInstances) { throw new UnsupportedOperationException(); // todo } else if (inst instanceof IntervalInstance) { ((IntervalInstance) inst).setInterval(interval); } else { inst = new IntervalInstance(interval, inst); } if (inst.dataset().numAttributes() != inst.numAttributes()) { if (header == null || inst.dataset().numAttributes() != header.numAttributes()) { header = determineOutputFormat(inst.dataset()); } inst.setDataset(header); } return inst; } @Override public Instances determineOutputFormat(Instances data) throws IllegalArgumentException { Assert.assertEquals(data.numAttributes() - 1, data.classIndex()); if (deepCopyInstances) { throw new UnsupportedOperationException(); // todo } else { ArrayList<Attribute> attributes = new ArrayList<>(interval.size() + 1); for (int i = 0; i < interval.size(); i++) { final int j = interval.translate(i); Attribute attribute = data.attribute(j); attribute = attribute.copy(String.valueOf(j)); attributes.add(attribute); } attributes.add((Attribute) data.classAttribute().copy()); data = new Instances(data.relationName(), attributes, 0); data.setClassIndex(data.numAttributes() - 1); } return data; } public IntInterval getInterval() { return interval; } public void setInterval(final IntInterval interval) { Assert.assertNotNull(interval); this.interval = interval; } public boolean isDeepCopyInstances() { return deepCopyInstances; } public void setDeepCopyInstances(final boolean deepCopyInstances) { this.deepCopyInstances = deepCopyInstances; } public static void main(String[] args) throws Exception { final Instances instances = DatasetLoading.loadGunPoint(); final Instance instance = instances.get(0); final IntervalInstance intervalInstance = new IntervalInstance(new IntInterval(10, 5), instance); System.out.println(intervalInstance.toString()); } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { // TODO Auto-generated method stub return null; } }
4,051
34.54386
105
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/MFCC.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import static experiments.data.DatasetLoading.loadDataNullable; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.math3.transform.DctNormalization; import org.apache.commons.math3.transform.FastCosineTransformer; import org.apache.commons.math3.transform.TransformType; import tsml.data_containers.TimeSeriesInstance; import utilities.multivariate_tools.MultivariateInstanceTools; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.FastVector; import weka.core.Instance; import weka.core.Instances; public class MFCC implements Transformer { // Default values (samples), assuming no sample rate set. int windowLength = 50; int overlapLength = 25; // Default values (miliseconds), determined using sample rate. int windowDuration = 25; int overlapDuration = 15; // Check whether there is an attribute called samplerate and use that before // deleting it. Boolean checkForSampleRate = true; int nfft = 512; int sampleRate = 16000; Spectrogram spectrogram; FastCosineTransformer dct = new FastCosineTransformer(DctNormalization.STANDARD_DCT_I); int numFilterBanks = 65; double[][] filterBank = null; double[][] melFreqCepsCo = null; // Upper and lower frequencies the filter bank will be applied to (Freq. outside // of these will not contribute to overall output.). int lowerFreq = 0; int upperFreq = 2000; public int interval = 0; public MFCC() { spectrogram = new Spectrogram(windowLength, overlapLength, nfft); } public void setSampleRate(int sampleRate) { this.sampleRate = sampleRate; } public String globalInfo() { return null; } public Instances determineOutputFormat(Instances inputFormat) { Instances instances = null; FastVector<Attribute> attributes = new FastVector<>(melFreqCepsCo.length); for (int i = 0; i < (melFreqCepsCo.length); i++) { attributes.addElement(new Attribute("MFCC_att" + interval + String.valueOf(i + 1))); } FastVector<String> classValues = new FastVector<>(inputFormat.classAttribute().numValues()); for (int i = 0; i < inputFormat.classAttribute().numValues(); i++) classValues.addElement(inputFormat.classAttribute().value(i)); attributes.addElement(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), classValues)); instances = new Instances("", attributes, 0); instances.setClassIndex(instances.numAttributes() - 1); return instances; } public Instances determineOutputFormatForFirstChannel(Instances instances) { try { return determineOutputFormat(instances); } catch (Exception e) { e.printStackTrace(); } return null; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { // TODO: not sure on how to oconvert this. need to have a think. throw new NotImplementedException("This method is not implemented for single transformations."); } @Override public Instance transform(Instance inst) { // TODO: not sure on how to oconvert this. need to have a think. throw new NotImplementedException("This method is not implemented for single transformations."); } /** * * @param instances Univariate instances. * @return Relational instances containing MFCC information. * @throws Exception */ public Instances transform(Instances instances) { Instances[] MFCCs = new Instances[instances.size()]; Instances flatMFCCs = null; Instances MFCCInstances = null; double[][] spectrogram = null; double cumalativeFilteredVals = 0; double[] signal = new double[instances.get(0).numAttributes() - 1]; // Check whether samplerate info is in file, deletes before moving on. if ((instances.attribute("samplerate") != null) && checkForSampleRate) { sampleRate = (int) instances.get(0).value(instances.attribute("samplerate")); instances.deleteAttributeAt(instances.attribute("samplerate").index()); } if (sampleRate == 0) { sampleRate = nfft; } else { windowLength = (int) ((windowDuration / 1000.0) * (double) sampleRate); overlapLength = (int) ((overlapDuration / 1000.0) * (double) sampleRate); } this.spectrogram.setWindowLength(windowLength); this.spectrogram.setOverlap(overlapLength); if (windowLength > nfft) { System.out.print("NOTE: NFFT < window length, increased from " + nfft); nfft = nearestPowerOF2(windowLength); System.out.println(" to " + nfft); } for (int i = 0; i < instances.size(); i++) { MFCCInstances = null; spectrogram = null; cumalativeFilteredVals = 0; signal = new double[instances.get(0).numAttributes() - 1]; for (int j = 0; j < instances.get(i).numAttributes() - 1; j++) { signal[j] = instances.get(i).value(j); } spectrogram = this.spectrogram.spectrogram(signal, windowLength, overlapLength, nfft); // Performed to create Periodogram estimate of the power spectrum. for (int j = 0; j < spectrogram.length; j++) { for (int k = 0; k < spectrogram[j].length; k++) { spectrogram[j][k] = (1 / (double) spectrogram[j].length) * Math.pow(spectrogram[j][k], 2); } } filterBank = createFilterBanks(); melFreqCepsCo = new double[spectrogram.length][filterBank.length]; for (int j = 0; j < spectrogram.length; j++) { for (int k = 0; k < filterBank.length; k++) { cumalativeFilteredVals = 0; for (int l = 0; l < spectrogram[j].length; l++) { cumalativeFilteredVals += (spectrogram[j][l] * filterBank[k][l]); } melFreqCepsCo[j][k] = cumalativeFilteredVals == 0 ? 0 : Math.log(cumalativeFilteredVals); } } for (int j = 0; j < melFreqCepsCo.length; j++) { melFreqCepsCo[j] = dct.transform(melFreqCepsCo[j], TransformType.FORWARD); } MFCCInstances = determineOutputFormat(instances.get(i).dataset()); double[] temp; for (int j = 0; j < Math.floor(numFilterBanks / 2); j++) { temp = new double[melFreqCepsCo.length + 1]; for (int k = 0; k < melFreqCepsCo.length; k++) { temp[k] = (-1) * melFreqCepsCo[k][j]; } temp[temp.length - 1] = instances.get(i).value(instances.get(i).numAttributes() - 1); MFCCInstances.add(new DenseInstance(1.0, temp)); } MFCCs[i] = MFCCInstances; } // Rearrange data Instances[] temp = new Instances[MFCCs[0].size()]; for (int i = 0; i < temp.length; i++) { temp[i] = new Instances(MFCCs[0], 0); for (int j = 0; j < MFCCs.length; j++) { temp[i].add(MFCCs[j].get(i)); } } return MultivariateInstanceTools.concatinateInstances(temp); } private double[][] createFilterBanks() { filterBank = new double[numFilterBanks][nfft / 2]; double[] filterPeaks = new double[numFilterBanks + 2]; // Local overload for holding Mel conversion. double lowerFreq = 1125 * Math.log(1 + (this.lowerFreq / (double) 700)); double upperFreq = 1125 * Math.log(1 + (this.upperFreq / (double) 700)); double step = (upperFreq - lowerFreq) / (filterPeaks.length - 1); for (int i = 0; i < filterPeaks.length; i++) { filterPeaks[i] = lowerFreq + (step * i); } // Back to hertz. for (int i = 0; i < filterPeaks.length; i++) { filterPeaks[i] = 700 * (Math.exp(filterPeaks[i] / 1125) - 1); } for (int i = 0; i < filterPeaks.length; i++) { filterPeaks[i] = Math.floor((nfft + 1) * (filterPeaks[i] / this.sampleRate)); } // Create Filter Banks. for (int i = 0; i < filterBank.length; i++) { for (int j = 0; j < filterBank[i].length; j++) { if (j >= filterPeaks[i] && j <= filterPeaks[i + 1]) { filterBank[i][j] = ((j - filterPeaks[i]) / (filterPeaks[i + 1] - filterPeaks[i])); } if (j > filterPeaks[i + 1] && j < filterPeaks[i + 2]) { filterBank[i][j] = ((filterPeaks[i + 2] - j) / (filterPeaks[i + 2] - filterPeaks[i + 1])); } if (j > filterPeaks[i + 2]) { filterBank[i][j] = 0; } if (j < filterPeaks[i] || (j == 0 && filterPeaks[i] == 0)) { filterBank[i][j] = 0; } if (Double.isNaN(filterBank[i][j])) { filterBank[i][j] = 0; } } } return filterBank; } private int nearestPowerOF2(int x) { float power = (float) (Math.log(x) / Math.log(2)); int m = (int) Math.ceil(power); nfft = (int) Math.pow(2.0, (double) m); return nfft; } public static void main(String[] args) { MFCC mfcc = new MFCC(); Instances[] data = new Instances[2]; data[0] = loadDataNullable("D:\\Test\\Datasets\\Truncated\\HeartbeatSound\\Heartbeatsound"); mfcc.setSampleRate(16000); System.out.println(data[0].get(0).toString()); try { data[1] = mfcc.transform(data[0]); } catch (Exception e) { e.printStackTrace(); } System.out.println(); System.out.println(data[1].get(0)); Instance[] temp = MultivariateInstanceTools.splitMultivariateInstanceWithClassVal(data[1].get(0)); System.out.println(temp[0]); } }
10,965
38.024911
114
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/MatrixProfile.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import experiments.data.DatasetLoading; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import java.util.ArrayList; import static utilities.rescalers.ZNormalisation.ROUNDING_ERROR_CORRECTION; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; /** * * @author Jason Lines (j.lines@uea.ac.uk) * * Note: if desired, once a set of Instances are processed the accessor * methods getDistances() and getIndices() can be used for manually * using the values, rather than having to extract the data back from * the output Instances of process * * To-do: - Cache distances that will be reused (is it worth it? * Probably not since it's offline, but might be important for very * large problems and small windows) - Implement 'stride' - not sure if * this makes sense particularly, but we could allow it so the user can * change the step between comparison subseries that are evaluated when * calculating the profile (e.g. not every 1 index, every 2, 3, ... * etc.) * */ public class MatrixProfile implements Transformer { private int windowSize = 10; private final int stride = 1; // to-do later (maybe!) private double[][] distances; private int[][] indices; private boolean m_Debug = false; public MatrixProfile() { this(10); } public MatrixProfile(int windowSize) { this.windowSize = windowSize; } @Override public Instance transform(Instance inst) { SingleInstanceMatrixProfile mpIns = new SingleInstanceMatrixProfile(inst, this.windowSize, this.stride); Instance out = new DenseInstance(inst.numAttributes() + 1 - windowSize); for (int i = 0; i < mpIns.distances.length; i++) { out.setValue(i, mpIns.distances[i]); } if (inst.classIndex() >= 0) { out.setValue(mpIns.distances.length, inst.classValue()); } return out; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i = 0; for (TimeSeries ts : inst) { out[i++] = new SingleInstanceMatrixProfile(ts.toValueArray(), this.windowSize, this.stride).series; } return new TimeSeriesInstance(out, inst.getLabelIndex()); } @Override public Instances transform(Instances instances) { int seriesLength = instances.numAttributes() - (instances.classIndex() >= 0 ? 1 : 0); if (windowSize < 3) { // throw new Exception("Error: window must be at least 3. You have specified // "+windowSize); if (m_Debug) System.out.println( "Error: window must be at least 3. You have specified " + windowSize + " Setting it to 3"); windowSize = 3; } else if (windowSize > seriesLength / 4) { if (m_Debug) System.out.println( "Error: the series length must be at least 4 times larger than the window size to satisfy the exclusion zone criteria for trivial matches. These instances have a series length of " + seriesLength + "; the maximum window size is therefore " + (seriesLength / 4) + " and you have specified " + windowSize); windowSize = seriesLength / 4; } return Transformer.super.transform(instances); } /** * An alternate version of process() that returns two instances objects in an * array. The first is the same output as process() (matrix profile distances) * and the second is the indices of the closest match * * Input: instances - instances to be transformed Output: instances[2] where: * [0] matrix profile distances [1] matrix profile indices */ public Instances[] processDistancesAndIndices(Instances instances) throws Exception { int seriesLength = instances.numAttributes() - (instances.classIndex() >= 0 ? 1 : 0); if (windowSize < 3) { throw new Exception("Error: window must be at least 3. You have specified " + windowSize); } if (windowSize > seriesLength) { throw new Exception("Error: window must be smaller than the number of attributes. Window length: " + windowSize + ", series length: " + seriesLength); } if (seriesLength / 4 < windowSize) { throw new Exception( "Error: the series length must be at least 4 times larger than the window size to satisfy the exclusion zone criteria for trivial matches. These instances have a series length of " + seriesLength + "; the maximum window size is therefore " + (seriesLength / 4) + " and you have specified " + windowSize); } SingleInstanceMatrixProfile mpIns; Instances outputDistances = this.determineOutputFormat(instances); Instances outputIndices = this.determineOutputFormat(instances); Instance outDist, outIdx; this.distances = new double[instances.numInstances()][]; this.indices = new int[instances.numInstances()][]; for (int a = 0; a < seriesLength - windowSize + 1; a++) { outputIndices.renameAttribute(a, "idx_" + a); } outputIndices.setRelationName(outputIndices.relationName() + "_indices"); for (int ins = 0; ins < instances.numInstances(); ins++) { mpIns = new SingleInstanceMatrixProfile(instances.get(ins), this.windowSize, this.stride); outDist = new DenseInstance(outputDistances.numAttributes()); outIdx = new DenseInstance(outputIndices.numAttributes()); distances[ins] = mpIns.distances; indices[ins] = mpIns.indices; for (int i = 0; i < mpIns.distances.length; i++) { outDist.setValue(i, mpIns.distances[i]); outIdx.setValue(i, mpIns.indices[i]); } if (instances.classIndex() >= 0) { outDist.setValue(mpIns.distances.length, instances.instance(ins).classValue()); outIdx.setValue(mpIns.indices.length, instances.instance(ins).classValue()); } outputDistances.add(outDist); outputIndices.add(outIdx); } return new Instances[] { outputDistances, outputIndices }; } public double[][] getDistances() throws Exception { if (this.distances == null) { throw new Exception("Error: must process instances before accessing distances"); } return this.distances; } public int[][] getIndices() throws Exception { if (this.indices == null) { throw new Exception("Error: must process instances before accessing indices"); } return this.indices; } private static class SingleInstanceMatrixProfile { private final double[] series; private final int windowSize; private final int stride; private final double[] distances; private final int[] indices; private final int seriesLength; public SingleInstanceMatrixProfile(Instance series, int windowSize, int stride) { this.series = series.toDoubleArray(); this.seriesLength = series.classIndex() > 0 ? series.numAttributes() - 1 : series.numAttributes(); this.windowSize = windowSize; this.stride = stride; this.distances = new double[seriesLength + 1 - windowSize]; this.indices = new int[seriesLength + 1 - windowSize]; for (int a = 0; a <= seriesLength - windowSize; a++) { this.locateBestMatch(a); } } public SingleInstanceMatrixProfile(double[] series, int windowSize, int stride) { this.series = series; this.seriesLength = series.length; this.windowSize = windowSize; this.stride = stride; this.distances = new double[seriesLength + 1 - windowSize]; this.indices = new int[seriesLength + 1 - windowSize]; for (int a = 0; a <= seriesLength - windowSize; a++) { this.locateBestMatch(a); } } // query is fixed, comparison is every possible match within the series private void locateBestMatch(int queryStartIdx) { double dist; double bsfDist = Double.MAX_VALUE; int bsfIdx = -1; double[] query = zNormalise(series, queryStartIdx, this.windowSize, false); double[] comparison; for (int comparisonStartIdx = 0; comparisonStartIdx <= seriesLength - windowSize; comparisonStartIdx += stride) { // exclusion zone +/- windowSize/2 around the window if (comparisonStartIdx >= queryStartIdx - windowSize * 1.5 && comparisonStartIdx <= queryStartIdx + windowSize * 1.5) { continue; } // using a bespoke version of this, rather than the shapelet version, for // efficiency - see notes with method comparison = zNormalise(series, comparisonStartIdx, windowSize, false); dist = 0; for (int j = 0; j < windowSize; j++) { dist += (query[j] - comparison[j]) * (query[j] - comparison[j]); if (dist > bsfDist) { dist = Double.MAX_VALUE; break; } } if (dist < bsfDist) { bsfDist = dist; bsfIdx = comparisonStartIdx; } } this.distances[queryStartIdx] = bsfDist; this.indices[queryStartIdx] = bsfIdx; } } // adapted from shapelet code to avoid copying subsequences - logic is // equivilent. In the shapelet version the input is the subsequence as double[] // (i.e. the shapelet). // In this case we don't already have the subsequence as a double[], so to avoid // copying into one just to use this method, a bespoke version is used to // process the subsequence // directly from the full series given a start idx. The logic that follows is // consitent and taken directly from the shapelet code, however. public static double[] zNormalise(double[] input, int startIdx, int subsequenceLength, boolean classValOn) { double mean; double stdv; int classValPenalty = classValOn ? 1 : 0; int inputLength = subsequenceLength - classValPenalty; double[] output = new double[subsequenceLength + classValPenalty]; double seriesTotal = 0; for (int i = startIdx; i < startIdx + inputLength; i++) { seriesTotal += input[i]; } mean = seriesTotal / (double) inputLength; stdv = 0; double temp; for (int i = startIdx; i < startIdx + inputLength; i++) { temp = (input[i] - mean); stdv += temp * temp; } stdv /= (double) inputLength; // if the variance is less than the error correction, just set it to 0, else // calc stdv. stdv = (stdv < ROUNDING_ERROR_CORRECTION) ? 0.0 : Math.sqrt(stdv); for (int i = startIdx; i < inputLength + startIdx; i++) { // if the stdv is 0 then set to 0, else normalise. output[i - startIdx] = (stdv == 0.0) ? 0.0 : ((input[i] - mean) / stdv); } if (classValOn) { output[output.length - 1] = input[input.length - 1]; } return output; } public static void main(String[] args) { try { short exampleOption = 1; switch (exampleOption) { case 0: { // <editor-fold defaultstate="collapsed" desc="An example of the code processing // a single instance"> double[] exampleSeries = { // <editor-fold defaultstate="collapsed" desc="hidden"> 0.706958948, 0.750908517, 0.900082659, 0.392463961, 0.242465518, 0.612627784, 0.965461774, 0.511642268, 0.973824154, 0.765900772, 0.570131418, 0.978983617, 0.71732363, 0.694103358, 0.988679068, 0.516752819, 0.680371205, 0.041150128, 0.438617378, 0.962620183, 0.336994745, 0.109872653, 0.729607701, 0.553675396, 0.907678336, 0.296047233, 0.62139885, 0.047203274, 0.234199203, 0.507061681, 40.1775059, 40.92078108, 40.32998362, 40.24925086, 40.23031747, 40.2612678, 40.24958999, 0.206638348, 0.188084622, 0.435294443, 0.016919806, 0.488749443, 0.536798782, 0.604030646, 0.027743671, 0.475801082, 0.219379181, 0.197770558, 0.180549958, 0.424767962, 0.730424542, 0.050246332, 0.775454296, 0.598464994, 0.041599684, 0.678161584, 0.022935237, 0.572039895, 0.895840616, 0.430037881, 0.606246479, 0.595235683, 0.684102456, 0.876411514, 0.634496091, 0.583138615, 0.83459057, 0.604222487, 0.526759991, 0.796785741, 0.603588625, 0.78414503, 0.676148061, 0.631703028, 0.029891999, 0.66954295, 0.09326132, 0.324903263, 0.329370111, 0.349991934, 0.98813969, 0.212371375, 40.43175799, 40.64309996, 40.25703808, 40.68109205, 40.98675558, 40.67109108, 40.19057322, 0.547164791, 0.148980971, 0.657974529, 0.033686273, 0.925714876, 0.155158131, 0.562893421, 0.55974838, 0.067785579, 0.185605974, 0.056922816, 0.906773429, 0.108453764, 0.857711715, 0.054685775, 0.282340146, 0.356960824, 0.506107616, 0.682422972, 0.845058908, 0.825395344, 0.840462024, 0.452107774, 0.199188375, 0.745644811, 0.318544188, 0.437352361, 0.001509022, 0.325114368, 0.378086159, 0.510979193, 0.053430927, 0.134820265, 0.202091967, 0.365691307, 0.104942853, 0.444478755, 0.021250513, 40.93704671, 40.20245208, 40.87017417, 40.12272305, 40.79370847, 40.01667509, 40.29991657, 0.881084794, 0.015035975, 0.868897876, 0.00632042, 0.922354652, 0.601708676, 0.558058363, 0.11333862, 0.771422385, 0.52350838, 0.392103683, 0.42441807, 0.084006383, 0.810320086, 0.140575367, 0.592926995, 0.136968111, 0.86361884, 0.800409212, 0.361548663, 0.887355284, 0.520255152, 0.85104809, 0.350659883, 0.38558232, 0.963846112, 0.738944264, 0.177064402, 0.27604281, 0.173068454, 0.301392245, 0.327037831, 0.359321481, 40.4284963, 40.63135518, 40.0415674, 40.58448039, 40.7447205, 40.63741215, 40.38637122, 0.333073723, 0.835468558, 0.901962258, 0.661272244, 0.296970939, 0.604075557, 0.43405287, 0.517690996, 0.448041559, 0.100768093, 0.166518799, 0.59463445, 0.853616259, 0.617191115, 0.170413139, 0.46838602, 0.596948951, 0.634140074, 0.72695993, 0.407250642, 0.161077052, 0.017273795, 0.962110794, 0.531243218, 0.076041357, 0.516862396, 0.551316188, 0.854549962, 0.333861949, 0.381543776, 0.952493204, 0.626465371, 0.637232052, 0.918986949, 0.414714591, 0.028046619, 0.927337815, 0.730504031, 0.577524028, 0.738305301, 0.498088814, 0.030412342, 0.892963296, 0.158905784, 0.308830195, 0.001044088, 0.528515062, 0.770532238, 0.148622557, 0.564126052, 0.284379515, 0.912867459, 0.938835582, 0.634984824, 0.151908861, 0.45635823, 0.96444686, 0.773402777, 0.42544929, 0.540827843, 0.017940591, 0.710334758, 40.72691681, 40.51454394, 40.32967767, 40.84169443, 40.56804387, 40.15860845, 40.46282824, 0.451688955, 0.541844839, 0.841712041, 0.360199018, 0.058959662, 0.556940395, 0.632788865, 0.618176594, 0.794095294, 0.016679839, 0.274969095, 0.967616659, 0.50959933, 0.797046729, 0.960273369, 0.820735666, 0.446419259, 0.089017654, 0.192430069, 0.475741946, 0.280867131, 0.342160569, 0.837739216, 0.590364989, 0.82525571, 0.281604012, 0.167508301, 0.2274851, 0.543793246, 0.541841033, 0.002968891, 0.73975265, 0.710442853, 0.056361441, 0.494012768, 40.88467555, 40.32410117, 40.8734326, 40.62995568, 40.20315046, 40.10966019, 40.43205643, 0.600012785, 0.530871599, 0.879191584, 0.995522866, 0.840788635, 0.675717205, 0.708321268, 0.568667757, 0.471350118, 0.084376171, 0.64306147, 0.958564678, 0.851967071, 0.767858501, 0.377896405, 0.355198698, 0.347686315, 0.220245913, 0.66680921, 0.973033751, 0.379253749, 0.671333966, 0.811846499, 0.882194418, 0.906573824, 0.110526759, 0.528251005, 0.594284369, 0.450898007, 0.34381444, 0.078977677, 0.459869753, 0.637764085, 0.934354742, 0.686230405, 0.173913574, 0.837440544, 0.796244826, 0.482733612, 40.88451874, 40.9480389, 40.64721753, 40.36044806, 40.58392222, 40.16336175, 40.18406683, 0.098042009, 0.141072966, 0.485982161, 0.654872193, 0.975890136, 0.419647877, 0.39811089, 0.563886789, 0.968525154, 0.446994618, 0.32338217, 0.360504306, 0.876710065, 0.776301087, 0.444540067, 0.238726928, 0.114215352, 0.904878926, 0.102432501, 0.483207846, 0.271168946, 0.187234805, 0.70038387, 0.714664048, 0.165472715, 0.773527567, 0.072575256, 0.015110261, 0.832353831, 0.511964426, 0.510665358, 0.268989309, 0.386169927, 0.769298622, 0.482800936, 0.370094824, 0.980576579, 0.97774188, 40.1261874, 40.08808535, 40.83331539, 40.18693955, 40.75391492, 40.67115714, 40.97951474, 0.048625932, 0.300809154, 0.076411212, 0.285448268, // </editor-fold> }; int windowSize = 10; SingleInstanceMatrixProfile simp = new SingleInstanceMatrixProfile(exampleSeries, windowSize, 1); for (int i = 0; i < exampleSeries.length - windowSize + 1; i++) { simp.locateBestMatch(i); } System.out.println("Example series:"); for (int a = 0; a < exampleSeries.length; a++) { System.out.print(exampleSeries[a] + ","); } System.out.println("\n\nMatrix Profile"); for (int j = 0; j < exampleSeries.length - windowSize; j++) { System.out.print(simp.distances[j] + ","); } System.out.println("\n\nIndices:"); for (int j = 0; j < exampleSeries.length - windowSize; j++) { System.out.print(simp.indices[j] + ","); } System.out.println(); // </editor-fold> break; } case 1: { // <editor-fold defaultstate="collapsed" desc="An example using GunPoint"> String datapath = "C:/users/sjx07ngu/Dropbox/TSC Problems/"; String datasetName = "GunPoint"; Instances train = DatasetLoading .loadDataNullable(datapath + datasetName + "/" + datasetName + "_TRAIN"); int windowSize = 10; MatrixProfile mp = new MatrixProfile(windowSize); Instances transformedToDistances = mp.transform(train); System.out.println(transformedToDistances); // additional use case: transform to indices too /* * Instances[] transformedToDistancesAndIndices = * mp.processDistancesAndIndices(train); * System.out.println(transformedToDistancesAndIndices[0]+"\n"); * System.out.println(transformedToDistancesAndIndices[1]); */ break; // </editor-fold> } case 2: { // <editor-fold defaultstate="collapsed" desc="An example using GunPoint, but // using a window that is bigger than m/4"> String datapath = "C:/users/sjx07ngu/Dropbox/TSC Problems/"; String datasetName = "GunPoint"; Instances train = DatasetLoading .loadDataNullable(datapath + datasetName + "/" + datasetName + "_TRAIN"); int windowSize = (train.numAttributes() - 1) / 4 + 1; MatrixProfile mp = new MatrixProfile(windowSize); Instances transformedToDistances = mp.transform(train); // Instances[] transformedToDistancesAndIndices = mp.process(train); System.out.println(transformedToDistances); break; // </editor-fold> } default: System.out.println("I've run out of examples!"); break; } } catch (Exception e) { e.printStackTrace(); } } @Override public Instances determineOutputFormat(Instances inputFormat) { int seriesLength = inputFormat.classIndex() >= 0 ? inputFormat.numAttributes() - 1 : inputFormat.numAttributes(); int numOutputAtts = seriesLength + 1 - windowSize; ArrayList<Attribute> atts = new ArrayList<>(); for (int a = 0; a < numOutputAtts; a++) { atts.add(new Attribute("dist_" + a)); } if (inputFormat.classIndex() >= 0) { Attribute target = inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals = new ArrayList<>(); for (int i = 0; i < target.numValues(); i++) { vals.add(target.value(i)); } atts.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances output = new Instances(inputFormat.relationName() + "_matrixProfile", atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) { output.setClassIndex(output.numAttributes() - 1); } return output; } }
24,265
48.421589
204
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/PAA.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.util.ArrayList; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; /** * Filter to reduce dimensionality of a time series into Piecewise Aggregate * Approximation (PAA) form. Default number of intervals = 8 * * @author James */ public class PAA implements Transformer { private int numIntervals = 8; private static final long serialVersionUID = 1L; public int getNumIntervals() { return numIntervals; } public void setNumIntervals(int intervals) { numIntervals = intervals; } public Instances determineOutputFormat(Instances inputFormat) { // Set up instances size and format. ArrayList<Attribute> attributes = new ArrayList<>(); for (int i = 0; i < numIntervals; i++) attributes.add(new Attribute("PAAInterval_" + i)); if (inputFormat.classIndex() >= 0) { // Classification set, set class // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals = new ArrayList<>(target.numValues()); for (int i = 0; i < target.numValues(); i++) { vals.add(target.value(i)); } attributes.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances result = new Instances("PAA" + inputFormat.relationName(), attributes, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } return result; } @Override public Instance transform(Instance inst) { double[] data = inst.toDoubleArray(); // remove class attribute if needed double[] temp; int c = inst.classIndex(); if (c >= 0) { temp = new double[data.length - 1]; System.arraycopy(data, 0, temp, 0, c); // assumes class attribute is in last index data = temp; } double[] intervals = convertInstance(data); // Now in PAA form, extract out the terms and set the attributes of new instance Instance newInstance; if (inst.classIndex() >= 0) newInstance = new DenseInstance(numIntervals + 1); else newInstance = new DenseInstance(numIntervals); for (int j = 0; j < numIntervals; j++) newInstance.setValue(j, intervals[j]); if (inst.classIndex() >= 0) newInstance.setValue(newInstance.numAttributes()-1, inst.classValue()); return newInstance; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i =0; for(TimeSeries ts : inst){ out[i++] = convertInstance(ts.toValueArray()); } return new TimeSeriesInstance(out, inst.getLabelIndex()); } private double[] convertInstance(double[] data) /* * throws Exception { * * if (numIntervals > data.length) throw new Exception( * "Error converting to PAA, number of intervals (" + numIntervals + ") greater" * + " than series length (" + data.length + ")"); */ { double[] intervals = new double[numIntervals]; // counters to keep track of progress towards completion of a frame // potential for data.length % intervals != 0, therefore non-integer // interval length, so weight the boundary data points to effect both // intervals it touches int currentFrame = 0; double realFrameLength = (double) data.length / numIntervals; double frameSum = 0.0, currentFrameSize = 0.0, remaining = 0.0; // PAA conversion for (int i = 0; i < data.length; ++i) { remaining = realFrameLength - currentFrameSize; if (remaining > 1.0) { // just use whole data point frameSum += data[i]; currentFrameSize += 1; } else { // use some portion of data point as needed frameSum += remaining * data[i]; currentFrameSize += remaining; } if (currentFrameSize == realFrameLength) { // if frame complete intervals[currentFrame++] = frameSum / realFrameLength; // store mean // before going onto next datapoint, 'use up' any of the current one on the new // interval // that might not have been used for interval just completed frameSum = (1 - remaining) * data[i]; currentFrameSize = (1 - remaining); } } // i.e. if the last interval didn't write because of double imprecision if (currentFrame == numIntervals - 1) { // if frame complete intervals[currentFrame++] = frameSum / realFrameLength; } return intervals; } public static double[] convertInstance(double[] data, int numIntervals) { PAA paa = new PAA(); paa.setNumIntervals(numIntervals); return paa.convertInstance(data); } public String getRevision() { throw new UnsupportedOperationException("Not supported yet."); // To change body of generated methods, choose // Tools | Templates. } public static void main(String[] args) { // System.out.println("PAAtest\n\n"); // // try { // Instances test = ClassifierTools.loadData("C:\\tempbakeoff\\TSC // Problems\\Car\\Car_TEST.arff"); // PAA paa = new PAA(); // paa.setNumIntervals(2); // Instances result = paa.process(test); // // System.out.println(test); // System.out.println("\n\n\nResults:\n\n"); // System.out.println(result); // } // catch (Exception e) { // System.out.println(e); // } // Jason's Test double[] wavey = { 0.841470985, 0.948984619, 0.997494987, 0.983985947, 0.909297427, 0.778073197, 0.598472144, 0.381660992, 0.141120008, -0.108195135, -0.350783228, -0.571561319, -0.756802495, -0.894989358, -0.977530118, -0.999292789, -0.958924275, -0.858934493, -0.705540326, -0.508279077, -0.279415498 }; PAA paa = new PAA(); paa.setNumIntervals(10); // convert into Instances format ArrayList<Attribute> atts = new ArrayList<>(); DenseInstance ins = new DenseInstance(wavey.length + 1); for (int i = 0; i < wavey.length; i++) { ins.setValue(i, wavey[i]); atts.add(new Attribute("att" + i)); } atts.add(new Attribute("classVal")); ins.setValue(wavey.length, 1); Instances instances = new Instances("blah", atts, 1); instances.setClassIndex(instances.numAttributes() - 1); instances.add(ins); Instances out = paa.transform(instances); for (int i = 0; i < out.numAttributes() - 1; i++) { System.out.print(out.instance(0).value(i) + ","); } System.out.println(); } }
8,193
33.868085
117
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/PACF.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.util.ArrayList; import tsml.data_containers.TSCapabilities; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import utilities.InstanceTools; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.RevisionUtils; import weka.core.Utils; /** * <!-- globalinfo-start --> Implementation of partial autocorrelation function * as a Weka SimpleBatchFilter Series to series transform independent of class * value <!-- globalinfo-end --> <!-- options-start --> Valid options are: * <p/> * * <pre> * -L * set the max lag. * </pre> * * <!-- options-end --> * * * author: Anthony Bagnall circa 2008. Reviewed and tidied up 2019 This should * not really be a batch filter, as it is series to series, but it makes the use * case simpler. */ public class PACF implements Transformer { protected static final int DEFAULT_MAXLAG = 100; /** * Auto correlations. These can be passed to the filter if they have already * been calculated. **/ protected double[] autos; /** Partial auto correlations, calculated by */ protected double[][] partials; /** Defaults to 1/4 length of series or 100, whichever is smaller */ protected int maxLag = DEFAULT_MAXLAG; /** * If the series are normalised, the calculation can be done much more * efficiently */ private boolean normalized = false; // if true, assum zero mean and unit variance /** Currently assumed constant for all series. Have to, using instances* */ protected int seriesLength; /** * Whatever the maxLag value, we always ignore at least the endTerms * correlations since they are based on too little data and hence unreliable */ protected int endTerms = 4; public void setMaxLag(int a) { maxLag = a; } public void setNormalized(boolean flag) { normalized = flag; } /** * ACF/PACF can only operate on real valued attributes with no missing values * * @return Capabilities object */ @Override public TSCapabilities getTSCapabilities() { TSCapabilities result = new TSCapabilities(this); // result.disableAll(); // // attributes must be numeric // // Here add in relational when ready // result.enable(Capabilities.Capability.NUMERIC_ATTRIBUTES); // // result.enable(Capabilities.Capability.MISSING_VALUES); // // class // result.enableAllClasses(); // result.enable(Capabilities.Capability.MISSING_CLASS_VALUES); // result.enable(Capabilities.Capability.NO_CLASS); return result; } @Override public Instances determineOutputFormat(Instances inputFormat) { // Check capabilities for the filter. Can only handle real valued, no missing. // getCapabilities().testWithFail(inputFormat); seriesLength = inputFormat.numAttributes(); if (inputFormat.classIndex() >= 0) seriesLength--; if (maxLag > seriesLength - endTerms) maxLag = seriesLength - endTerms; if (maxLag < 0) maxLag = inputFormat.numAttributes() - 1; // Set up instances size and format. ArrayList<Attribute> atts = new ArrayList<>(); String name; for (int i = 0; i < maxLag; i++) { name = "PACF_" + i; atts.add(new Attribute(name)); } if (inputFormat.classIndex() >= 0) { // Classification set, set class // Get the class values Attribute target = inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals = new ArrayList<>(target.numValues()); for (int i = 0; i < target.numValues(); i++) vals.add(target.value(i)); atts.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances result = new Instances("PACF" + inputFormat.relationName(), atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) result.setClassIndex(result.numAttributes() - 1); return result; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i =0; for(TimeSeries ts : inst){ out[i++] = convertInstance(ts.toValueArray()); } return new TimeSeriesInstance(out, inst.getLabelIndex()); } @Override public Instance transform(Instance inst) { double[] d = InstanceTools.ConvertInstanceToArrayRemovingClassValue(inst); double[] pi = convertInstance(d); int length = pi.length + (inst.classIndex() >= 0 ? 1 : 0); // ACF atts + PACF atts + optional classvalue. // 6. Stuff back into new Instances. Instance out = new DenseInstance(length); // Set class value. if (inst.classIndex() >= 0) { out.setValue(length - 1, inst.classValue()); } for (int k = 0; k < pi.length; k++) { out.setValue(k, pi[k]); } return out; } private double[] convertInstance(double[] d) { // 2. Fit Autocorrelations, if not already set externally autos = ACF.fitAutoCorrelations(d, maxLag); // 3. Form Partials partials = formPartials(autos); // 5. Find parameters double[] pi = new double[maxLag]; for (int k = 0; k < maxLag; k++) { // Set NANs to zero if (Double.isNaN(partials[k][k]) || Double.isInfinite(partials[k][k])) { pi[k] = 0; } else pi[k] = partials[k][k]; } return pi; } /** * Finds partial autocorrelation function using Durban-Leverson recursions * * @param acf the ACF * @return */ public static double[][] formPartials(double[] acf) { // Using the Durban-Leverson int p = acf.length; double[][] phi = new double[p][p]; double numerator, denominator; phi[0][0] = acf[0]; for (int k = 1; k < p; k++) { // Find diagonal k,k // Naive implementation, should be able to do with running sums? numerator = acf[k]; for (int i = 0; i < k; i++) numerator -= phi[i][k - 1] * acf[k - 1 - i]; denominator = 1; for (int i = 0; i < k; i++) denominator -= phi[k - 1 - i][k - 1] * acf[k - 1 - i]; if (denominator != 0)// What to do otherwise? phi[k][k] = numerator / denominator; // Find terms 1 to k-1 for (int i = 0; i < k; i++) phi[i][k] = phi[i][k - 1] - phi[k][k] * phi[k - 1 - i][k - 1]; } return phi; } public double[][] getPartials() { return partials; } public String getRevision() { return RevisionUtils.extract("$Revision: 2:2019 $"); } public void setOptions(String[] options) throws Exception { String maxLagString = Utils.getOption('L', options); if (maxLagString.length() != 0) this.maxLag = Integer.parseInt(maxLagString); else this.maxLag = DEFAULT_MAXLAG; } public static void main(String[] args) { } }
8,201
32.341463
113
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/PCA.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.io.File; import java.util.ArrayList; import java.util.List; import experiments.data.DatasetLoading; import tsml.classifiers.shapelet_based.ShapeletTransformClassifier; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.data_containers.utilities.Converter; import tsml.data_containers.utilities.Splitter; import weka.attributeSelection.PrincipalComponents; import weka.core.Instance; import weka.core.Instances; /** * Transformer to generate Principal Components. Uses weka attribute selection * PrincipalComponents. There is also a weka Filter PrincipalComponents, but it * is confusingly structured, like all Weka Filters, and has protected methods. * The down side of using the ArttributeSelection version is that it does not * have the capability to set a maximum number of attributes. This * implementation creates a full transform then deletes attributes. This could * be wasteful in memory for large attribute spaces (although PCA will * internally need mxm memory anyway. * * This assumes that the PrincipalComponents sorts the eignevectors so the first * has most variance. I'm 99.9% sure it does * * @author Tony Bagnall (ajb) */ public class PCA implements TrainableTransformer { private int numAttributesToKeep; // changed this to constructor as you could change number of atts to keep after // fitting private PrincipalComponents pca; private boolean isFit = false; private ConstantAttributeRemover remover; public PCA() { this(100); } public PCA(int attsToKeep) { pca = new PrincipalComponents(); numAttributesToKeep = Math.max(1, attsToKeep); System.out.println(numAttributesToKeep); } @Override public void fit(Instances data) { numAttributesToKeep = Math.min(data.numAttributes() - 1, numAttributesToKeep); try { // Build the evaluator // this method is sets the names of the componenets used. pca.setMaximumAttributeNames(numAttributesToKeep); pca.setVarianceCovered(1.0); pca.buildEvaluator(data); isFit = true; } catch (Exception e) { throw new RuntimeException(" Error in Transformers/PCA when fitting the PCA transform"); } } @Override public boolean isFit() { return isFit; } @Override public Instances transform(Instances data) { if (!isFit) throw new RuntimeException("Fit PCA before transforming"); Instances newData = null; try { newData = pca.transformedData(data); if (remover == null) { remover = new ConstantAttributeRemover(); remover.fit(newData); } newData = remover.transform(newData); } catch (Exception e) { throw new RuntimeException(" Error in Transformers/PCA when performing the PCA transform: " + e); } return newData; } @Override public Instance transform(Instance inst) { if (!isFit) throw new RuntimeException("Fit PCA before transforming"); Instance newInst = null; try { newInst = pca.convertInstance(inst); /* * for(int del:attsToRemove) newInst.deleteAttributeAt(del); */ // TODO: replace with Truncator while (newInst.numAttributes() - 1 > numAttributesToKeep) newInst.deleteAttributeAt(newInst.numAttributes() - 2); } catch (Exception e) { e.printStackTrace(); } return newInst; } @Override public Instances determineOutputFormat(Instances data) throws IllegalArgumentException { if (data.numAttributes() - 1 < numAttributesToKeep) numAttributesToKeep = data.numAttributes() - 1; return null; } public static void main(String[] args) throws Exception { // Aarons local path for testing. String local_path = "D:\\Work\\Data\\Univariate_ts\\"; // Aarons local path for testing. // String m_local_path = "D:\\Work\\Data\\Multivariate_ts\\"; // String m_local_path_orig = "D:\\Work\\Data\\Multivariate_arff\\"; String dataset_name = "ChinaTown"; Instances train = DatasetLoading .loadData(local_path + dataset_name + File.separator + dataset_name + "_TRAIN.ts"); Instances test = DatasetLoading .loadData(local_path + dataset_name + File.separator + dataset_name + "_TEST.ts"); /* * Instances train= DatasetLoading.loadData( * "Z:\\ArchiveData\\Univariate_arff\\Chinatown\\Chinatown_TRAIN.arff"); * Instances test= DatasetLoading.loadData( * "Z:\\ArchiveData\\Univariate_arff\\Chinatown\\Chinatown_TEST.arff"); */ /* * PCA pca=new PCA(1); pca.fit(train); Instances trans=pca.transform(train); // * Instances trans2=pca.transform(test); * System.out.println(" Transfrom 1"+trans); * System.out.println("Num attribvvutes = "+trans.numAttributes()); */ // System.out.println(" Transfrom 2"+trans2); ShapeletTransformClassifier st = new ShapeletTransformClassifier(); st.setPCA(true, 100); st.buildClassifier(train); double acc = utilities.ClassifierTools.accuracy(test, st); System.out.println("acc: " + acc); } private PrincipalComponents[] pca_transforms; private int[] attributesToKeep_dims; private String[] trainLabels; @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { List<TimeSeriesInstance> split_inst = Splitter.splitTimeSeriesInstance(inst); List<TimeSeriesInstance> out = new ArrayList<>(split_inst.size()); for(int i=0; i<pca_transforms.length; i++){ pca = pca_transforms[i]; numAttributesToKeep = attributesToKeep_dims[i]; out.add(Converter.fromArff(transform(Converter.toArff(split_inst.get(i), trainLabels)))); } return Splitter.mergeTimeSeriesInstance(out); } @Override public void fit(TimeSeriesInstances data) { List<TimeSeriesInstances> split = Splitter.splitTimeSeriesInstances(data); pca_transforms = new PrincipalComponents[split.size()]; attributesToKeep_dims = new int[split.size()]; trainLabels = data.getClassLabels(); for(int i=0; i<data.getMaxNumDimensions(); i++){ pca_transforms[i] = new PrincipalComponents(); pca = pca_transforms[i]; //set the ref. fit(Converter.toArff(split.get(i))); attributesToKeep_dims[i] = numAttributesToKeep; } isFit=true; } }
7,672
34.688372
116
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Padder.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import weka.core.Instance; import weka.core.Instances; /** * Class to pad series to make them all equal length. In the ARFF data model, unequal length series are padded with * missing values to avoid ragged arrays. This class fills in the series based on the train data. It is assumed the * train and test data in ARFF format are already padded to be the same length. This may have involved some prior preprocessing. * * There is an edge case when the longest series in the Test data is longer than the longest in the Train data. In this * scenario, the over long test instance is truncated in Transform. * * todo: implement univariate * todo: implement multivariate * todo: handle edge case * todo: test all * @author Tony Bagnall 18/4/2020 */ public class Padder implements TrainableTransformer{ private int finalNumberOfAttributes; enum PaddingType{FLAT,NOISE} private PaddingType padType=PaddingType.FLAT; private boolean isFit; /** * Finds the length all series will be padded to. Not currently required, but this could be enhanced to remove * instances with lengths that could be considered outliers. * @param data */ @Override public void fit(Instances data) { if(data.attribute(0).isRelationValued()) { //Multivariate Instances in=data.instance(0).relationalValue(0); finalNumberOfAttributes=in.numAttributes(); } else finalNumberOfAttributes=data.numAttributes()-1; isFit = true; } @Override public boolean isFit() { return isFit; } /** * * It uses the series mean and variance (if noise is added) * to pad. * @param data * @return */ @Override public Instances transform(Instances data) { if(data.attribute(0).isRelationValued()) { //Multivariate } else{ } return null; } @Override public Instance transform(Instance inst) { return null; } @Override public Instances determineOutputFormat(Instances data) throws IllegalArgumentException { return null; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { // TODO Auto-generated method stub return null; } @Override public void fit(TimeSeriesInstances data) { // TODO Auto-generated method stub } }
3,294
28.419643
128
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/PowerCepstrum.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import java.util.ArrayList; import tsml.data_containers.TimeSeriesInstance; /** * * @author ajb */ public class PowerCepstrum extends PowerSpectrum{ public PowerCepstrum(){} @Override public Instances determineOutputFormat(Instances inputFormat) { //Set up instances size and format. int length=(fftTransformer.findLength(inputFormat)); length/=2; ArrayList<Attribute> atts=new ArrayList<>(); String name; for(int i=0;i<length;i++){ name = "PowerSpectrum_"+i; atts.add(new Attribute(name)); } if(inputFormat.classIndex()>=0){ //Classification set, set class //Get the class values as a fast vector Attribute target =inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals=new ArrayList<>(target.numValues()); for(int i=0;i<target.numValues();i++) vals.add(target.value(i)); atts.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(),vals)); } Instances result = new Instances("Cepstrum"+inputFormat.relationName(),atts,inputFormat.numInstances()); if(inputFormat.classIndex()>=0) result.setClassIndex(result.numAttributes()-1); return result; } @Override public Instance transform(Instance inst){ Instance out = super.transform(inst); //log dataset for(int j=0;j<out.numAttributes();j++){ if(j!=out.classIndex()) out.setValue(j,Math.log(out.value(j))); } double[] ar=out.toDoubleArray(); //Have to pad int n = (int)MathsPower2.roundPow2(ar.length-1); if(n<ar.length-1) n*=2; FFT.Complex[] complex=new FFT.Complex[n]; for(int j=0;j<ar.length-1;j++) complex[j]=new FFT.Complex(ar[j],0); for(int j=ar.length-1;j<n;j++) complex[j]=new FFT.Complex(0,0); //Take inverse FFT inverseFFT(complex,complex.length); //Square the terms for the PowerCepstrum for(int j=0;j<ar.length-1;j++) out.setValue(j,complex[j].real*complex[j].real+complex[j].imag*complex[j].imag); return out; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { TimeSeriesInstance f_inst = super.transform(inst); double[][] values = f_inst.toValueArray(); //log all the output/ for(int i=0; i<values.length;i++){ int length = values[i].length; for(int j=0; j<length; j++) values[i][j] = Math.log(values[i][j]); //Have to pad int n = (int)MathsPower2.roundPow2(length); if(n<length) n*=2; FFT.Complex[] complex=new FFT.Complex[n]; for(int j=0;j<length;j++) complex[j]=new FFT.Complex(values[i][j],0); for(int j=length;j<n;j++) complex[j]=new FFT.Complex(0,0); //Take inverse FFT inverseFFT(complex,complex.length); //Square the terms for the PowerCepstrum for(int j=0; j<length; j++) values[i][j] = complex[j].real*complex[j].real+complex[j].imag*complex[j].imag; } return new TimeSeriesInstance(values, inst.getLabelIndex()); } public void logDataSet(Instances out ){ for(int i=0;i<out.numInstances();i++){ Instance ins=out.instance(i); for(int j=0;j<ins.numAttributes();j++){ if(j!=ins.classIndex()) ins.setValue(j,Math.log(ins.value(j))); } } } }
4,608
30.568493
112
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/PowerSpectrum.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import experiments.data.DatasetLoading; import fileIO.OutFile; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; /** * <!-- globalinfo-start --> Implementation of power spectrum function as a Weka * SimpleBatchFilter Series to series transform independent of class value <!-- * globalinfo-end --> <!-- options-start --> Valid options are: * <p/> * TO DO <!-- options-end --> * * * author: Anthony Bagnall circa 2008. Reviewed and tidied up 2019 */ public class PowerSpectrum extends FFT { boolean log = false; FFT fftTransformer; public void takeLogs(boolean x) { log = x; } public PowerSpectrum() { fftTransformer = new FFT(); fftTransformer.useDFT(); } public void useFFT() { fftTransformer.useFFT(); } @Override public Instances determineOutputFormat(Instances inputFormat) { // Set up instances size and format. int length = (fftTransformer.findLength(inputFormat)); length /= 2; ArrayList<Attribute> atts = new ArrayList<>(); String name; for (int i = 0; i < length; i++) { name = "PowerSpectrum_" + i; atts.add(new Attribute(name)); } if (inputFormat.classIndex() >= 0) { // Classification set, set class // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals = new ArrayList(target.numValues()); for (int i = 0; i < target.numValues(); i++) vals.add(target.value(i)); atts.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances result = new Instances("PowerSpectrum" + inputFormat.relationName(), atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) result.setClassIndex(result.numAttributes() - 1); return result; } @Override public Instance transform(Instance inst){ Instance f=fftTransformer.transform(inst); int length = f.numAttributes(); if (inst.classIndex() >= 0) length--; length /= 2; Instance out=new DenseInstance(length + (inst.classIndex() >= 0 ? 1 : 0)); if(log) { double l1; for(int j=0;j<length;j++){ l1= Math.sqrt(f.value(j*2)*f.value(j*2)+f.value(j*2+1)*f.value(j*2+1)); out.setValue(j,Math.log(l1)); } } else{ for (int j = 0; j < length; j++) { out.setValue(j, Math.sqrt(f.value(j * 2) * f.value(j * 2) + f.value(j * 2 + 1) * f.value(j * 2 + 1))); } } //Set class value. if(inst.classIndex()>=0) out.setValue(out.numAttributes()-1, inst.classValue()); return out; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { TimeSeriesInstance f_inst =fftTransformer.transform(inst); List<List<Double>> out_data = new ArrayList<>(); int length = inst.getMaxLength() / 2; for(TimeSeries f : f_inst){ List<Double> vals = new ArrayList<>(length); if(log){ double l1; for(int j=0;j<length;j++){ l1= Math.sqrt(f.getValue(j*2)*f.getValue(j*2)+f.getValue(j*2+1)*f.getValue(j*2+1)); vals.add(Math.log(l1)); } } else{ for (int j = 0; j < length; j++) { vals.add(Math.sqrt(f.getValue(j * 2) * f.getValue(j * 2) + f.getValue(j * 2 + 1) * f.getValue(j * 2 + 1))); } } out_data.add(vals); } return new TimeSeriesInstance(out_data, inst.getLabelIndex()); } public static void waferTest() { /* * Instances a=WekaMethods. * loadDataThrowable("C:\\Research\\Data\\Time Series Data\\Time Series Classification\\wafer\\wafer_TRAIN" * ); Instances b=WekaMethods. * loadDataThrowable("C:\\Research\\Data\\Time Series Data\\Time Series Classification\\wafer\\wafer_TEST" * ); PowerSpectrum ps=new PowerSpectrum(); try{ Instances c=ps.process(a); * Instances d=ps.process(b); OutFile of = new * OutFile("C:\\Research\\Data\\Time Series Data\\Time Series Classification\\wafer\\wafer_TRAIN_PS.arff" * ); OutFile of2 = new * OutFile("C:\\Research\\Data\\Time Series Data\\Time Series Classification\\wafer\\wafer_TEST_PS.arff" * ); of.writeString(c.toString()); of2.writeString(d.toString()); * }catch(Exception e){ System.out.println(" Exception ="+e); } */ } /* Transform by the built in filter */ public static double[] powerSpectrum(double[] d) { // Check power of 2 if (((d.length) & (d.length - 1)) != 0) // Not a power of 2 return null; FFT.Complex[] c = new FFT.Complex[d.length]; for (int j = 0; j < d.length; j++) { c[j] = new FFT.Complex(d[j], 0.0); } FFT f = new FFT(); f.fft(c, c.length); double[] ps = new double[c.length]; for (int i = 0; i < c.length; i++) ps[i] = c[i].getReal() * c[i].getReal() + c[i].getImag() * c[i].getImag(); return ps; } public static Instances loadData(String fullPath) { Instances d = null; FileReader r; int nosAtts; try { r = new FileReader(fullPath + ".arff"); d = new Instances(r); d.setClassIndex(d.numAttributes() - 1); } catch (Exception e) { System.out.println("Unable to load data on path " + fullPath + " Exception thrown =" + e); e.printStackTrace(); System.exit(0); } return d; } public static void matlabComparison() { // MATLAB Output generated by // Power of 2: use FFT // Create set of instances with 16 attributes, with values // Case 1: All Zeros // Case 2: 1,2,...16 // Case 3: -8,-7, -6,...,0,1,...7 // Case 4: 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1 /* * PowerSpectrum ps=new PowerSpectrum(); * * Instances test1=ClassifierTools. * loadDataThrowable("C:\\Users\\ajb\\Dropbox\\TSC Problems\\TestData\\FFT_test1" * ); Instances test2=ClassifierTools. * loadDataThrowable("C:\\Users\\ajb\\Dropbox\\TSC Problems\\TestData\\FFT_test2" * ); Instances t2; try{ t2=ps.process(test1); * System.out.println(" TEST 1 PS ="+t2); t2=ps.process(test2); * System.out.println(" TEST 2 PS ="+t2); * * * }catch(Exception e){ System.out.println(" Errrrrrr = "+e); * e.printStackTrace(); System.exit(0); } */ // Not a power of 2: use padding // Not a power of 2: use truncate // Not a power of 2: use DFT } public static void main(String[] args) { String problemPath = "E:/TSCProblems/"; String resultsPath = "E:/Temp/"; String datasetName = "ItalyPowerDemand"; Instances train = DatasetLoading .loadDataNullable("E:/TSCProblems/" + datasetName + "/" + datasetName + "_TRAIN"); PowerSpectrum ps = new PowerSpectrum(); try { Instances trans = ps.transform(train); OutFile out = new OutFile(resultsPath + datasetName + "PS_JAVA.csv"); out.writeLine(datasetName); for (Instance ins : trans) { double[] d = ins.toDoubleArray(); for (int j = 0; j < d.length; j++) { if (j != trans.classIndex()) out.writeString(d[j] + ","); } out.writeString("\n"); } } catch (Exception ex) { System.out.println("ERROR IN DEMO"); Logger.getLogger(ACF.class.getName()).log(Level.SEVERE, null, ex); } } }
9,211
34.705426
127
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/ROCKET.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.concurrent.*; import org.apache.commons.lang3.ArrayUtils; import tsml.classifiers.MultiThreadable; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.data_containers.utilities.TimeSeriesSummaryStatistics; import utilities.generic_storage.Pair; import weka.core.*; import static utilities.ClusteringUtilities.zNormalise; import static utilities.StatisticalUtilities.dot; import static utilities.Utilities.extractTimeSeries; import static utilities.multivariate_tools.MultivariateInstanceTools.*; /** * ROCKET transformer. Returns the max and proportion of positive values (PPV) of n randomly initialised * convolutional kernels. * * @article{dempster2020rocket, * title={ROCKET: Exceptionally fast and accurate time series classification using random convolutional kernels}, * author={Dempster, Angus and Petitjean, Fran{\c{c}}ois and Webb, Geoffrey I}, * journal={Data Mining and Knowledge Discovery}, * volume={34}, * number={5}, * pages={1454--1495}, * year={2020}, * publisher={Springer} * } * * Transform based on sktime python implementation by the author: * https://github.com/alan-turing-institute/sktime/blob/master/sktime/transformers/series_as_features/rocket.py * * @author Aaron Bostrom, Matthew Middlehurst */ public class ROCKET implements TrainableTransformer, Randomizable, MultiThreadable { private int numKernels = 10000; private boolean normalise = true; private int seed; private boolean multithreading = false; private ExecutorService ex; private boolean fit = false; private int[] candidateLengths = { 7, 9, 11 }; private int[] numSampledDimensions, dimensions; private int[] lengths, dilations, paddings; private double[] weights, biases; public ROCKET(){ } public ROCKET(int numKernels){ this.numKernels = numKernels; } @Override public int getSeed() { return seed; } public int getNumKernels() { return numKernels; } @Override public void setSeed(int seed) { this.seed = seed; } public void setNumKernels(int numKernels){ this.numKernels = numKernels; } public void setNormalise(boolean normalise){ this.normalise = normalise; } @Override public boolean isFit() { return fit; } @Override public void enableMultiThreading(int numThreads){ multithreading = true; ex = Executors.newFixedThreadPool(numThreads); } @Override public Instances determineOutputFormat(Instances data) throws IllegalArgumentException { ArrayList<Attribute> atts = new ArrayList<>(); for (int i = 0; i < numKernels * 2; i++) { atts.add(new Attribute("att" + i)); } if (data.classIndex() >= 0) atts.add(data.classAttribute()); Instances transformedData = new Instances("ROCKETTransform", atts, data.numInstances()); if (data.classIndex() >= 0) transformedData.setClassIndex(transformedData.numAttributes() - 1); return transformedData; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] output = new double[1][]; if (multithreading){ output[0] = transformRocketMultithread(inst.toValueArray()); } else { output[0] = transformRocket(inst.toValueArray()); } return new TimeSeriesInstance(output, inst.getLabelIndex()); } @Override public Instance transform(Instance inst) { if (!fit) { System.err.println("Must fit ROCKET prior to tranformation."); return null; } double[][] data; if (inst.dataset().checkForAttributeType(Attribute.RELATIONAL)) { data = convertMultiInstanceToArrays(splitMultivariateInstance(inst)); } else{ data = new double[1][]; data[0] = extractTimeSeries(inst); } double[] transform; if (multithreading){ transform = transformRocketMultithread(data); } else{ transform = transformRocket(data); } double[] output = new double[numKernels * 2 + 1]; System.arraycopy(transform, 0, output, 0, numKernels * 2); output[output.length - 1] = inst.classValue(); return new DenseInstance(1, output); } private double[] transformRocket(double[][] inst) { if (normalise){ for (double[] dim : inst) { zNormalise(dim); } } // apply kernels to the dataset. double[] output = new double[numKernels * 2]; // 2 features per kernel int a1 = 0, a2 = 0, a3 = 0, b1, b2; // for weights, channel indices and features for (int i = 0; i < numKernels; i++) { b1 = a1 + numSampledDimensions[i] * lengths[i]; b2 = a2 + numSampledDimensions[i]; Pair<Double, Double> out = applyKernel(inst, ArrayUtils.subarray(weights, a1, b1), lengths[i], biases[i], dilations[i], paddings[i], numSampledDimensions[i], ArrayUtils.subarray(dimensions, a2, b2)); output[a3] = out.var1; output[a3 + 1] = out.var2; a1 = b1; a2 = b2; a3 += 2; } return output; } private double[] transformRocketMultithread(double[][] inst){ if (normalise){ for (double[] dim : inst) { zNormalise(dim); } } ArrayList<Future<Pair<Double, Double>>> futures = new ArrayList<>(numKernels); int a1 = 0, a2 = 0, b1, b2; for (int i = 0; i < numKernels; ++i) { b1 = a1 + numSampledDimensions[i] * lengths[i]; b2 = a2 + numSampledDimensions[i]; Kernel k = new Kernel(ArrayUtils.subarray(weights, a1, b1), lengths[i], biases[i], dilations[i], paddings[i], numSampledDimensions[i], ArrayUtils.subarray(dimensions, a2, b2)); futures.add(ex.submit(new TransformThread(i, inst, k))); a1 = b1; a2 = b2; } double[] output = new double[numKernels * 2]; int a3 = 0; for (Future<Pair<Double, Double>> f : futures) { Pair<Double, Double> out; try { out = f.get(); } catch (Exception e) { e.printStackTrace(); return null; } output[a3] = out.var1; output[a3 + 1] = out.var2; a3 += 2; } return output; } @Override public void fit(TimeSeriesInstances data) { if (multithreading){ fitRocketMultithread(data.getMaxLength(), data.getMaxNumDimensions()); } else { fitRocket(data.getMaxLength(), data.getMaxNumDimensions()); } } @Override public void fit(Instances data) { int inputLength, numDimensions; if (data.checkForAttributeType(Attribute.RELATIONAL)){ inputLength = channelLength(data); numDimensions = numDimensions(data); } else{ inputLength = data.classIndex() > -1 ? data.numAttributes() - 1 : data.numAttributes(); numDimensions = 1; } if (multithreading){ fitRocketMultithread(inputLength, numDimensions); } else{ fitRocket(inputLength, numDimensions); } fit = true; } private void fitRocket(int inputLength, int numDimensions){ Random random = new Random(seed); // generate random kernel lengths between 7,9 or 11, for numKernels. lengths = sampleLengths(random, candidateLengths, numKernels); // randomly select number of dimensions for each kernel numSampledDimensions = new int[numKernels]; if (numDimensions == 1){ Arrays.fill(numSampledDimensions, 1); } else{ for (int i = 0; i < numKernels; i++) { int limit = Math.min(numDimensions, lengths[i]); // convert to base 2 log. log2(b) = log10(b) / log10(2) double log2 = Math.log(limit + 1) / Math.log(2.0); numSampledDimensions[i] = (int) Math.floor(Math.pow(2.0, uniform(random, 0, log2))); } } dimensions = new int[Arrays.stream(numSampledDimensions).sum()]; // generate init values // weights - this should be the size of all the lengths for each dimension summed weights = new double[dot(lengths, numSampledDimensions)]; biases = new double[numKernels]; dilations = new int[numKernels]; paddings = new int[numKernels]; int a1 = 0, a2 = 0, b1, b2; // for weights and channel indices for (int i = 0; i < numKernels; i++) { // select weights for each dimension double[][] _weights = new double[numSampledDimensions[i]][]; for (int n = 0; n < numSampledDimensions[i]; n++) { _weights[n] = normalDist(random, lengths[i]); } for (int n = 0; n < numSampledDimensions[i]; n++) { b1 = a1 + lengths[i]; double mean = TimeSeriesSummaryStatistics.mean(_weights[n]); for (int j = a1; j < b1; ++j) { weights[j] = _weights[n][j - a1] - mean; } a1 = b1; } // randomly select dimensions for kernel if (numDimensions > 1){ ArrayList<Integer> al = new ArrayList<>(numDimensions); for (int n = 0; n < numDimensions; n++) { al.add(n); } b2 = a2 + numSampledDimensions[i]; for (int j = a2; j < b2; j++) { dimensions[j] = al.remove(random.nextInt(al.size())); } a2 = b2; } // draw uniform random sample from 0-1 and shift it to -1 to 1. biases[i] = (random.nextDouble() * 2.0) - 1.0; double value = (double) (inputLength - 1) / (double) (lengths[i] - 1); // convert to base 2 log. log2(b) = log10(b) / log10(2) double log2 = Math.log(value) / Math.log(2.0); dilations[i] = (int) Math.floor(Math.pow(2.0, uniform(random, 0, log2))); paddings[i] = random.nextInt(2) == 1 ? Math.floorDiv((lengths[i] - 1) * dilations[i], 2) : 0; } } private void fitRocketMultithread(int inputLength, int numDimensions) { ArrayList<Future<Kernel>> futures = new ArrayList<>(numKernels); lengths = new int[numKernels]; numSampledDimensions = new int[numKernels]; int[][] tempDimensions = new int[numKernels][]; double[][] tempWeights = new double[numKernels][]; biases = new double[numKernels]; dilations = new int[numKernels]; paddings = new int[numKernels]; for (int i = 0; i < numKernels; ++i) { futures.add(ex.submit(new FitThread(i, inputLength, numDimensions))); } int idx = 0; for (Future<Kernel> f : futures) { Kernel k; try { k = f.get(); } catch (Exception e) { e.printStackTrace(); return; } lengths[idx] = k.length; numSampledDimensions[idx] = k.numSampledDimensions; tempDimensions[idx] = k.dimensions; tempWeights[idx] = k.weights; biases[idx] = k.bias; dilations[idx] = k.dilation; paddings[idx] = k.padding; idx++; } dimensions = new int[Arrays.stream(numSampledDimensions).sum()]; weights = new double[dot(lengths, numSampledDimensions)]; int a1 = 0, a2 = 0; // for weights and channel indices for (int i = 0; i < numKernels; ++i) { System.arraycopy(tempWeights[i], 0, weights, a1, tempWeights[i].length); a1 += tempWeights[i].length; System.arraycopy(tempDimensions[i], 0, dimensions, a2, numSampledDimensions[i]); a2 += numSampledDimensions[i]; } } private static Pair<Double, Double> applyKernel(double[][] inst, double[] weights, int length, double bias, int dilation, int padding, int numSampledDimensions, int[] dimensions) { int inputLength = inst[0].length; int outputLength = (inputLength + (2 * padding)) - ((length - 1) * dilation); double _ppv = 0; double _max = -99999999; int end = (inputLength + padding) - ((length - 1) * dilation); for (int i = -padding; i < end; i++) { double _sum = bias; int index = i; for (int j = 0; j < length; j++) { if (index > -1 && index < inputLength) { for (int n = 0; n < numSampledDimensions; n++) { _sum = _sum + weights[j + n * numSampledDimensions] * inst[dimensions[n]][index]; } } index = index + dilation; } if (_sum > _max) _max = _sum; if (_sum > 0) _ppv += 1; } return new Pair<>(_ppv / outputLength, _max); } private static double uniform(Random rand, double a, double b) { return a + rand.nextDouble() * (b - a); } private static double[] normalDist(Random rand, int size) { double[] out = new double[size]; for (int i = 0; i < size; ++i) out[i] = rand.nextGaussian(); return out; } private static int[] sampleLengths(Random random, int[] samples, int size) { int[] out = new int[size]; for (int i = 0; i < size; ++i) { out[i] = samples[random.nextInt(samples.length)]; } return out; } public void addKernels(ROCKET rocket){ if (!fit){ lengths = new int[0]; numSampledDimensions = new int[0]; dimensions = new int[0]; weights = new double[0]; biases = new double[0]; dilations = new int[0]; paddings = new int[0]; fit = true; } lengths = ArrayUtils.addAll(lengths, rocket.lengths); numSampledDimensions = ArrayUtils.addAll(numSampledDimensions, rocket.numSampledDimensions); dimensions = ArrayUtils.addAll(dimensions, rocket.dimensions); weights = ArrayUtils.addAll(weights, rocket.weights); biases = ArrayUtils.addAll(biases, rocket.biases); dilations = ArrayUtils.addAll(dilations, rocket.dilations); paddings = ArrayUtils.addAll(paddings, rocket.paddings); numKernels += rocket.numKernels; } private static class Kernel { int numSampledDimensions; int[] dimensions; int length, dilation, padding; double[] weights; double bias; public Kernel() { } public Kernel(double[] weights, int length, double bias, int dilation, int padding, int numSampledDimensions, int[] dimensions) { this.weights = weights; this.length = length; this.bias = bias; this.dilation = dilation; this.padding = padding; this.numSampledDimensions = numSampledDimensions; this.dimensions = dimensions; } } private class TransformThread implements Callable<Pair<Double, Double>> { int i; double[][] inst; Kernel k; public TransformThread(int i, double[][] inst, Kernel k){ this.i = i; this.inst = inst; this.k = k; } @Override public Pair<Double, Double> call() { int inputLength = inst[0].length; int outputLength = (inputLength + (2 * k.padding)) - ((k.length - 1) * k.dilation); double _ppv = 0; double _max = -99999999; int end = (inputLength + k.padding) - ((k.length - 1) * k.dilation); for (int i = -k.padding; i < end; i++) { double _sum = k.bias; int index = i; for (int j = 0; j < k.length; j++) { if (index > -1 && index < inputLength) { for (int n = 0; n < k.numSampledDimensions; n++) { _sum = _sum + k.weights[j + n * k.numSampledDimensions] * inst[k.dimensions[n]][index]; } } index = index + k.dilation; } if (_sum > _max) _max = _sum; if (_sum > 0) _ppv += 1; } return new Pair<>(_ppv / outputLength, _max); } } private class FitThread implements Callable<Kernel>{ int i; int inputLength; int numDimensions; public FitThread(int i, int inputLength, int numDimensions){ this.i = i; this.inputLength = inputLength; this.numDimensions = numDimensions; } @Override public Kernel call() { Kernel k = new Kernel(); Random random = new Random(seed + i * numKernels); k.length = candidateLengths[random.nextInt(candidateLengths.length)]; // randomly select number of dimensions for each kernel if (numDimensions == 1){ k.numSampledDimensions = 1; } else{ int limit = Math.min(numDimensions, k.length); // convert to base 2 log. log2(b) = log10(b) / log10(2) double log2 = Math.log(limit + 1) / Math.log(2.0); k.numSampledDimensions = (int) Math.floor(Math.pow(2.0, uniform(random, 0, log2))); } // select weights for each dimension double[][] _weights = new double[k.numSampledDimensions][]; for (int n = 0; n < k.numSampledDimensions; n++) { _weights[n] = normalDist(random, k.length); } k.weights = new double[k.length * k.numSampledDimensions]; int a1 = 0, b1; for (int n = 0; n < k.numSampledDimensions; n++) { b1 = a1 + k.length; double mean = TimeSeriesSummaryStatistics.mean(_weights[n]); for (int j = a1; j < b1; ++j) { k.weights[j] = _weights[n][j - a1] - mean; } a1 = b1; } // randomly select dimensions for kernel k.dimensions = new int[k.numSampledDimensions]; if (numDimensions > 1){ ArrayList<Integer> al = new ArrayList<>(numDimensions); for (int n = 0; n < numDimensions; n++) { al.add(n); } for (int j = 0; j < k.numSampledDimensions; j++) { k.dimensions[j] = al.remove(random.nextInt(al.size())); } } // draw uniform random sample from 0-1 and shift it to -1 to 1. k.bias = (random.nextDouble() * 2.0) - 1.0; double value = (double) (inputLength - 1) / (double) (k.length - 1); // convert to base 2 log. log2(b) = log10(b) / log10(2) double log2 = Math.log(value) / Math.log(2.0); k.dilation = (int) Math.floor(Math.pow(2.0, uniform(random, 0, log2))); k.padding = random.nextInt(2) == 1 ? Math.floorDiv((k.length - 1) * k.dilation, 2) : 0; return k; } } }
20,760
33.601667
117
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/RankOrder.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import weka.core.Capabilities; import weka.core.Instances; import weka.core.Instance; import weka.core.Capabilities.Capability; import weka.filters.*; import java.util.*; import org.apache.commons.lang3.NotImplementedException; import tsml.data_containers.TSCapabilities; import tsml.data_containers.TimeSeriesInstance; import weka.core.DenseInstance; /* * copyright: Anthony Bagnall * */ public class RankOrder implements Transformer { public double[][] ranks; public int numAtts = 0; private boolean normalise = true; public void setNormalise(boolean f) { normalise = f; }; @Override public Instance transform(Instance inst) { throw new NotImplementedException( "Single instance transformation does not make sense for rank order, which is column wise ranking!"); } @Override public Instances transform(Instances inst) { // Set input instance format Instances result = new Instances(determineOutputFormat(inst), 0); rankOrder(inst); // Stuff into new set of instances for (int i = 0; i < inst.numInstances(); i++) { // Create a deep copy, think this is necessary to maintain meta data? Instance in = new DenseInstance(inst.instance(i)); // Reset to the ranks for (int j = 0; j < numAtts; j++) in.setValue(j, ranks[i][j]); result.add(in); } return result; } protected class Pair implements Comparable { int pos; double val; public Pair(int p, double d) { pos = p; val = d; } public int compareTo(Object c) { if (val > ((Pair) c).val) return 1; if (val < ((Pair) c).val) return -1; return 0; } } public void rankOrder(Instances inst) { numAtts = inst.numAttributes(); int c = inst.classIndex(); if (c > 0) numAtts--; // If a classification problem it is assumed the class attribute is the last one // in the instances Pair[][] d = new Pair[numAtts][inst.numInstances()]; for (int j = 0; j < inst.numInstances(); j++) { Instance x = inst.instance(j); for (int i = 0; i < numAtts; i++) d[i][j] = new Pair(j, x.value(i)); } // Form rank order data set (in transpose of sorted array) // Sort each array of Pair for (int i = 0; i < numAtts; i++) Arrays.sort(d[i]); ranks = new double[inst.numInstances()][numAtts]; for (int j = 0; j < inst.numInstances(); j++) for (int i = 0; i < numAtts; i++) ranks[d[i][j].pos][i] = j; } @Override public Instances determineOutputFormat(Instances inputFormat) { Instances result = new Instances(inputFormat, 0); return result; } public TSCapabilities getTSCapabilities() { TSCapabilities result = Transformer.super.getTSCapabilities(); /*result.enableAllAttributes(); result.enableAllClasses(); result.enable(Capability.NO_CLASS); // filter doesn't need class to be set*/ return result; } public static void main(String[] args) { } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { // TODO Auto-generated method stub return null; } }
3,775
25.780142
104
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Resizer.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import experiments.data.DatasetLists; import experiments.data.DatasetLoading; import org.apache.commons.lang3.ArrayUtils; import tsml.classifiers.shapelet_based.ShapeletTransformClassifier; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.data_containers.utilities.TimeSeriesSummaryStatistics; import utilities.ClassifierTools; import utilities.generic_storage.Triple; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import java.io.File; import java.util.*; import java.util.concurrent.TimeUnit; /** * Interface to determine how to resize the data. */ interface IResizeMetric { int calculateResizeValue(Map<Integer, Integer> counts); } /** * Interface to determine how to pad the data. */ interface IPadMetric { double calculatePadValue(double[] data); } /** * Class to resize data. */ public class Resizer implements TrainableTransformer { private int resizeLength; private boolean isFit = false; private IResizeMetric resizeMetric = new MedianResizeMetric(); private IPadMetric padMetric = new MeanPadMetric(); /** * Default constructor. */ public Resizer() {} /** * Constructor to pass in the resizing metric. * * @param resizeMetric metric for resizing the data */ public Resizer(IResizeMetric resizeMetric) { this.resizeMetric = resizeMetric; } /** * Constructor to pass in the padding metric. * * @param padMetric metric for padding the data */ public Resizer(IPadMetric padMetric) { this.padMetric = padMetric; } /** * Constructor to pass in the resizing and padding metrics. * * @param resizeMetric metric for resizing the data * @param padMetric metric for padding the data */ public Resizer(IResizeMetric resizeMetric, IPadMetric padMetric) { this(resizeMetric); this.padMetric = padMetric; } @Override public Instances determineOutputFormat(Instances inputFormat) { ArrayList<Attribute> atts = new ArrayList<>(); Attribute a; for (int i = 0; i < resizeLength; i++) { a = new Attribute("Resizer" + (i + 1)); atts.add(a); } if (inputFormat.classIndex() >= 0) { // Classification set, set class // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals = new ArrayList<>(target.numValues()); for (int i = 0; i < target.numValues(); i++) vals.add(target.value(i)); atts.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances result = new Instances("Resizer" + inputFormat.relationName(), atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) result.setClassIndex(result.numAttributes() - 1); return result; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][resizeLength]; int i = 0; for (TimeSeries ts : inst) { int diff = resizeLength - ts.getSeriesLength(); double[] data = ts.toValueArray(); // just need to copy data across, if we're the same or longer. truncate the // first values. if (diff <= 0) { System.arraycopy(data, 0, out[i], 0, resizeLength); } // we're shorter than the average else { System.arraycopy(data, 0, out[i], 0, data.length); for (int j = data.length; j < resizeLength; j++) out[i][j] = padMetric.calculatePadValue(data); } //check if any NaNs exist as we want to overwrite those too. for (int j = 0; j < out[i].length; j++) if (Double.isNaN(out[i][j])) { out[i][j] = padMetric.calculatePadValue(data); } //System.out.println(Arrays.toString(out[i])); i++; } return new TimeSeriesInstance(out, inst.getLabelIndex()); } @Override public void fit(TimeSeriesInstances data) { Map<Integer, Integer> lengthCounts = data.getHistogramOfLengths(); resizeLength = resizeMetric.calculateResizeValue(lengthCounts); isFit = true; } private Map<Integer, Integer> calculateLengthHistogram(Instances data) { Map<Integer, Integer> counts = new TreeMap<>(); // build histogram of series lengths if (data.attribute(0).isRelationValued()) { // Multivariate for (Instance ins : data) { histogramLengths(ins.relationalValue(0), false, counts); } } else { histogramLengths(data, true, counts); } return counts; } private void histogramLengths(Instances d, boolean classValue, Map<Integer, Integer> counts) { for (Instance internal : d) { counts.merge(Truncator.findLength(internal, classValue), 1, Integer::sum); } } @Override public boolean isFit() { return isFit; } @Override public void fit(Instances data) { // TODO Auto-generated method stub } /* * Example */ public static void main(String[] args) throws Exception { //String local_path = "D:\\Work\\Data\\Multivariate_ts\\"; // Aarons local path for testing. String local_path = "Z:\\ArchiveData\\Univariate_arff\\"; String output_dir = "Z:\\Personal Spaces\\Aaron's - safe space\\UnivariateUnequalPaddedProblems\\"; //String dataset_name = "PLAID"; for (String dataset_name : DatasetLists.variableLengthUnivariate) { System.out.println(dataset_name); TimeSeriesInstances train = DatasetLoading .loadTSData(local_path + dataset_name + File.separator + dataset_name + "_TRAIN.arff"); TimeSeriesInstances test = DatasetLoading .loadTSData(local_path + dataset_name + File.separator + dataset_name + "_TEST.arff"); if (train.hasMissing() || !train.isEqualLength()) { Resizer rs = new Resizer(new Resizer.MaxResizeMetric(), new Resizer.MeanNoisePadMetric()); TimeSeriesInstances transformed_train = rs.fitTransform(train); TimeSeriesInstances transformed_test = rs.transform(test); DatasetLoading.saveTSDataset(transformed_train, output_dir + dataset_name + "\\" + dataset_name + "_TRAIN"); DatasetLoading.saveTSDataset(transformed_test, output_dir + dataset_name + "\\" + dataset_name + "_TEST"); } } } public static void test1() throws Exception { String local_path = "D:\\Work\\Data\\Univariate_ts\\"; // Aarons local path for testing. String dataset_name = "PLAID"; Instances train = DatasetLoading .loadData(local_path + dataset_name + File.separator + dataset_name + "_TRAIN.ts"); Instances test = DatasetLoading .loadData(local_path + dataset_name + File.separator + dataset_name + "_TEST.ts"); Resizer rs = new Resizer(); Map<Integer, Integer> map = rs.calculateLengthHistogram(train); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Train: " + entry.getKey() + " " + entry.getValue()); } Instances resized_train = rs.fitTransform(train); map = rs.calculateLengthHistogram(resized_train); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Rezised_Train " + entry.getKey() + " " + entry.getValue()); } Instances resized_test = rs.transform(test); ShapeletTransformClassifier stc = new ShapeletTransformClassifier(); stc.setTrainTimeLimit(TimeUnit.MINUTES, 5); stc.buildClassifier(resized_train); double acc = ClassifierTools.accuracy(resized_test, stc); System.out.println(acc); } /* * RESIZE METRICS */ /** * Static nested class to set the new size of each series to the weighted * median. */ public static class WeightedMedianResizeMetric implements IResizeMetric { @Override public int calculateResizeValue(Map<Integer, Integer> counts) { int total_counts = counts.values().stream().mapToInt(e -> e.intValue()).sum(); double cumulative_weight = 0; int median = 0; for (Map.Entry<Integer, Integer> entry : counts.entrySet()) { cumulative_weight += (double) entry.getValue() / (double) total_counts; median = entry.getKey(); if (cumulative_weight > 1 / 2) break; } return median; } } /** * Static nested class to set the new size of each series to the median. */ public static class MedianResizeMetric implements IResizeMetric { @Override public int calculateResizeValue(Map<Integer, Integer> counts) { int total_counts = counts.values().stream().mapToInt(e -> e.intValue()).sum(); // construct ordered list counts of keys. int[] keys = new int[total_counts]; // {6 : 3, 10 : 1} => [6,6,6,10] int k = 0; for (Map.Entry<Integer, Integer> entry : counts.entrySet()) { for (int i = 0; i < entry.getValue(); i++) keys[k++] = entry.getKey(); } int middle = keys.length / 2; if (keys.length % 2 == 1) return keys[middle]; else return (keys[middle - 1] + keys[middle]) / 2; } } /** * Static nested class to set the new size of each series to the maximum * length of a series. */ public static class MaxResizeMetric implements IResizeMetric { @Override public int calculateResizeValue(Map<Integer, Integer> counts) { return counts.keySet().stream().max(Integer::compareTo).get(); } } /* * PAD METRICS */ /** * Static nested class to set the padding to the mean of a series. */ public static class MeanPadMetric implements IPadMetric { @Override public double calculatePadValue(double[] data) { return TimeSeriesSummaryStatistics.mean(data); } } /** * Static nested class to set the padding to the mean of a series with some * noise added. */ public static class MeanNoisePadMetric implements IPadMetric { Map<Integer, Triple<Double, Double, Double>> cache = new HashMap<>(); Random random = new Random(); @Override public double calculatePadValue(double[] data) { int hash = data.hashCode(); Triple<Double, Double, Double> stats = cache.get(hash); if (stats == null) { stats = new Triple<Double, Double, Double>(TimeSeriesSummaryStatistics.max(data), TimeSeriesSummaryStatistics.min(data), TimeSeriesSummaryStatistics.mean(Arrays.asList(ArrayUtils.toObject(data)))); cache.put(hash, stats); } double scaledMax = stats.var1 / 100.0; double scaledMin = stats.var2 / 100.0; //mean + some noise between scaled min and max. return stats.var3 + (random.nextDouble() * (scaledMax - scaledMin)) + scaledMin; } } /** * Static nested class to set the padding to 0 or the value passed. */ public static class FlatPadMetric implements IPadMetric { private final int padValue; public FlatPadMetric(int value) { this.padValue = value; } @Override public double calculatePadValue(double[] data) { return padValue; } } }
12,997
33.295515
136
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/RowNormalizer.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ /** Class NormalizeAttribute.java * * @author AJB * @version 1 * @since 14/4/09 * * Class normalizes attributes, basic version. Assumes no missing values. * * Normalise onto [0,1] if norm==NormType.INTERVAL, * Normalise onto Normal(0,1) if norm==NormType.STD_NORMAL, * * */ package tsml.transformers; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import experiments.data.DatasetLoading; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.data_containers.utilities.TimeSeriesSummaryStatistics; import utilities.InstanceTools; import utilities.NumUtils; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.FastVector; import weka.core.Instance; import weka.core.Instances; public class RowNormalizer implements Transformer { public enum NormType { INTERVAL, STD, STD_NORMAL }; public static boolean throwErrorOnZeroVariance = false; NormType norm = NormType.STD_NORMAL; public RowNormalizer(){ this(NormType.STD_NORMAL); } public RowNormalizer(NormType type){ norm = type; } @Override public Instances transform(Instances data) { switch (norm) { case INTERVAL: // Map onto [0,1] return intervalNorm(data); case STD: // Subtract the mean of the series return standard(data); default: // Transform to zero mean, unit variance return standardNorm(data); } } @Override public Instance transform(Instance inst) { switch (norm) { case INTERVAL: // Map onto [0,1] return intervalNorm(inst); case STD: // Subtract the mean of the series return standard(inst); default: // Transform to zero mean, unit variance return standardNorm(inst); } } /* Wont normalise the class value */ public Instances intervalNorm(Instances data) { Instances out = determineOutputFormat(data); for(Instance inst : data){ out.add(intervalNorm(inst)); } return out; } public Instance intervalNorm(Instance inst) { return intervalInCopy(inst, InstanceTools.max(inst), InstanceTools.min(inst)); } public Instances standard(Instances data) { Instances out = determineOutputFormat(data); for(Instance inst : data){ out.add(standard(inst)); } return out; } public Instance standard(Instance data){ double size = data.numAttributes(); int classIndex = data.classIndex(); if (classIndex > 0) size--; double mean = InstanceTools.sum(data) / size; return standardInCopy(data, mean); } public Instances standardNorm(Instances data) { Instances out = determineOutputFormat(data); for(Instance inst : data){ out.add(standardNorm(inst)); } return out; } private Instance standardNorm(Instance inst) { double mean,sum,sumSq,var = 0; double size = inst.numAttributes(); if (inst.classIndex() >= 0) size--; sum = InstanceTools.sum(inst); sumSq = InstanceTools.sumSq(inst); var = (sumSq - sum * sum / size) / size; mean = sum / size; //if the instance has zero variance just return a list of 0's, else return the normed instance. return NumUtils.isNearlyEqual(var,0) ? constantInCopy(inst, 0) : normaliseInCopy(inst, mean, Math.sqrt(var)); } @Override public Instances determineOutputFormat(Instances inputFormat) throws IllegalArgumentException { FastVector<Attribute> atts=new FastVector<>(); for(int i=0;i<inputFormat.numAttributes()-1;i++) { String name = norm.toString()+i; atts.addElement(new Attribute(name)); } //Get the class values as a fast vector Attribute target =inputFormat.attribute(inputFormat.classIndex()); FastVector<String> vals=new FastVector<>(target.numValues()); for(int i=0;i<target.numValues();i++) vals.addElement(target.value(i)); atts.addElement(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(),vals)); Instances result = new Instances("NormaliseCase "+inputFormat.relationName(),atts,inputFormat.numInstances()); if(inputFormat.classIndex()>=0){ result.setClassIndex(result.numAttributes()-1); } return result; } /*I THINK THESE COULD BE REFACTORED INTO INSTANCE TOOLS*/ public static Instance normaliseInCopy(Instance orig, double mean, double std){ Instance copy = new DenseInstance(orig.numAttributes()); for (int j = 0; j < orig.numAttributes(); j++) if (j != orig.classIndex() && !orig.attribute(j).isNominal()) copy.setValue(j, (orig.value(j) - mean) / (std)); if(orig.classIndex() >= 0) copy.setValue(orig.classIndex(), orig.classValue()); return copy; } public static Instance standardInCopy(Instance orig, double mean){ Instance copy = new DenseInstance(orig.numAttributes()); for (int j = 0; j < orig.numAttributes(); j++) if (j != orig.classIndex() && !orig.attribute(j).isNominal()) copy.setValue(j, (orig.value(j) - mean)); if(orig.classIndex() >= 0) copy.setValue(orig.classIndex(), orig.classValue()); return copy; } public static Instance intervalInCopy(Instance orig, double min, double max){ Instance copy = new DenseInstance(orig.numAttributes()); for (int j = 0; j < orig.numAttributes(); j++) if (j != orig.classIndex() && !orig.attribute(j).isNominal()) copy.setValue(j, (orig.value(j) - min) / (max - min)); if(orig.classIndex() >= 0) copy.setValue(orig.classIndex(), orig.classValue()); return copy; } public static Instance constantInCopy(Instance orig, double constant){ Instance copy = new DenseInstance(orig.numAttributes()); for (int j = 0; j < orig.numAttributes(); j++) if (j != orig.classIndex() && !orig.attribute(j).isNominal()) copy.setValue(j, constant); if(orig.classIndex() >= 0) copy.setValue(orig.classIndex(), orig.classValue()); return copy; } /* END BLOCK */ /* TimeSeries Utilities */ @Override public TimeSeriesInstances transform(TimeSeriesInstances data) { switch (norm) { case INTERVAL: // Map onto [0,1] return intervalNorm(data); case STD: // Subtract the mean of the series return standard(data); default: // Transform to zero mean, unit variance return standardNorm(data); } } public static TimeSeriesInstances standardNorm(TimeSeriesInstances data) { TimeSeriesInstances out = new TimeSeriesInstances(data.getClassLabels()); for(TimeSeriesInstance inst : data){ out.add(standardNorm(inst)); } return out; } public static TimeSeriesInstances standard(TimeSeriesInstances data) { TimeSeriesInstances out = new TimeSeriesInstances(data.getClassLabels()); for(TimeSeriesInstance inst : data){ out.add(standard(inst)); } return out; } public static TimeSeriesInstances intervalNorm(TimeSeriesInstances data) { TimeSeriesInstances out = new TimeSeriesInstances(data.getClassLabels()); for(TimeSeriesInstance inst : data){ out.add(intervalNorm(inst)); } return out; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { switch (norm) { case INTERVAL: // Map onto [0,1] return intervalNorm(inst); case STD: // Subtract the mean of the series return standard(inst); default: // Transform to zero mean, unit variance return standardNorm(inst); } } public static TimeSeriesInstance standardNorm(TimeSeriesInstance inst) { List<TimeSeries> out = new ArrayList<>(inst.getNumDimensions()); for(TimeSeries ts : inst){ out.add(standardNorm(ts)); } return new TimeSeriesInstance(inst.getLabelIndex(), out); } public static TimeSeriesInstance standard(TimeSeriesInstance inst) { List<TimeSeries> out = new ArrayList<>(inst.getNumDimensions()); for(TimeSeries ts : inst){ out.add(standard(ts)); } return new TimeSeriesInstance(inst.getLabelIndex(), out); } public static TimeSeriesInstance intervalNorm(TimeSeriesInstance inst) { List<TimeSeries> out = new ArrayList<>(inst.getNumDimensions()); for(TimeSeries ts : inst){ out.add(intervalNorm(ts)); } return new TimeSeriesInstance(inst.getLabelIndex(), out); } public static TimeSeries standardNorm(TimeSeries ts) { double[] out = ts.toValueArray(); //this is a copy. double mean = TimeSeriesSummaryStatistics.mean(out); double var = TimeSeriesSummaryStatistics.variance(ts, mean); boolean constant = NumUtils.isNearlyEqual(var,0); //if we have zero variance, then just return array of 0's if(constant){ for(int i =0; i<out.length; i++){ out[i] = 0; } } else{ double std = Math.sqrt(var); for(int i =0; i<out.length; i++){ out[i] = (out[i] - mean) / std; } } return new TimeSeries(out); } public static TimeSeries standard(TimeSeries ts){ double[] out = ts.toValueArray(); //this is a copy. double mean = TimeSeriesSummaryStatistics.mean(out); for(int i =0; i<out.length; i++){ out[i] = (out[i] - mean); } return new TimeSeries(out); } public static TimeSeries intervalNorm(TimeSeries ts){ double[] out = ts.toValueArray(); //this is a copy. double max = TimeSeriesSummaryStatistics.max(out); double min = TimeSeriesSummaryStatistics.min(out); for(int i =0; i<out.length; i++){ out[i] = (out[i] - min) / (max - min); } return new TimeSeries(out); } static String[] fileNames = { // Number of train,test cases,length,classes "Beef", // 30,30,470,5 "Coffee", // 28,28,286,2 "OliveOil", "Earthquakes", "Ford_A", "Ford_B" }; static String path = "C:\\Research\\Data\\Time Series Data\\Time Series Classification\\"; public static void main(String[] args) throws IOException { String localPath="src/main/java/experiments/data/tsc/"; String datasetName = "ChinaTown"; Instances train = DatasetLoading.loadData(localPath + datasetName + File.separator + datasetName+"_TRAIN.ts"); Instances test = DatasetLoading.loadData(localPath + datasetName + File.separator + datasetName+"_TEST.ts"); RowNormalizer hTransform= new RowNormalizer(); Instances out_train = hTransform.transform(train); Instances out_test = hTransform.transform(test); System.out.println(out_train.toString()); System.out.println(out_test.toString()); } }
11,219
28.371728
118
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/RunLength.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.io.FileReader; import java.util.ArrayList; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.utilities.TimeSeriesSummaryStatistics; import utilities.InstanceTools; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; /* * copyright: Anthony Bagnall * * */ public class RunLength implements Transformer { private int maxRunLength = 50; private boolean useGlobalMean = true; private double globalMean = 5.5; public RunLength() { } public RunLength(int maxRL) { maxRunLength = maxRL; } public void setMaxRL(int m) { maxRunLength = m; } public void setGlobalMean(double d) { useGlobalMean = true; globalMean = d; } public void noGlobalMean() { useGlobalMean = false; } @Override public Instances determineOutputFormat(Instances inputFormat) { // Treating counts as reals ArrayList<Attribute> atts = new ArrayList<>(); Attribute a; for (int i = 0; i < maxRunLength; i++) { a = new Attribute("RunLengthCount" + (i + 1)); atts.add(a); } if (inputFormat.classIndex() >= 0) { // Classification set, set class // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals = new ArrayList<>(target.numValues()); for (int i = 0; i < target.numValues(); i++) vals.add(target.value(i)); atts.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances result = new Instances("RunLengths" + inputFormat.relationName(), atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) result.setClassIndex(result.numAttributes() - 1); return result; } @Override public Instance transform(Instance inst) { // 1: Get series into an array, remove class value if present double[] d = InstanceTools.ConvertInstanceToArrayRemovingClassValue(inst); double t = 0; if (useGlobalMean) t = globalMean; else { // Find average t = InstanceTools.mean(inst); } double[] histogram = create_data(d, t); Instance newInst = new DenseInstance(inst.numAttributes()); // 3. Put run lengths and class value into instances for (int j = 0; j < histogram.length; j++) newInst.setValue(j, histogram[j]); if (inst.classIndex() >= 0) newInst.setValue(inst.numAttributes() - 1, inst.classValue()); return newInst; } private double[] create_data(double[] d, double t) { // 2: Form histogram of run lengths: note missing values assumed in the same run double[] histogram = new double[d.length]; int pos = 1; int length = 0; boolean u2 = false; boolean under = d[0] < t ? true : false; while (pos < d.length) { u2 = d[pos] < t ? true : false; // System.out.println("Pos ="+pos+" currentUNDER ="+under+" newUNDER = "+u2); if (Double.isNaN(d[pos]) || under == u2) { length++; } else { // System.out.println("Position "+pos+" has run length "+length); if (length < maxRunLength - 1) histogram[length]++; else histogram[maxRunLength - 1]++; under = u2; length = 0; } pos++; } if (length < maxRunLength - 1) histogram[length]++; else histogram[maxRunLength - 1]++; return histogram; } // Primitives version, assumes zero mean global, passes max run length public int[] processSingleSeries(double[] d, int mrl) { double mean = 0; int pos = 1; int length = 0; boolean u2 = false; int[] histogram = new int[mrl]; boolean under = d[0] < mean ? true : false; while (pos < d.length) { u2 = d[pos] < mean ? true : false; if (under == u2) { length++; } else { if (length < mrl - 1) histogram[length]++; else histogram[mrl - 1]++; under = u2; length = 0; } pos++; } if (length < mrl - 1) histogram[length]++; else histogram[mrl - 1]++; return histogram; } // Test Harness public static void main(String[] args) { RunLength cp = new RunLength(); cp.noGlobalMean(); Instances data = null; String fileName = "C:\\Research\\Data\\Time Series Data\\Time Series Classification\\TestData\\TimeSeries_Train.arff"; try { FileReader r; r = new FileReader(fileName); data = new Instances(r); data.setClassIndex(data.numAttributes() - 1); System.out.println(data); Instances newInst = cp.transform(data); System.out.println("\n" + newInst); } catch (Exception e) { System.out.println(" Error =" + e); StackTraceElement[] st = e.getStackTrace(); for (int i = st.length - 1; i >= 0; i--) System.out.println(st[i]); } } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i =0; for(TimeSeries ts : inst){ out[i++] = create_data(ts.toValueArray(), useGlobalMean ? globalMean : TimeSeriesSummaryStatistics.mean(ts)); } return new TimeSeriesInstance(out, inst.getLabelIndex()); } }
5,846
27.110577
121
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/SAX.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import experiments.data.DatasetLoading; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.TechnicalInformation; import weka.core.TechnicalInformationHandler; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Filter to reduce dimensionality of and discretise a time series into SAX * form, does not normalize, must be done separately if wanted. * * Output attributes can be in two forms - discrete alphabet or real values 0 to * alphabetsize-1 * * Default number of intervals = 8 Default alphabet size = 4 * * @author James */ public class SAX implements Transformer, TechnicalInformationHandler { private int numIntervals = 8; private int alphabetSize = 4; private boolean useRealAttributes = false; private List<String> alphabet = null; private Instances inputFormat; private static final long serialVersionUID = 1L; // individual strings for each symbol in the alphabet, up to ten symbols private static final String[] alphabetSymbols = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; public int getNumIntervals() { return numIntervals; } public int getAlphabetSize() { return alphabetSize; } public List<String> getAlphabet() { if (alphabet == null) generateAlphabet(); return alphabet; } public static List<String> getAlphabet(int alphabetSize) { List<String> alphb = new ArrayList<>(); for (int i = 0; i < alphabetSize; ++i) alphb.add(alphabetSymbols[i]); return alphb; } public void setNumIntervals(int intervals) { numIntervals = intervals; } public void setAlphabetSize(int alphasize) { if (alphasize > 10) { alphasize = 10; System.out.println("Alpha size too large, setting to 10"); } else if (alphasize < 2) { alphasize = 2; System.out.println("Alpha size too small, setting to 2"); } alphabetSize = alphasize; } public void useRealValuedAttributes(boolean b) { useRealAttributes = b; } public void generateAlphabet() { alphabet = new ArrayList<>(); for (int i = 0; i < alphabetSize; ++i) alphabet.add(alphabetSymbols[i]); } // lookup table for the breakpoints for a gaussian curve where the area under // curve T between Ti and Ti+1 = 1/a, 'a' being the size of the alphabet. // columns up to a=10 stored // lit. suggests that a = 3 or 4 is bet in almost all cases, up to 6 or 7 at // most // for specific datasets public double[] generateBreakpoints(int alphabetSize) { double maxVal = Double.MAX_VALUE; double[] breakpoints = null; switch (alphabetSize) { case 2: { breakpoints = new double[] { 0, maxVal }; break; } case 3: { breakpoints = new double[] { -0.43, 0.43, maxVal }; break; } case 4: { breakpoints = new double[] { -0.67, 0, 0.67, maxVal }; break; } case 5: { breakpoints = new double[] { -0.84, -0.25, 0.25, 0.84, maxVal }; break; } case 6: { breakpoints = new double[] { -0.97, -0.43, 0, 0.43, 0.97, maxVal }; break; } case 7: { breakpoints = new double[] { -1.07, -0.57, -0.18, 0.18, 0.57, 1.07, maxVal }; break; } case 8: { breakpoints = new double[] { -1.15, -0.67, -0.32, 0, 0.32, 0.67, 1.15, maxVal }; break; } case 9: { breakpoints = new double[] { -1.22, -0.76, -0.43, -0.14, 0.14, 0.43, 0.76, 1.22, maxVal }; break; } case 10: { breakpoints = new double[] { -1.28, -0.84, -0.52, -0.25, 0.0, 0.25, 0.52, 0.84, 1.28, maxVal }; break; } } return breakpoints; } @Override public Instances determineOutputFormat(Instances inputFormat) { ArrayList<Attribute> attributes = new ArrayList<>(); // If the alphabet is to be considered as discrete values (i.e non real), // generate nominal values based on alphabet size if (!useRealAttributes) generateAlphabet(); Attribute att; String name; for (int i = 0; i < numIntervals; i++) { name = "SAXInterval_" + i; if (!useRealAttributes) att = new Attribute(name, alphabet); else att = new Attribute(name); attributes.add(att); } if (inputFormat.classIndex() >= 0) { // Classification set, set class // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals = new ArrayList<>(); for (int i = 0; i < target.numValues(); i++) { vals.add(target.value(i)); } attributes.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances result = new Instances("SAX" + inputFormat.relationName(), attributes, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } return result; } @Override public Instances transform(Instances data) { Instances output = determineOutputFormat(data); // Convert input to PAA format PAA paa = new PAA(); paa.setNumIntervals(numIntervals); // Now convert PAA -> SAX for (Instance inst : data) { // lower mem to do it series at a time. output.add(transform(paa.transform(inst))); } return output; } @Override public Instance transform(Instance inst) { double[] data = inst.toDoubleArray(); // remove class attribute if needed double[] temp; int c = inst.classIndex(); if (c >= 0) { temp = new double[data.length - 1]; System.arraycopy(data, 0, temp, 0, c); // assumes class attribute is in last index data = temp; } convertSequence(data); // Now in SAX form, extract out the terms and set the attributes of new instance Instance newInstance = new DenseInstance(numIntervals + (inst.classIndex() >= 0 ? 1 : 0)); for (int j = 0; j < numIntervals; j++) newInstance.setValue(j, data[j]); if (inst.classIndex() >= 0) newInstance.setValue(newInstance.numAttributes()-1, inst.classValue()); return newInstance; } @Override public TimeSeriesInstances transform(TimeSeriesInstances data) { // Convert input to PAA format PAA paa = new PAA(); paa.setNumIntervals(numIntervals); // Now convert PAA -> SAX TimeSeriesInstances out = new TimeSeriesInstances(data.getClassLabels()); for (TimeSeriesInstance inst : data) { // lower mem to do it series at a time. out.add(transform(paa.transform(inst))); } return out; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i =0; for(TimeSeries ts : inst){ double[] o = ts.toValueArray(); convertSequence(o); out[i++] = o; } return new TimeSeriesInstance(out, inst.getLabelIndex()); } /** * converts a double[] of 'paa-ed' data to sax letters * * @param data * @throws Exception */ public void convertSequence(double[] data) { double[] gaussianBreakpoints = generateBreakpoints(alphabetSize); for (int i = 0; i < numIntervals; ++i) { // find symbol corresponding to each mean for (int j = 0; j < alphabetSize; ++j) if (data[i] < gaussianBreakpoints[j]) { data[i] = j; break; } } } /** * Will perform a SAX transformation on a single series passed as a double[] * * @param alphabetSize size of SAX alphabet * @param numIntervals size of resulting word * @throws Exception */ public static double[] convertSequence(double[] data, int alphabetSize, int numIntervals) { SAX sax = new SAX(); sax.setNumIntervals(numIntervals); sax.setAlphabetSize(alphabetSize); sax.useRealValuedAttributes(true); double[] d = PAA.convertInstance(data, numIntervals); sax.convertSequence(d); return d; } public String getRevision() { throw new UnsupportedOperationException("Not supported yet."); // To change body of generated methods, choose // Tools | Templates. } public static void main(String[] args) throws IOException { System.out.println("SAXtest\n\n"); String localPath="src/main/java/experiments/data/tsc/"; Instances test = DatasetLoading .loadData(localPath+"Chinatown/Chinatown_TRAIN.arff"); test = new RowNormalizer().transform(test); SAX sax = new SAX(); sax.setNumIntervals(8); sax.setAlphabetSize(4); sax.useRealValuedAttributes(false); Instances result = sax.transform(test); System.out.println(test); System.out.println("\n\n\nResults:\n\n"); System.out.println(result); } @Override public TechnicalInformation getTechnicalInformation() { TechnicalInformation result; result = new TechnicalInformation(TechnicalInformation.Type.ARTICLE); result.setValue(TechnicalInformation.Field.TITLE, "Experiencing SAX: a novel symbolic representation of time series"); result.setValue(TechnicalInformation.Field.AUTHOR, "Jessica Lin, Eamonn Keogh, Li Wei and Stefano Lonardi"); result.setValue(TechnicalInformation.Field.YEAR, "2007"); result.setValue(TechnicalInformation.Field.JOURNAL, "Data Mining and Knowledge Discovery"); result.setValue(TechnicalInformation.Field.VOLUME, "15"); result.setValue(TechnicalInformation.Field.NUMBER, "2"); result.setValue(TechnicalInformation.Field.PAGES, "107-144"); return result; } }
11,737
31.97191
117
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/ShapeDTWFeatures.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import tsml.classifiers.distance_based.ShapeDTW_1NN; import tsml.data_containers.TimeSeriesInstance; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import java.util.ArrayList; /* * This class is used to transform a time series into a set * of ShapeDTW distances. It does this by calculating the * distance between an unknown time series and all * time series in a reference set. */ public class ShapeDTWFeatures implements Transformer { private Instances referenceSet; private Instances dataset; /** * No default parameter because the reference set must be given inorder * to be able to calculate distances. * * @param referenceSet */ public ShapeDTWFeatures(Instances referenceSet) { this.referenceSet = referenceSet; } @Override public Instance transform(Instance inst) { double [] distances = getDistances(inst); //Now in ShapeDTW distances form, extract out the terms and set the attributes of new instance Instance newInstance; int numAtts = distances.length; if (inst.classIndex() >= 0) newInstance = new DenseInstance(numAtts + 1); else newInstance = new DenseInstance(numAtts); // Copy over the values into the Instance for (int j = 0; j < numAtts; j++) newInstance.setValue(j, distances[j]); // Set the class value if (inst.classIndex() >= 0) newInstance.setValue(newInstance.numAttributes()-1, inst.classValue()); newInstance.setDataset(dataset); return newInstance; } /** * Private function to get all the distances from inst and all the * time series in the reference set. * * @param inst * @return */ private double [] getDistances(Instance inst) { double [] dists = new double[this.referenceSet.numInstances()]; for(int i=0;i< dists.length;i++) { dists[i] = ShapeDTW_1NN.NN_DTW_Subsequences.calculateDistance(inst,referenceSet.get(i)); } return dists; } @Override public Instances determineOutputFormat(Instances inputFormat) throws IllegalArgumentException { //If the class index exists. if(inputFormat.classIndex() >= 0) { if (inputFormat.classIndex() != inputFormat.numAttributes() - 1) { throw new IllegalArgumentException("cannot handle class values not at end"); } } ArrayList<Attribute> attributes = new ArrayList<>(); // Create a list of attributes for(int i = 0; i<referenceSet.numInstances(); i++) { attributes.add(new Attribute("ShapeDTW_Distance_" + i)); } // Add the class attribute (if it exists) if(inputFormat.classIndex() >= 0) { attributes.add(inputFormat.classAttribute()); } Instances result = new Instances("ShapeDTWDistances" + inputFormat.relationName(), attributes, inputFormat.numInstances()); // Set the class attribute (if it exists) if(inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } this.dataset = result; return result; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { return null; } }
4,196
35.181034
131
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/ShapeletTransform.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import tsml.classifiers.TrainTimeContractable; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.transformers.shapelet_tools.OrderLineObj; import tsml.transformers.shapelet_tools.Shapelet; import tsml.transformers.shapelet_tools.ShapeletCandidate; import tsml.transformers.shapelet_tools.ShapeletTransformTimingUtilities; import tsml.transformers.shapelet_tools.class_value.NormalClassValue; import tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance; import tsml.transformers.shapelet_tools.quality_measures.ShapeletQuality; import tsml.transformers.shapelet_tools.quality_measures.ShapeletQuality.ShapeletQualityChoice; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchFactory; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import utilities.NumUtils; import utilities.class_counts.ClassCounts; import utilities.rescalers.SeriesRescaler; import weka.core.*; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * * NOTE: As shapelet extraction can be time consuming, there is an option to * output shapelets to a text file (Default location is in the root dir of the * project, file name "defaultShapeletOutput.txt"). * * Default settings are TO NOT PRODUCE OUTPUT FILE - unless file name is * changed, each successive filter will overwrite the output (see * "setLogOutputFile(String fileName)" to change file dir and name). * * To reconstruct a filter from this output, please see the method * "createFilterFromFile(String fileName)". * * * * A filter to transform a dataset by k shapelets. Once built on a training set, * the filter can be used to transform subsequent datasets using the extracted * shapelets. * <p> * See <a href= * "http://delivery.acm.org/10.1145/2340000/2339579/p289-lines.pdf?ip=139.222.14.198&acc=ACTIVE%20SERVICE&CFID=221649628&CFTOKEN=31860141&__acm__=1354814450_3dacfa9c5af84445ea2bfd7cc48180c8"> * Lines J., Davis, L., Hills, J., Bagnall, A.: A shapelet transform for time * series classification. In: Proc. 18th ACM SIGKDD (2012)</a> * * @author Jason Lines, Aaron Bostrom and Tony Bagnall * * Refactored version for */ public class ShapeletTransform implements Serializable, TechnicalInformationHandler, TrainableTransformer { // Global defaults. Max should be a lambda set to series length public final static int MAXTRANSFORMSIZE = 1000; public final static int DEFAULT_MINSHAPELETLENGTH = 3; public final static int DEFAULT_MAXSHAPELETLENGTH = 23; // Im not sure this is used anywhere, should be in Options for condensing data? public static final int minimumRepresentation = 25; // If condensing the search set, this is the minimum number of // instances per class to search // Variables for experiments protected static long subseqDistOpCount; private boolean removeSelfSimilar = true; private boolean pruneMatchingShapelets; // this int is used to serialise our position when iterating through a dataset. public int casesSoFar; public boolean searchComplete = false; protected boolean supressOutput = true; // defaults to print in System.out AS WELL as file, set to true to stop // printing to console protected int numShapelets; // The maximum number of shapelets in the transform. This is K and is different // to the total number of shapelets to look for/looked for protected ArrayList<Shapelet> shapelets; protected String ouputFileLocation = "defaultShapeletOutput.txt"; // default store location protected boolean recordShapelets; // default action is to write an output file protected long numShapeletsEvaluated = 0;// This counts the total number of shapelets returned by // searchForShapeletsInSeries. It does not include early abandoned // shapelets protected long numEarlyAbandons = 0;// This counts number of shapelets early abandoned // All of these can be in an ShapeletTransformOptions // ShapeletTransformFactoryOptions.ShapeletTransformOptions options; protected boolean roundRobin; protected transient ShapeletQuality quality; protected boolean useCandidatePruning; protected boolean useRoundRobin; protected boolean useBalancedClasses; protected ShapeletDistance shapeletDistance; protected ShapeletSearch searchFunction; protected Comparator<Shapelet> shapeletComparator; protected NormalClassValue classValue; protected String serialName; protected Shapelet worstShapelet; protected Instances inputData; protected TimeSeriesInstances inputDataTS; protected ArrayList<Shapelet> kShapelets; protected int candidatePruningStartPercentage; protected long count; protected Map<Double, ArrayList<Shapelet>> kShapeletsMap; protected static final double ROUNDING_ERROR_CORRECTION = 0.000000000000001; protected int[] dataSourceIDs; /** * Contract data */ protected boolean adaptiveTiming = false; private double timePerShapelet = 0; private long totalShapeletsPerSeries = 0; // Found once private long shapeletsSearchedPerSeries = 0;// This is taken from the search function private int numSeriesToUse = 0; private long contractTime = 0; // nano seconds time. If set to zero everything reverts to // BalancedClassShapeletTransform private double beta = 0.2; /** * Default constructor; Quality measure defaults to information gain. */ public ShapeletTransform() { this(MAXTRANSFORMSIZE, DEFAULT_MINSHAPELETLENGTH, DEFAULT_MAXSHAPELETLENGTH, ShapeletQualityChoice.INFORMATION_GAIN); } /** * Constructor for generating a shapelet transform from an ArrayList of * Shapelets. * * @param shapes */ public ShapeletTransform(ArrayList<Shapelet> shapes) { this(); this.shapelets = shapes; this.numShapelets = shapelets.size(); } /** * Full constructor to create a usable filter. Quality measure defaults to * information gain. * * @param k the number of shapelets to be generated * @param minShapeletLength minimum length of shapelets * @param maxShapeletLength maximum length of shapelets */ public ShapeletTransform(int k, int minShapeletLength, int maxShapeletLength) { this(k, minShapeletLength, maxShapeletLength, ShapeletQualityChoice.INFORMATION_GAIN); } /** * Full, exhaustive, constructor for a filter. Quality measure set via enum, * invalid selection defaults to information gain. * * @param k the number of shapelets to be generated * @param minShapeletLength minimum length of shapelets * @param maxShapeletLength maximum length of shapelets * @param qualityChoice the shapelet quality measure to be used with this * filter */ public ShapeletTransform(int k, int minShapeletLength, int maxShapeletLength, ShapeletQualityChoice qualityChoice) { this.numShapelets = k; this.shapelets = new ArrayList<>(); this.useCandidatePruning = false; this.casesSoFar = 0; this.recordShapelets = true; // default action is to write an output file this.roundRobin = false; this.useRoundRobin = false; this.shapeletComparator = new Shapelet.LongOrder(); this.kShapelets = new ArrayList<>(); setQualityMeasure(qualityChoice); this.shapeletDistance = new ShapeletDistance(); this.classValue = new NormalClassValue(); ShapeletSearchOptions sOp = new ShapeletSearchOptions.Builder().setMin(minShapeletLength) .setMax(maxShapeletLength).build(); this.searchFunction = new ShapeletSearchFactory(sOp).getShapeletSearch(); } protected void initQualityBound(ClassCounts classDist) { if (!useCandidatePruning) return; quality.initQualityBound(classDist, candidatePruningStartPercentage); } /** * Sets the format of the filtered instances that are output. I.e. will include * k attributes each shapelet distance and a class value * * @param inputFormat the format of the input data * @return a new Instances object in the desired output format */ @Override public Instances determineOutputFormat(Instances inputFormat) throws IllegalArgumentException { if (this.numShapelets < 1) { System.out.println(this.numShapelets); throw new IllegalArgumentException( "ShapeletTransform not initialised correctly - please specify a value of k (this.numShapelets) that is greater than or equal to 1. It is currently set tp " + this.numShapelets); } // Set up instances size and format. // int length = this.numShapelets; int length = this.shapelets.size(); ArrayList<Attribute> atts = new ArrayList<>(); String name; for (int i = 0; i < length; i++) { name = "Shapelet_" + i; atts.add(new Attribute(name)); } if (inputFormat.classIndex() >= 0) { // Classification set, set class // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); FastVector vals = new FastVector(target.numValues()); for (int i = 0; i < target.numValues(); i++) { vals.addElement(target.value(i)); } atts.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances result = new Instances("Shapelets" + inputFormat.relationName(), atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } return result; } @Override public void fit(Instances data) { inputData = data; int length=data.numAttributes() - 1; if(data.attribute(0).isRelationValued()) length=data.instance(0).relationalValue(0).numInstances(); totalShapeletsPerSeries = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(1, length, searchFunction.getMinShapeletLength(), searchFunction.getMaxShapeletLength()); // check the input data is correct and assess whether the filter has been setup // correctly. trainShapelets(data); searchComplete = true; // we log the count from the subsequence distance before we reset it in the // transform. // we only care about the count from the train. What is it counting? count = shapeletDistance.getCount(); } @Override public Instance transform(Instance data) { throw new UnsupportedOperationException( "NOT IMPLEMENTED YET. Cannot transform a single instance yet, is trivial though (ShapeletTransform.transform"); // return buildTansformedDataset(data); } @Override public Instances transform(Instances data) throws IllegalArgumentException { return buildTansformedDataset(data); } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { // init out data for transforming. shapeletDistance.init(inputDataTS); // setup classsValue classValue.init(inputDataTS); Shapelet s; //get distance to each shapelet and create new instance int size = shapelets.size(); //1 dimensional double[][] out = new double[1][size]; for (int i = 0; i < size; i++) { s = shapelets.get(i); shapeletDistance.setShapelet(s); out[0][i] = shapeletDistance.calculate(inst, 0); } return new TimeSeriesInstance(out, inst.getLabelIndex()); } @Override public TimeSeriesInstances transform(TimeSeriesInstances data) { return buildTansformedDataset(data); } @Override public void fit(TimeSeriesInstances data) { inputDataTS = data; totalShapeletsPerSeries = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(1, data.getMaxLength(), searchFunction.getMinShapeletLength(), searchFunction.getMaxShapeletLength()); // check the input data is correct and assess whether the filter has been setup // correctly. trainShapelets(data); searchComplete = true; // we log the count from the subsequence distance before we reset it in the // transform. // we only care about the count from the train. What is it counting? count = shapeletDistance.getCount(); } protected void trainShapelets(Instances data) { // we might round robin the data in here. // So we need to override the input data with the new ordering. // we don't need to undo the roundRobin because we clone the data into a // different order. inputData = orderDataSet(data); // Initialise search function for ShapeletSearch object searchFunction.setComparator(shapeletComparator); searchFunction.init(inputData); // setup shapelet distance function (sDist). Just initialises the count to 0 shapeletDistance.init(inputData); // setup classValue classValue.init(inputData); // Contract is controlled by restricting number of shapelets per series. shapeletsSearchedPerSeries = searchFunction.getNumShapeletsPerSeries(); shapelets = findBestKShapelets(inputData); // get k shapelets } protected void trainShapelets(TimeSeriesInstances data) { // we might round robin the data in here. // So we need to override the input data with the new ordering. // we don't need to undo the roundRobin because we clone the data into a // different order. inputDataTS = orderDataSet(data); // Initialise search function for ShapeletSearch object searchFunction.setComparator(shapeletComparator); searchFunction.init(inputDataTS); // setup shapelet distance function (sDist). Just initialises the count to 0 shapeletDistance.init(inputDataTS); // setup classValue classValue.init(inputDataTS); outputPrint("num shapelets before search " + numShapelets); // Contract is controlled by restricting number of shapelets per series. shapeletsSearchedPerSeries = searchFunction.getNumShapeletsPerSeries(); shapelets = findBestKShapelets(inputDataTS); // get k shapelets outputPrint(shapelets.size() + " Shapelets have been generated num shapelets now " + numShapelets); } /** * This method determines the order in which the series will be searched for * shapelets There are currently just two options: the original order or round * robin (take one of each class in turn). Round robin clones the data, which * could be an issue for resources but makes sense * * @param data * @return */ private Instances orderDataSet(Instances data) { int dataSize = data.numInstances(); // shapelets discovery has not yet been carried out, so this must be training // data dataSourceIDs = new int[dataSize]; Instances dataset = data; if (roundRobin) { // Reorder the data in round robin order dataset = roundRobinData(data, dataSourceIDs); } else { for (int i = 0; i < dataSize; i++) { dataSourceIDs[i] = i; } } return dataset; } /** * This method determines the order in which the series will be searched for * shapelets There are currently just two options: the original order or round * robin (take one of each class in turn). Round robin clones the data, which * could be an issue for resources but makes sense * * @param data * @return */ private TimeSeriesInstances orderDataSet(TimeSeriesInstances data) { int dataSize = data.numInstances(); // shapelets discovery has not yet been carried out, so this must be training // data dataSourceIDs = new int[dataSize]; TimeSeriesInstances dataset = data; if (roundRobin) { // Reorder the data in round robin order dataset = roundRobinData(data, dataSourceIDs); } else { for (int i = 0; i < dataSize; i++) { dataSourceIDs[i] = i; } } return dataset; } public TimeSeriesInstances buildTansformedDataset(TimeSeriesInstances data) { // init out data for transforming. shapeletDistance.init(inputDataTS); // setup classsValue classValue.init(inputDataTS); Shapelet s; // for each data, get distance to each shapelet and create new instance int size = shapelets.size(); int dataSize = data.numInstances(); //1 dimensional double[][][] out = new double[dataSize][1][size]; double dist; for (int i = 0; i < size; i++) { s = shapelets.get(i); shapeletDistance.setShapelet(s); for (int j = 0; j < dataSize; j++) { dist = shapeletDistance.calculate(data.get(j), j); out[j][0][i] = dist; } } return new TimeSeriesInstances(out, data.getClassIndexes(), data.getClassLabels()); } // given a set of instances transform it by the internal shapelets. public Instances buildTansformedDataset(Instances data) { // Reorder the training data and reset the shapelet indexes Instances output = determineOutputFormat(data); long startTime=System.nanoTime(); // init out data for transforming. shapeletDistance.init(data); // setup classsValue classValue.init(data); Shapelet s; // for each data, get distance to each shapelet and create new instance int size = shapelets.size(); int dataSize = data.numInstances(); // create our data instances for (int j = 0; j < dataSize; j++) { output.add(new DenseInstance(size + 1)); } double dist; for (int i = 0; i < size; i++) { s = shapelets.get(i); shapeletDistance.setShapelet(s); for (int j = 0; j < dataSize; j++) { dist = shapeletDistance.calculate(data.instance(j), j); output.instance(j).setValue(i, dist); } } // do the classValues. for (int j = 0; j < dataSize; j++) { // we always want to write the true ClassValue here. Irrelevant of binarised or // not. output.instance(j).setValue(size, data.instance(j).classValue()); } return output; } /** * protected method for extracting k shapelets. this method extracts shapelets * series by series, using the searchFunction method searchForShapeletsInSeries, * which itself uses checkCandidate 1. The search method determines the method * of choosing shapelets. By default all are evaluated (ShapeletSearch) or the * alternative RandomSearch, which finds a fixed number of shapelets determined * by the time contract. 2. The qualityFunction assesses each candidate, and * uses the worstShapelet (set in checkCandidate) to test for inclusion and any * lower bounding. I dont think it uses it to test for inclusion. 3. self * similar are removed by default, and the method combine is used to merge the * current candidates and the new ones * * @param data the data that the shapelets will be taken from * @return an ArrayList of FullShapeletTransform objects in order of their * fitness (by infoGain, seperationGap then shortest length) */ public ArrayList<Shapelet> findBestKShapelets(Instances data) { if (useBalancedClasses) return findBestKShapeletsBalanced(data); else return findBestKShapeletsOriginal(data); } public ArrayList<Shapelet> findBestKShapelets(TimeSeriesInstances data) { if (useBalancedClasses) return findBestKShapeletsBalanced(data); else return findBestKShapeletsOriginal(data); } /** * * @param data * @return */ private ArrayList<Shapelet> findBestKShapeletsBalanced(TimeSeriesInstances data) { // If the number of shapelets we can calculate exceeds the total number in the // series, we will revert to full search ShapeletSearch full = new ShapeletSearch(searchFunction.getOptions()); ShapeletSearch current = searchFunction; full.init(data); boolean contracted = true; boolean keepGoing = true; if (contractTime == 0) { contracted = false; } long startTime = System.nanoTime(); long usedTime = 0; // This can be used to reduce the number of series searched. Better done with // Aaron's Condenser int numSeriesToUse = data.numInstances(); // temp store of shapelets for each time series ArrayList<Shapelet> seriesShapelets; // construct a map for our K-shapelets lists, on for each classVal. if (kShapeletsMap == null) { kShapeletsMap = new TreeMap(); for (int i = 0; i < data.numClasses(); i++) { kShapeletsMap.put((double) i, new ArrayList<>()); } } // found out how many shapelets we want from each class, split evenly. int proportion = numShapelets / kShapeletsMap.keySet().size(); outputPrint("Processing data for numShapelets " + numShapelets + " with proportion per class = " + proportion); outputPrint("in contract balanced: Contract (secs)" + contractTime / 1000000000.0); long prevEarlyAbandons = 0; int passes = 0; // continue processing series until we run out of time (if contracted) while (casesSoFar < numSeriesToUse && keepGoing) { // outputPrint("BALANCED: "+casesSoFar +" Cumulative time (secs) = // "+usedTime/1000000000.0+" Contract time (secs) ="+contractTime/1000000000.0+" // contracted = "+contracted+" search type = "+searchFunction.getSearchType()); // get the Shapelets list based on the classValue of our current time series. kShapelets = kShapeletsMap.get((double) data.get(casesSoFar).getLabelIndex()); // we only want to pass in the worstKShapelet if we've found K shapelets. but we // only care about // this class values worst one. This is due to the way we represent each classes // shapelets in the map. worstShapelet = kShapelets.size() == proportion ? kShapelets.get(kShapelets.size() - 1) : null; // set the series we're working with. shapeletDistance.setSeries(casesSoFar); // set the class value of the series we're working with. classValue.setShapeletValue(data.get(casesSoFar)); long t1 = System.nanoTime(); seriesShapelets = current.searchForShapeletsInSeries(data.get(casesSoFar), this::checkCandidate); long t2 = System.nanoTime(); numShapeletsEvaluated += seriesShapelets.size(); if (adaptiveTiming && contracted && passes == 0) { long tempEA = numEarlyAbandons - prevEarlyAbandons; prevEarlyAbandons = numEarlyAbandons; double newTimePerShapelet = (double) (t2 - t1) / (seriesShapelets.size() + tempEA); if (totalShapeletsPerSeries < (seriesShapelets.size() + tempEA))// Switch to full enum for next // iteration current = full; else current = searchFunction; shapeletsSearchedPerSeries = adjustNumberPerSeries(contractTime - usedTime, numSeriesToUse - casesSoFar, newTimePerShapelet); searchFunction.setNumShapeletsPerSeries(shapeletsSearchedPerSeries); } if (seriesShapelets != null) { Collections.sort(seriesShapelets, shapeletComparator); if (isRemoveSelfSimilar()) seriesShapelets = removeSelfSimilar(seriesShapelets); kShapelets = combine(proportion, kShapelets, seriesShapelets); } // re-update the list because it's changed now. kShapeletsMap.put((double)data.get(casesSoFar).getLabelIndex(), kShapelets); casesSoFar++; createSerialFile(); usedTime = System.nanoTime() - startTime; // Logic is we have underestimated the contract so can run back through. If we // over estimate it we will just stop. if (contracted) { if (casesSoFar == numSeriesToUse - 1 && !searchFunction.getSearchType().equals("FULL")) { /// HORRIBLE! casesSoFar = 0; passes++; } if (usedTime > contractTime) keepGoing = false; } } kShapelets = buildKShapeletsFromMap(kShapeletsMap); this.numShapelets = kShapelets.size(); if (recordShapelets) recordShapelets(kShapelets, this.ouputFileLocation); // if (!supressOutput) // writeShapelets(kShapelets, new OutputStreamWriter(System.out)); return kShapelets; } private ArrayList<Shapelet> findBestKShapeletsBalanced(Instances data) { // If the number of shapelets we can calculate exceeds the total number in the // series, we will revert to full search System.out.println(" Contract enforced here mins = "+contractTime/(1000000000*60l)+" shapelets per series = "+shapeletsSearchedPerSeries); ShapeletSearch full = new ShapeletSearch(searchFunction.getOptions()); ShapeletSearch current = searchFunction; full.init(data); boolean contracted = true; boolean keepGoing = true; if (contractTime == 0) { contracted = false; } long startTime = System.nanoTime(); long usedTime = 0; // This can be used to reduce the number of series searched. Better done with // Aaron's Condenser int numSeriesToUse = data.numInstances(); // temp store of shapelets for each time series ArrayList<Shapelet> seriesShapelets; // construct a map for our K-shapelets lists, on for each classVal. if (kShapeletsMap == null) { kShapeletsMap = new TreeMap(); for (int i = 0; i < data.numClasses(); i++) { kShapeletsMap.put((double) i, new ArrayList<>()); } } // found out how many shapelets we want from each class, split evenly. int proportion = numShapelets / kShapeletsMap.keySet().size(); long prevEarlyAbandons = 0; int passes = 0; // continue processing series until we run out of time (if contracted) while (casesSoFar < numSeriesToUse && keepGoing) { if(casesSoFar%100==0) outputPrint("BALANCED: "+casesSoFar +" series used so far, num series to use ="+numSeriesToUse+" Cumulative time (secs) ="+usedTime/1000000000.0+" Contract time (secs) ="+contractTime/1000000000.0+" contracted = "+contracted+" search type = "+searchFunction.getSearchType()); // get the Shapelets list based on the classValue of our current time series. kShapelets = kShapeletsMap.get(data.get(casesSoFar).classValue()); // we only want to pass in the worstKShapelet if we've found K shapelets. but we // only care about // this class values worst one. This is due to the way we represent each classes // shapelets in the map. worstShapelet = kShapelets.size() == proportion ? kShapelets.get(kShapelets.size() - 1) : null; // set the series we're working with. shapeletDistance.setSeries(casesSoFar); // set the class value of the series we're working with. classValue.setShapeletValue(data.get(casesSoFar)); long t1 = System.nanoTime(); seriesShapelets = current.searchForShapeletsInSeries(data.get(casesSoFar), this::checkCandidate); long t2 = System.nanoTime(); numShapeletsEvaluated += seriesShapelets.size(); if (adaptiveTiming && contracted && passes == 0) { long tempEarlyAbandons = numEarlyAbandons - prevEarlyAbandons; prevEarlyAbandons = numEarlyAbandons; double newTimePerShapelet = (double) (t2 - t1) / (seriesShapelets.size() + tempEarlyAbandons); if (totalShapeletsPerSeries < (seriesShapelets.size() + tempEarlyAbandons))// Switch to full enum for next // iteration { current = full; } else current = searchFunction; // System.out.println(" time for case " + casesSoFar + " evaluate " + seriesShapelets.size() + " but what about early ones?"); // System.out.println(" Est time per shapelet " + timePerShapelet / 1000000000 + " actual "+ newTimePerShapelet / 1000000000); shapeletsSearchedPerSeries = adjustNumberPerSeries(contractTime - usedTime, numSeriesToUse - casesSoFar, newTimePerShapelet); // System.out.println("Changing number of shapelets sampled from " + searchFunction.getNumShapeletsPerSeries() + " to " + shapeletsSearchedPerSeries); searchFunction.setNumShapeletsPerSeries(shapeletsSearchedPerSeries); // System.out.println("data : " + casesSoFar + " has " + seriesShapelets.size() + " candidates" // + " cumulative early abandons " + numEarlyAbandons + " worst so far =" + worstShapelet // + " evaluated this series = " + (seriesShapelets.size() + tempEarlyAbandons)); } if (seriesShapelets != null) { Collections.sort(seriesShapelets, shapeletComparator); if (isRemoveSelfSimilar()) seriesShapelets = removeSelfSimilar(seriesShapelets); kShapelets = combine(proportion, kShapelets, seriesShapelets); } // re-update the list because it's changed now. kShapeletsMap.put(data.get(casesSoFar).classValue(), kShapelets); casesSoFar++; createSerialFile(); usedTime = System.nanoTime() - startTime; // Logic is we have underestimated the contract so can run back through. If we // over estimate it we will just stop. if (contracted) { if (casesSoFar == numSeriesToUse - 1 && !searchFunction.getSearchType().equals("FULL")) { /// HORRIBLE! casesSoFar = 0; passes++; } if (usedTime > contractTime) keepGoing = false; } } kShapelets = buildKShapeletsFromMap(kShapeletsMap); this.numShapelets = kShapelets.size(); if (recordShapelets) recordShapelets(kShapelets, this.ouputFileLocation); // if (!supressOutput) // writeShapelets(kShapelets, new OutputStreamWriter(System.out)); return kShapelets; } public boolean getUseBalancedClass(){ return useBalancedClasses;} protected ArrayList<Shapelet> buildKShapeletsFromMap(Map<Double, ArrayList<Shapelet>> kShapeletsMap) { ArrayList<Shapelet> kShapelets = new ArrayList<>(); int numberOfClassVals = kShapeletsMap.keySet().size(); int proportion = numShapelets / numberOfClassVals; Iterator<Shapelet> it; // all lists should be sorted. // go through the map and get the sub portion of best shapelets for the final // list. for (ArrayList<Shapelet> list : kShapeletsMap.values()) { int i = 0; it = list.iterator(); while (it.hasNext() && i++ <= proportion) { kShapelets.add(it.next()); } } return kShapelets; } public ArrayList<Shapelet> findBestKShapeletsOriginal(TimeSeriesInstances data) { ShapeletSearch full = new ShapeletSearch(searchFunction.getOptions()); boolean contracted = true; boolean keepGoing = true; if (contractTime == 0) { contracted = false; } long startTime = System.nanoTime(); long usedTime = 0; int numSeriesToUse = data.numInstances(); // This can be used to reduce the number of series in favour of more ArrayList<Shapelet> seriesShapelets; // temp store of all shapelets for each time series int dataSize = data.numInstances(); // for all possible time series. long prevEarlyAbandons = 0; int passes = 0; while (casesSoFar < numSeriesToUse && keepGoing) { outputPrint("ORIGINAL: "+casesSoFar +" Cumulative time (secs) ="+usedTime/1000000000.0+" Contract time (secs) ="+contractTime/1000000000.0+" search type = "+searchFunction.getSearchType()); // set the worst Shapelet so far, as long as the shapelet set is full. worstShapelet = kShapelets.size() == numShapelets ? kShapelets.get(numShapelets - 1) : null; // set the series we're working with. shapeletDistance.setSeries(casesSoFar); // set the class value of the series we're working with. classValue.setShapeletValue(data.get(casesSoFar)); long t1 = System.nanoTime(); seriesShapelets = searchFunction.searchForShapeletsInSeries(data.get(casesSoFar), this::checkCandidate); long t2 = System.nanoTime(); numShapeletsEvaluated += seriesShapelets.size(); if (adaptiveTiming && contracted && passes == 0) { long tempEA = numEarlyAbandons - prevEarlyAbandons; prevEarlyAbandons = numEarlyAbandons; double newTimePerShapelet = (double) (t2 - t1) / (seriesShapelets.size() + tempEA); shapeletsSearchedPerSeries = adjustNumberPerSeries(contractTime - usedTime, numSeriesToUse - casesSoFar, newTimePerShapelet); searchFunction.setNumShapeletsPerSeries(shapeletsSearchedPerSeries); } if (seriesShapelets != null) { Collections.sort(seriesShapelets, shapeletComparator); if (isRemoveSelfSimilar()) seriesShapelets = removeSelfSimilar(seriesShapelets); kShapelets = combine(numShapelets, kShapelets, seriesShapelets); } casesSoFar++; createSerialFile(); usedTime = System.nanoTime() - startTime; // Logic is we have underestimated the contract so can run back through. If we // over estimate it we will just stop. if (casesSoFar == numSeriesToUse - 1 && !searchFunction.getSearchType().equals("FULL")) { /// HORRIBLE! casesSoFar = 0; passes++; } if (contracted) { if (usedTime > contractTime) keepGoing = false; } } this.numShapelets = kShapelets.size(); if (recordShapelets) recordShapelets(kShapelets, this.ouputFileLocation); // if (!supressOutput) // writeShapelets(kShapelets, new OutputStreamWriter(System.out)); return kShapelets; } /* * This just goes case by case with no class balancing. With two class problems, * we found this better */ public ArrayList<Shapelet> findBestKShapeletsOriginal(Instances data) { ShapeletSearch full = new ShapeletSearch(searchFunction.getOptions()); boolean contracted = true; boolean keepGoing = true; if (contractTime == 0) { contracted = false; } long startTime = System.nanoTime(); long usedTime = 0; int numSeriesToUse = data.numInstances(); // This can be used to reduce the number of series in favour of more ArrayList<Shapelet> seriesShapelets; // temp store of all shapelets for each time series int dataSize = data.numInstances(); // for all possible time series. long prevEarlyAbandons = 0; int passes = 0; while (casesSoFar < numSeriesToUse && keepGoing) { // outputPrint("ORIGINAL: "+casesSoFar +" Cumulative time (secs) = // "+usedTime/1000000000.0+" Contract time (secs) ="+contractTime/1000000000.0+" // search type = "+searchFunction.getSearchType()); // set the worst Shapelet so far, as long as the shapelet set is full. worstShapelet = kShapelets.size() == numShapelets ? kShapelets.get(numShapelets - 1) : null; // set the series we're working with. shapeletDistance.setSeries(casesSoFar); // set the class value of the series we're working with. classValue.setShapeletValue(data.get(casesSoFar)); long t1 = System.nanoTime(); seriesShapelets = searchFunction.searchForShapeletsInSeries(data.get(casesSoFar), this::checkCandidate); long t2 = System.nanoTime(); numShapeletsEvaluated += seriesShapelets.size(); if (adaptiveTiming && contracted && passes == 0) { long tempEA = numEarlyAbandons - prevEarlyAbandons; prevEarlyAbandons = numEarlyAbandons; double newTimePerShapelet = (double) (t2 - t1) / (seriesShapelets.size() + tempEA); shapeletsSearchedPerSeries = adjustNumberPerSeries(contractTime - usedTime, numSeriesToUse - casesSoFar, newTimePerShapelet); searchFunction.setNumShapeletsPerSeries(shapeletsSearchedPerSeries); } if (seriesShapelets != null) { Collections.sort(seriesShapelets, shapeletComparator); if (isRemoveSelfSimilar()) seriesShapelets = removeSelfSimilar(seriesShapelets); kShapelets = combine(numShapelets, kShapelets, seriesShapelets); } casesSoFar++; createSerialFile(); usedTime = System.nanoTime() - startTime; // Logic is we have underestimated the contract so can run back through. If we // over estimate it we will just stop. if (casesSoFar == numSeriesToUse - 1 && !searchFunction.getSearchType().equals("FULL")) { /// HORRIBLE! casesSoFar = 0; passes++; } if (contracted) { if (usedTime > contractTime) keepGoing = false; } } this.numShapelets = kShapelets.size(); if (recordShapelets) recordShapelets(kShapelets, this.ouputFileLocation); // if (!supressOutput) // writeShapelets(kShapelets, new OutputStreamWriter(System.out)); return kShapelets; } private long adjustNumberPerSeries(long timeRemaining, int seriesRemaining, double lastTimePerShapelet) { // reinforce time per shapelet timePerShapelet = (1 - beta) * timePerShapelet + beta * lastTimePerShapelet; // Find time left per series long timePerSeries = timeRemaining / seriesRemaining; // Find how many we think we can do in that time long shapeletsPerSeries = (long) (timePerSeries / timePerShapelet); if (shapeletsPerSeries < 1) return 1; return shapeletsPerSeries; } public void createSerialFile() { if (serialName == null) return; // Serialise the object. ObjectOutputStream out = null; try { out = new ObjectOutputStream(new FileOutputStream(serialName)); out.writeObject(this); } catch (IOException ex) { System.out.println("Failed to write " + ex); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { System.out.println("Failed to close " + ex); } } } } /** * protected method for extracting k shapelets. * * @param numShapelets * @param data the data that the shapelets will be taken from * @param minShapeletLength * @param maxShapeletLength * @return an ArrayList of FullShapeletTransform objects in order of their * fitness (by infoGain, seperationGap then shortest length) */ public ArrayList<Shapelet> findBestKShapelets(int numShapelets, Instances data, int minShapeletLength, int maxShapeletLength) { this.numShapelets = numShapelets; // setup classsValue classValue.init(data); // setup subseqDistance shapeletDistance.init(data); Instances newData = orderDataSet(data); return findBestKShapelets(newData); } /** * Private method to combine two ArrayList collections of FullShapeletTransform * objects. * * @param k the maximum number of shapelets to be returned * after combining the two lists * @param kBestSoFar the (up to) k best shapelets that have been * observed so far, passed in to combine with * shapelets from a new series (sorted) * @param timeSeriesShapelets the shapelets taken from a new series that are to * be merged in descending order of fitness with the * kBestSoFar * @return an ordered ArrayList of the best k (or less) (sorted) * FullShapeletTransform objects from the union of the input ArrayLists */ protected ArrayList<Shapelet> combine(int k, ArrayList<Shapelet> kBestSoFar, ArrayList<Shapelet> timeSeriesShapelets) { // both kBestSofar and timeSeries are sorted so we can exploit this. // maintain a pointer for each list. ArrayList<Shapelet> newBestSoFar = new ArrayList<>(); // best so far pointer int bsfPtr = 0; // new time seris pointer. int tssPtr = 0; for (int i = 0; i < k; i++) { Shapelet shapelet1 = null, shapelet2 = null; if (bsfPtr < kBestSoFar.size()) { shapelet1 = kBestSoFar.get(bsfPtr); } if (tssPtr < timeSeriesShapelets.size()) { shapelet2 = timeSeriesShapelets.get(tssPtr); } boolean shapelet1Null = shapelet1 == null; boolean shapelet2Null = shapelet2 == null; // both lists have been explored, but we have less than K elements. if (shapelet1Null && shapelet2Null) { break; } // one list is expired keep adding the other list until we reach K. if (shapelet1Null) { // even if the list has expired don't just add shapelets without considering // they may be dupes. AddToBestSoFar(shapelet2, newBestSoFar); tssPtr++; continue; } // one list is expired keep adding the other list until we reach K. if (shapelet2Null) { // even if the list has expired don't just add shapelets without considering // they may be dupes. AddToBestSoFar(shapelet1, newBestSoFar); bsfPtr++; continue; } // if both lists are fine then we need to compare which one to use. int compare = shapeletComparator.compare(shapelet1, shapelet2); if (compare < 0) { AddToBestSoFar(shapelet1, newBestSoFar); bsfPtr++; shapelet1 = null; } else { AddToBestSoFar(shapelet2, newBestSoFar); tssPtr++; shapelet2 = null; } } return newBestSoFar; } private void AddToBestSoFar(Shapelet shapelet1, ArrayList<Shapelet> newBestSoFar) { boolean containsMatchingShapelet = false; if (pruneMatchingShapelets) containsMatchingShapelet = containsMatchingShapelet(shapelet1, newBestSoFar); if (!containsMatchingShapelet) newBestSoFar.add(shapelet1); } private boolean containsMatchingShapelet(Shapelet shapelet, ArrayList<Shapelet> newBestSoFar) { // we're going to be comparing all the shapelets we have to shapelet. this.shapeletDistance.setShapelet(shapelet); // go backwards from where we're at until we stop matching. List is sorted. for (int index = newBestSoFar.size() - 1; index >= 0; index--) { Shapelet shape = newBestSoFar.get(index); int compare2 = shapeletComparator.compare(shape, shapelet); // if we are not simply equal to the shapelet that we're looking at then abandon // ship. if (compare2 != 0) { return false; // stop evaluating. we no longer have any matches. } // if we're here then evaluate the shapelet distance. if they're equal in the // comparator it means same length, same IG. double dist = this.shapeletDistance.distanceToShapelet(shape); // if we hit a shapelet we nearly match with 1e-6 match with stop checking. if (NumUtils.isNearlyEqual(dist, 0.0)) { return true; // this means we should not add the shapelet. } } return false; } /** * protected method to remove self-similar shapelets from an ArrayList (i.e. if * they come from the same series and have overlapping indicies) * * @param shapelets the input Shapelets to remove self similar * FullShapeletTransform objects from * @return a copy of the input ArrayList with self-similar shapelets removed */ protected static ArrayList<Shapelet> removeSelfSimilar(ArrayList<Shapelet> shapelets) { // return a new pruned array list - more efficient than removing // self-similar entries on the fly and constantly reindexing ArrayList<Shapelet> outputShapelets = new ArrayList<>(); int size = shapelets.size(); boolean[] selfSimilar = new boolean[size]; for (int i = 0; i < size; i++) { if (selfSimilar[i]) { continue; } outputShapelets.add(shapelets.get(i)); for (int j = i + 1; j < size; j++) { // no point recalc'ing if already self similar to something if ((!selfSimilar[j]) && selfSimilarity(shapelets.get(i), shapelets.get(j))) { selfSimilar[j] = true; } } } return outputShapelets; } protected Shapelet checkCandidate(TimeSeriesInstance series, int start, int length, int dimension) { // init qualityBound. initQualityBound(classValue.getClassDistributions()); // Set bound of the bounding algorithm if (worstShapelet != null) { quality.setBsfQuality(worstShapelet.qualityValue); } // set the candidate. This is the instance, start and length. shapeletDistance.setCandidate(series, start, length, dimension); // create orderline by looping through data set and calculating the subsequence // distance from candidate to all data, inserting in order. ArrayList<OrderLineObj> orderline = new ArrayList<>(); int dataSize = inputDataTS.numInstances(); for (int i = 0; i < dataSize; i++) { // Check if it is possible to prune the candidate if (quality.pruneCandidate()) { numEarlyAbandons++; return null; } double distance = 0.0; // don't compare the shapelet to the the time series it came from because we // know it's 0. if (i != casesSoFar) { distance = shapeletDistance.calculate(inputDataTS.get(i), i); } // this could be binarised or normal. double classVal = classValue.getClassValue(inputDataTS.get(i)); // without early abandon, it is faster to just add and sort at the end orderline.add(new OrderLineObj(distance, classVal)); // Update qualityBound - presumably each bounding method for different quality // measures will have a different update procedure. quality.updateOrderLine(orderline.get(orderline.size() - 1)); } Shapelet shapelet = new Shapelet(shapeletDistance.getCandidate(), dataSourceIDs[casesSoFar], start, quality.getQualityMeasure()); // this class distribution could be binarised or normal. shapelet.calculateQuality(orderline, classValue.getClassDistributions()); shapelet.classValue = classValue.getShapeletValue(); // set classValue of shapelet. (interesing to know). shapelet.dimension = dimension; return shapelet; } protected Shapelet checkCandidate(Instance series, int start, int length, int dimension) { // init qualityBound. initQualityBound(classValue.getClassDistributions()); // Set bound of the bounding algorithm if (worstShapelet != null) { quality.setBsfQuality(worstShapelet.qualityValue); } // set the candidate. This is the instance, start and length. shapeletDistance.setCandidate(series, start, length, dimension); // create orderline by looping through data set and calculating the subsequence // distance from candidate to all data, inserting in order. ArrayList<OrderLineObj> orderline = new ArrayList<>(); int dataSize = inputData.numInstances(); for (int i = 0; i < dataSize; i++) { // Check if it is possible to prune the candidate if (quality.pruneCandidate()) { numEarlyAbandons++; return null; } double distance = 0.0; // don't compare the shapelet to the the time series it came from because we // know it's 0. if (i != casesSoFar) { distance = shapeletDistance.calculate(inputData.instance(i), i); } // this could be binarised or normal. double classVal = classValue.getClassValue(inputData.instance(i)); // without early abandon, it is faster to just add and sort at the end orderline.add(new OrderLineObj(distance, classVal)); // Update qualityBound - presumably each bounding method for different quality // measures will have a different update procedure. quality.updateOrderLine(orderline.get(orderline.size() - 1)); } Shapelet shapelet = new Shapelet(shapeletDistance.getCandidate(), dataSourceIDs[casesSoFar], start, quality.getQualityMeasure()); // this class distribution could be binarised or normal. shapelet.calculateQuality(orderline, classValue.getClassDistributions()); shapelet.classValue = classValue.getShapeletValue(); // set classValue of shapelet. (interesing to know). shapelet.dimension = dimension; return shapelet; } /** * Load a set of Instances from an ARFF * * @param fileName the file name of the ARFF * @return a set of Instances from the ARFF */ public static Instances loadData(String fileName) { Instances data = null; try { FileReader r; r = new FileReader(fileName); data = new Instances(r); data.setClassIndex(data.numAttributes() - 1); } catch (IOException e) { System.out.println(" Error =" + e + " in method loadData"); } return data; } /** * A private method to assess the self similarity of two FullShapeletTransform * objects (i.e. whether they have overlapping indicies and are taken from the * same time series). * * @param shapelet the first FullShapeletTransform object (in practice, this * will be the dominant shapelet with quality >= candidate) * @param candidate the second FullShapeletTransform * @return */ private static boolean selfSimilarity(Shapelet shapelet, Shapelet candidate) { // check whether they're the same dimension or not. if (candidate.seriesId == shapelet.seriesId && candidate.dimension == shapelet.dimension) { if (candidate.startPos >= shapelet.startPos && candidate.startPos < shapelet.startPos + shapelet.getLength()) { // candidate starts within // exisiting shapelet return true; } if (shapelet.startPos >= candidate.startPos && shapelet.startPos < candidate.startPos + candidate.getLength()) { return true; } } return false; } /** * A method to read in a FullShapeletTransform log file to reproduce a * FullShapeletTransform * <p> * NOTE: assumes shapelets from log are Z-NORMALISED * * @param fileName the name and path of the log file * @return a duplicate FullShapeletTransform to the object that created the * original log file * @throws Exception */ public static ShapeletTransform createFilterFromFile(String fileName) throws Exception { return createFilterFromFile(fileName, Integer.MAX_VALUE); } /** * A method to obtain time taken to find a single best shapelet in the data set * * @param data the data set to be processed * @param minShapeletLength minimum shapelet length * @param maxShapeletLength maximum shapelet length * @return time in seconds to find the best shapelet */ public double timingForSingleShapelet(Instances data, int minShapeletLength, int maxShapeletLength) { data = roundRobinData(data, null); long startTime = System.nanoTime(); findBestKShapelets(1, data, minShapeletLength, maxShapeletLength); long finishTime = System.nanoTime(); return (double) (finishTime - startTime) / 1000000000.0; } public void writeAdditionalData(String saveDirectory, int fold) { recordShapelets(this.kShapelets, saveDirectory + "_shapelets" + fold + ".csv"); } public void recordShapelets(ArrayList<Shapelet> kShapelets, String saveLocation) { // just in case the file doesn't exist or the directories. File file = new File(saveLocation); if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } try (FileWriter out = new FileWriter(file)) { writeShapelets(kShapelets, out); } catch (IOException ex) { Logger.getLogger(ShapeletTransform.class.getName()).log(Level.SEVERE, null, ex); } } protected void writeShapelets(ArrayList<Shapelet> kShapelets, OutputStreamWriter out) { try { out.append("informationGain,seriesId,startPos,classVal,numChannels,dimension\n"); for (Shapelet kShapelet : kShapelets) { out.append(kShapelet.qualityValue + "," + kShapelet.seriesId + "," + kShapelet.startPos + "," + kShapelet.classValue + "," + kShapelet.getNumDimensions() + "," + kShapelet.dimension + "\n"); for (int i = 0; i < kShapelet.numDimensions; i++) { double[] shapeletContent = kShapelet.getContent().getShapeletContent(i); for (int j = 0; j < shapeletContent.length; j++) { out.append(shapeletContent[j] + ","); } out.append("\n"); } } } catch (IOException ex) { Logger.getLogger(ShapeletTransform.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a list of the lengths of the shapelets found by this transform. * * @return An ArrayList of Integers representing the lengths of the shapelets. */ public ArrayList<Integer> getShapeletLengths() { ArrayList<Integer> shapeletLengths = new ArrayList<>(); if (shapelets != null) { for (Shapelet s : this.shapelets) { shapeletLengths.add(s.getLength()); } } return shapeletLengths; } /** * A method to read in a FullShapeletTransform log file to reproduce a * FullShapeletTransform, * <p> * NOTE: assumes shapelets from log are Z-NORMALISED * * @param fileName the name and path of the log file * @param maxShapelets * @return a duplicate FullShapeletTransform to the object that created the * original log file * @throws Exception */ public static ShapeletTransform createFilterFromFile(String fileName, int maxShapelets) throws Exception { File input = new File(fileName); Scanner scan = new Scanner(input); scan.useDelimiter("\n"); ShapeletTransform sf = new ShapeletTransform(); ArrayList<Shapelet> shapelets = new ArrayList<>(); String shapeletContentString; String shapeletStatsString; ArrayList<Double> content; double[] contentArray; Scanner lineScan; Scanner statScan; double qualVal; int serID; int starPos; int shapeletCount = 0; while (shapeletCount < maxShapelets && scan.hasNext()) { shapeletStatsString = scan.next(); shapeletContentString = scan.next(); // Get the shapelet stats statScan = new Scanner(shapeletStatsString); statScan.useDelimiter(","); qualVal = Double.parseDouble(statScan.next().trim()); serID = Integer.parseInt(statScan.next().trim()); starPos = Integer.parseInt(statScan.next().trim()); // End of shapelet stats lineScan = new Scanner(shapeletContentString); lineScan.useDelimiter(","); content = new ArrayList<>(); while (lineScan.hasNext()) { String next = lineScan.next().trim(); if (!next.isEmpty()) { content.add(Double.parseDouble(next)); } } contentArray = new double[content.size()]; for (int i = 0; i < content.size(); i++) { contentArray[i] = content.get(i); } contentArray = sf.shapeletDistance.seriesRescaler.rescaleSeries(contentArray, false); ShapeletCandidate cand = new ShapeletCandidate(); cand.setShapeletContent(contentArray); Shapelet s = new Shapelet(cand, qualVal, serID, starPos); shapelets.add(s); shapeletCount++; } sf.shapelets = shapelets; sf.searchComplete = true; sf.numShapelets = shapelets.size(); sf.setShapeletMinAndMax(1, 1); return sf; } /** * A method to read in a shapelet csv file and return a shapelet arraylist. * * @param f * @return a duplicate FullShapeletTransform to the object that created the * original log file * @throws FileNotFoundException */ public static ArrayList<Shapelet> readShapeletCSV(File f) throws FileNotFoundException { ArrayList<Shapelet> shapelets = new ArrayList<>(); Scanner sc = new Scanner(f); System.out.println(sc.nextLine()); boolean readHeader = true; double quality = 0, classVal = 0; int series = 0, position = 0, dimension = 0, numDimensions = 1; ShapeletCandidate cand = null; int currentDim = 0; while (sc.hasNextLine()) { String line = sc.nextLine(); String[] cotentsAsString = line.split(","); if (readHeader) { quality = Double.parseDouble(cotentsAsString[0]); series = Integer.parseInt(cotentsAsString[1]); position = Integer.parseInt(cotentsAsString[2]); classVal = Double.parseDouble(cotentsAsString[3]); numDimensions = Integer.parseInt(cotentsAsString[4]); dimension = Integer.parseInt(cotentsAsString[5]); cand = new ShapeletCandidate(numDimensions); currentDim = 0; readHeader = false; } else { // read dims until we run out. double[] content = new double[cotentsAsString.length]; for (int i = 0; i < content.length; i++) { content[i] = Double.parseDouble(cotentsAsString[i]); } // set the content for the current channel. cand.setShapeletContent(currentDim, content); currentDim++; // if we've evald all the current dim data for a shapelet we can add it to the // list, and move on with the next one. if (currentDim == numDimensions) { Shapelet shapelet = new Shapelet(cand, quality, series, position); shapelet.dimension = dimension; shapelet.classValue = classVal; shapelets.add(shapelet); readHeader = true; } } } return shapelets; } /** * Method to reorder the given Instances in round robin order * * @param data Instances to be reordered * @param sourcePos Pointer to array of ints, where old positions of instances * are to be stored. * @return Instances in round robin order */ public static Instances roundRobinData(Instances data, int[] sourcePos) { // Count number of classes TreeMap<Double, ArrayList<Instance>> instancesByClass = new TreeMap<>(); TreeMap<Double, ArrayList<Integer>> positionsByClass = new TreeMap<>(); NormalClassValue ncv = new NormalClassValue(); ncv.init(data); // Get class distributions ClassCounts classDistribution = ncv.getClassDistributions(); // Allocate arrays for instances of every class for (int i = 0; i < classDistribution.size(); i++) { int frequency = classDistribution.get(i); instancesByClass.put((double) i, new ArrayList<>(frequency)); positionsByClass.put((double) i, new ArrayList<>(frequency)); } int dataSize = data.numInstances(); // Split data according to their class memebership for (int i = 0; i < dataSize; i++) { Instance inst = data.instance(i); instancesByClass.get(ncv.getClassValue(inst)).add(inst); positionsByClass.get(ncv.getClassValue(inst)).add(i); } // Merge data into single list in round robin order Instances roundRobinData = new Instances(data, dataSize); for (int i = 0; i < dataSize;) { // Allocate arrays for instances of every class for (int j = 0; j < classDistribution.size(); j++) { ArrayList<Instance> currentList = instancesByClass.get((double) j); ArrayList<Integer> currentPositions = positionsByClass.get((double) j); if (!currentList.isEmpty()) { roundRobinData.add(currentList.remove(currentList.size() - 1)); if (sourcePos != null && sourcePos.length == dataSize) { sourcePos[i] = currentPositions.remove(currentPositions.size() - 1); } i++; } } } return roundRobinData; } /** * Method to reorder the given Instances in round robin order * * @param data Instances to be reordered * @param sourcePos Pointer to array of ints, where old positions of instances * are to be stored. * @return Instances in round robin order */ public static TimeSeriesInstances roundRobinData(TimeSeriesInstances data, int[] sourcePos) { // Count number of classes TreeMap<Double, ArrayList<TimeSeriesInstance>> instancesByClass = new TreeMap<>(); TreeMap<Double, ArrayList<Integer>> positionsByClass = new TreeMap<>(); NormalClassValue ncv = new NormalClassValue(); ncv.init(data); // Get class distributions ClassCounts classDistribution = ncv.getClassDistributions(); // Allocate arrays for instances of every class for (int i = 0; i < classDistribution.size(); i++) { int frequency = classDistribution.get(i); instancesByClass.put((double) i, new ArrayList<>(frequency)); positionsByClass.put((double) i, new ArrayList<>(frequency)); } int dataSize = data.numInstances(); // Split data according to their class memebership for (int i = 0; i < dataSize; i++) { TimeSeriesInstance inst = data.get(i); instancesByClass.get(ncv.getClassValue(inst)).add(inst); positionsByClass.get(ncv.getClassValue(inst)).add(i); } // Merge data into single list in round robin order TimeSeriesInstances roundRobinData = new TimeSeriesInstances(data.getClassLabels()); for (int i = 0; i < dataSize;) { // Allocate arrays for instances of every class for (int j = 0; j < classDistribution.size(); j++) { ArrayList<TimeSeriesInstance> currentList = instancesByClass.get((double) j); ArrayList<Integer> currentPositions = positionsByClass.get((double) j); if (!currentList.isEmpty()) { roundRobinData.add(currentList.remove(currentList.size() - 1)); if (sourcePos != null && sourcePos.length == dataSize) { sourcePos[i] = currentPositions.remove(currentPositions.size() - 1); } i++; } } } return roundRobinData; } public void outputPrint(String val) { if (!this.supressOutput) { System.out.println(val); } } @Override public String toString() { String str = "Shapelets: \n"; for (Shapelet s : shapelets) { str += s.toString() + "\n"; } return str; } public String getShapeletCounts() { return "numShapelets," + numShapelets + ",numShapeletsEvaluated," + numShapeletsEvaluated + ",numEarlyAbandons," + numEarlyAbandons; } // searchFunction public String getParameters() { String str = "minShapeletLength," + searchFunction.getMin() + ",maxShapeletLength," + searchFunction.getMax() + ",numShapelets," + numShapelets + ",numShapeletsEvaluated," + numShapeletsEvaluated + ",numEarlyAbandons," + numEarlyAbandons + ",searchFunction," + this.searchFunction.getSearchType() + ",qualityMeasure," + this.quality.getQualityMeasure().getClass().getSimpleName() + ",subseqDistance," + this.shapeletDistance.getClass().getSimpleName() + ",roundrobin," + roundRobin + ",earlyAbandon," + useCandidatePruning + ",TransformClass," + this.getClass().getSimpleName(); return str; } /** * * @param data * @param minShapeletLength * @param maxShapeletLength * @return * @throws Exception */ public long opCountForSingleShapelet(Instances data, int minShapeletLength, int maxShapeletLength) throws Exception { data = roundRobinData(data, null); subseqDistOpCount = 0; findBestKShapelets(1, data, minShapeletLength, maxShapeletLength); return subseqDistOpCount; } public static void main(String[] args) { } /** * @return the removeSelfSimilar */ public boolean isRemoveSelfSimilar() { return removeSelfSimilar; } /** * @param removeSelfSimilar the removeSelfSimilar to set */ public void setRemoveSelfSimilar(boolean removeSelfSimilar) { this.removeSelfSimilar = removeSelfSimilar; } /** * @return the pruneMatchingShapelets */ public boolean isPruneMatchingShapelets() { return pruneMatchingShapelets; } /** * @param pruneMatchingShapelets the pruneMatchingShapelets to set */ public void setPruneMatchingShapelets(boolean pruneMatchingShapelets) { this.pruneMatchingShapelets = pruneMatchingShapelets; } public void setClassValue(NormalClassValue cv) { classValue = cv; } public void setSearchFunction(ShapeletSearch shapeletSearch) { searchFunction = shapeletSearch; } public ShapeletSearch getSearchFunction() { return searchFunction; } public void setSerialName(String sName) { serialName = sName; } public void useSeparationGap() { shapeletComparator = new Shapelet.ReverseSeparationGap(); } public void setShapeletComparator(Comparator<Shapelet> comp) { shapeletComparator = comp; } public void setUseRoundRobin(boolean b) { useRoundRobin = b; } public ShapeletDistance getSubSequenceDistance() { return shapeletDistance; } public TechnicalInformation getTechnicalInformation() { TechnicalInformation result; result = new TechnicalInformation(TechnicalInformation.Type.ARTICLE); result.setValue(TechnicalInformation.Field.AUTHOR, "authors"); result.setValue(TechnicalInformation.Field.YEAR, "put in Aarons paper"); result.setValue(TechnicalInformation.Field.TITLE, "stuff"); result.setValue(TechnicalInformation.Field.JOURNAL, "places"); result.setValue(TechnicalInformation.Field.VOLUME, "vol"); result.setValue(TechnicalInformation.Field.PAGES, "pages"); return result; } public void turnOffLog() { this.recordShapelets = false; } public void supressOutput() { this.supressOutput = true; } /** * Use candidate pruning technique when checking candidate quality. This speeds * up the transform processing time. */ public void useCandidatePruning() { this.useCandidatePruning = true; this.candidatePruningStartPercentage = 10; } /** * Use candidate pruning technique when checking candidate quality. This speeds * up the transform processing time. * * @param percentage the percentage of data to be preprocessed before pruning is * initiated. In most cases the higher the percentage the less * effective pruning becomes */ public void useCandidatePruning(int percentage) { this.useCandidatePruning = true; this.candidatePruningStartPercentage = percentage; } /********************** SETTERS ************************************/ /** * Shouldnt really have this method, but it is a convenience to allow * refactoring ClusteredShapeletTransform * * @param s */ public void setShapelets(ArrayList<Shapelet> s) { this.shapelets = s; } /** * Set the transform to round robin the data or not. This transform defaults * round robin to false to keep the instances in the same order as the original * data. If round robin is set to true, the transformed data will be reordered * which can make it more difficult to use the ensemble. * * @param val */ public void setRoundRobin(boolean val) { this.roundRobin = val; } public void setUseBalancedClasses(boolean val) { this.useBalancedClasses = val; } public void setSuppressOutput(boolean b) { this.supressOutput = !b; } public void setNumberOfShapelets(int k) { this.numShapelets = k; } /** * Set file path for the filter log. Filter log includes shapelet quality, * seriesId, startPosition, and content for each shapelet. * * @param fileName the updated file path of the filter log */ public void setLogOutputFile(String fileName) { this.recordShapelets = true; this.ouputFileLocation = fileName; } /** * Mutator method to set the minimum and maximum shapelet lengths for the * filter. * * @param min minimum length of shapelets * @param max maximum length of shapelets */ public void setShapeletMinAndMax(int min, int max) { searchFunction.setMinAndMax(min, max); } public void setQualityMeasure(ShapeletQualityChoice qualityChoice) { quality = new ShapeletQuality(qualityChoice); } public void setRescaler(SeriesRescaler rescaler) { if (shapeletDistance != null) this.shapeletDistance.seriesRescaler = rescaler; } public void setCandidatePruning(boolean f) { this.useCandidatePruning = f; this.candidatePruningStartPercentage = f ? 10 : 100; } public void setContractTime(long c) { contractTime = c; } public void setAdaptiveTiming(boolean b) { adaptiveTiming = b; } public void setTimePerShapelet(double t) { timePerShapelet = t; } public void setShapeletDistance(ShapeletDistance ssd) { shapeletDistance = ssd; } /*************** GETTERS *************/ public long getCount() { return count; } public ShapeletQualityChoice getQualityMeasure() { return quality.getChoice(); } public int getNumberOfShapelets() { return numShapelets; } public long getNumShapeletsPerSeries() { return searchFunction.getNumShapeletsPerSeries(); } public ArrayList<Shapelet> getShapelets() { return this.shapelets; } public boolean getSuppressOutput() { return this.supressOutput; } @Override public boolean isFit() { return searchComplete; } }
76,805
39.616605
292
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Sine.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.io.File; import java.io.IOException; import experiments.data.DatasetLoading; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import weka.core.*; /* * copyright: Anthony Bagnall * @author Aaron Bostrom * * */ public class Sine implements Transformer { @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { //multidimensional sine. sine applied series wise for each dimension double[][] out = new double[inst.getNumDimensions()][]; int index = 0; for(TimeSeries ts : inst){ double[] data = new double[ts.getSeriesLength()]; double n = data.length; for (int k = 0; k < n; k++) { double fk = 0; for (int i = 0; i < n; i++) { double c = k * (i + 0.5) * (Math.PI / n); fk += ts.getValue(i) * Math.sin(c); } data[k] = fk; } out[index++] = data; } return new TimeSeriesInstance(out, inst.getLabelIndex()); } @Override public Instance transform(Instance inst) { int n=inst.numAttributes()-1; Instance newInst= new DenseInstance(inst.numAttributes()); for(int k=0;k<n;k++){ double fk=0; for(int i=0;i<n;i++){ double c=k*(i+0.5)*(Math.PI/n); fk+=inst.value(i)*Math.sin(c); } newInst.setValue(k, fk); } newInst.setValue(inst.classIndex(), inst.classValue()); return newInst; } public Instances determineOutputFormat(Instances inputFormat) { FastVector<Attribute> atts = new FastVector<>(); for (int i = 0; i < inputFormat.numAttributes() - 1; i++) { // Add to attribute list String name = "Sine_" + i; atts.addElement(new Attribute(name)); } // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); FastVector<String> vals = new FastVector<>(target.numValues()); for (int i = 0; i < target.numValues(); i++) vals.addElement(target.value(i)); atts.addElement(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); Instances result = new Instances("SINE" + inputFormat.relationName(), atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } return result; } public static void main(String[] args) throws IOException { String localPath="src/main/java/experiments/data/tsc/"; String datasetName = "ChinaTown"; Instances train = DatasetLoading.loadData(localPath + datasetName + File.separator + datasetName+"_TRAIN.ts"); Instances test = DatasetLoading.loadData(localPath + datasetName + File.separator + datasetName+"_TEST.ts"); Sine sineTransform= new Sine(); Instances out_train = sineTransform.transform(train); Instances out_test = sineTransform.transform(test); System.out.println(out_train.toString()); System.out.println(out_test.toString()); } }
4,087
35.5
118
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Slope.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import java.util.ArrayList; import java.util.Arrays; /** * This class splits a time series into intervals of approximately equal length. * Then within each interval, a least squares regression line is calculated and * the gradient of this line is returned. Therefore, this transformer will * produce a time series of length numIntervals where each element represents * the gradient of the line within each interval. * * @author Vincent Nicholson * */ public class Slope implements Transformer { private int numIntervals; public Slope() { this.numIntervals = 8; } public Slope(int numIntervals) { this.numIntervals = numIntervals; } public int getNumIntervals() { return this.numIntervals; } public void setNumIntervals(int numIntervals) { this.numIntervals = numIntervals; } @Override public Instance transform(Instance inst) { double[] data = inst.toDoubleArray(); // remove class attribute if needed double[] temp; int c = inst.classIndex(); if (c >= 0) { temp = new double[data.length - 1]; System.arraycopy(data, 0, temp, 0, c); // assumes class attribute is in last index data = temp; } checkParameters(data.length); double[] gradients = getGradients(data); // Now in DWT form, extract out the terms and set the attributes of new instance Instance newInstance; int numAtts = gradients.length; if (inst.classIndex() >= 0) newInstance = new DenseInstance(numAtts + 1); else newInstance = new DenseInstance(numAtts); // Copy over the values into the Instance for (int j = 0; j < numAtts; j++) newInstance.setValue(j, gradients[j]); // Set the class value if (inst.classIndex() >= 0) newInstance.setValue(newInstance.numAttributes() - 1, inst.classValue()); return newInstance; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i =0; for(TimeSeries ts : inst){ checkParameters(ts.getSeriesLength()); out[i++] = getGradients(ts.toValueArray()); } return new TimeSeriesInstance(out, inst.getLabelIndex()); } /** * Private function for getting the gradients of a time series. * * @param inst - the time series to be transformed. * @return the transformed inst. */ private double[] getGradients(double[] inst) { double[] gradients = new double[this.numIntervals]; // Split inst into intervals double[][] intervals = getIntervals(inst); // perform least squares regression on each interval for (int i = 0; i < intervals.length; i++) { gradients[i] = getGradient(intervals[i]); } return gradients; } /** * Private function for splitting a time series into approximately equal * intervals. * * @param inst * @return */ private double[][] getIntervals(double[] inst) { int numElementsRemaining = inst.length; int numIntervalsRemaining = this.numIntervals; int startIndex = 0; double[][] intervals = new double[this.numIntervals][]; for (int i = 0; i < this.numIntervals; i++) { int intervalSize = (int) Math.ceil(numElementsRemaining / numIntervalsRemaining); double[] interval = Arrays.copyOfRange(inst, startIndex, startIndex + intervalSize); intervals[i] = interval; numElementsRemaining -= intervalSize; numIntervalsRemaining--; startIndex = startIndex + intervalSize; } return intervals; } /** * Private method to calculate the gradient of a given interval. * * @param y - an interval. * @return */ private double getGradient(double[] y) { double[] x = new double[y.length]; for (int i = 1; i <= y.length; i++) { x[i - 1] = i; } double meanX = calculateMean(x); double meanY = calculateMean(y); // Calculate w which is given as: // w = sum((y-meanY)^2) - sum((x-meanX)^2) double ySquaredDiff = 0.0; for (int i = 0; i < y.length; i++) { ySquaredDiff += Math.pow(y[i] - meanY, 2); } double xSquaredDiff = 0.0; for (int i = 0; i < y.length; i++) { xSquaredDiff += Math.pow(x[i] - meanX, 2); } double w = ySquaredDiff - xSquaredDiff; // Calculate r which is given as: // r = 2*sum((x-meanX)(y-meanY)) double xyDiff = 0.0; for (int i = 0; i < y.length; i++) { xyDiff += (x[i] - meanX) * (y[i] - meanY); } double r = 2 * xyDiff; // The gradient of the least squares regression line. // remove NaNs double m; if (r == 0) { m = 0; } else { m = (w + Math.sqrt(Math.pow(w, 2) + Math.pow(r, 2))) / r; } return m; } /** * Private method for calculating the mean of an array. * * @param arr * @return */ private double calculateMean(double[] arr) { double sum = 0.0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum / (double) arr.length; } @Override public Instances determineOutputFormat(Instances inputFormat) throws IllegalArgumentException { // If the class index exists. if (inputFormat.classIndex() >= 0) { if (inputFormat.classIndex() != inputFormat.numAttributes() - 1) { throw new IllegalArgumentException("cannot handle class values not at end"); } } ArrayList<Attribute> attributes = new ArrayList<>(); // Create a list of attributes for (int i = 0; i < numIntervals; i++) { attributes.add(new Attribute("SlopeGradient_" + i)); } // Add the class attribute (if it exists) if (inputFormat.classIndex() >= 0) { attributes.add(inputFormat.classAttribute()); } Instances result = new Instances("Slope" + inputFormat.relationName(), attributes, inputFormat.numInstances()); // Set the class attribute (if it exists) if (inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } return result; } private void checkParameters(int timeSeriesLength) { if (this.numIntervals < 1) { throw new IllegalArgumentException("numIntervals must be greater than zero."); } if (this.numIntervals > timeSeriesLength) { throw new IllegalArgumentException("numIntervals cannot be longer than the time series length."); } } /** * Main class for testing. * * @param args */ public static void main(String[] args) { Instances data = createData(new double[] { 1, 2, 3, 4, 5 }); // test bad num_intervals (must be at least 1, cannot be higher than the time // series length) int[] badNumIntervals = new int[] { 0, -5, 6 }; for (int badNumInterval : badNumIntervals) { try { Slope s = new Slope(badNumInterval); s.transform(data); System.out.println("Test failed."); } catch (IllegalArgumentException e) { System.out.println("Test passed."); } } // test good num_levels int[] goodNumIntervals = new int[] { 5, 3, 1 }; for (int goodNumInterval : goodNumIntervals) { try { Slope s = new Slope(goodNumInterval); s.transform(data); System.out.println("Test passed."); } catch (IllegalArgumentException e) { System.out.println("Test failed."); } } // test output of transformer Instances test = createData(new double[] { 4, 6, 10, 12, 8, 6, 5, 5 }); Slope s = new Slope(2); Instances res = s.transform(test); double[] resArr = res.get(0).toDoubleArray(); System.out.println( Arrays.equals(resArr, new double[] { (5.0 + Math.sqrt(41)) / 4.0, (1.0 + Math.sqrt(101)) / -10.0 })); test = createData(new double[] { -5, 2.5, 1, 3, 10, -1.5, 6, 12, -3, 0.2 }); res = s.transform(test); resArr = res.get(0).toDoubleArray(); // This is the correct output, but difficult to test if floating point numbers // are exactly correct. } /** * Function to create data for testing purposes. * * @return */ private static Instances createData(double[] data) { // Create the attributes ArrayList<Attribute> atts = new ArrayList<>(); for (int i = 0; i < data.length; i++) { atts.add(new Attribute("test_" + i)); } Instances newInsts = new Instances("Test_dataset", atts, 1); // create the test data createInst(data, newInsts); return newInsts; } /** * private function for creating an instance from a double array. Used for * testing purposes. * * @param arr * @return */ private static void createInst(double[] arr, Instances dataset) { Instance inst = new DenseInstance(arr.length); for (int i = 0; i < arr.length; i++) { inst.setValue(i, arr[i]); } inst.setDataset(dataset); dataset.add(inst); } }
10,752
33.687097
119
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Spectrogram.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.transform.DftNormalization; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import utilities.multivariate_tools.MultivariateInstanceTools; import weka.core.*; import static experiments.data.DatasetLoading.loadDataNullable; import java.util.ArrayList; import java.util.List; public class Spectrogram implements Transformer { private int nfft = 256; private int windowLength = 75; private int overlap = 70; public Spectrogram() { } public Spectrogram(int windowLength, int overlap, int nfft) { this.windowLength = windowLength; this.overlap = overlap; this.nfft = nfft; } public void setNFFT(int x) { nfft = x; } public int getNFFT() { return nfft; } public void setWindowLength(int x) { windowLength = x; } public void setOverlap(int x) { overlap = x; } public String globalInfo() { return null; } public Instances determineOutputFormat(Instances inputFormat) { Instances instances = null; FastVector<Attribute> attributes = new FastVector<>(nfft / 2); for (int i = 0; i < (nfft / 2); i++) { attributes.addElement(new Attribute("Spec_att" + String.valueOf(i + 1))); } attributes.addElement(inputFormat.attribute(inputFormat.numAttributes() - 1)); instances = new Instances("", attributes, 0); instances.setClassIndex(instances.numAttributes() - 1); return instances; } @Override public Instance transform(Instance inst) { /* * double[] signal = new double[instances.get(i).numAttributes() - 1]; * * for (int j = 0; j < instances.get(i).numAttributes() - 1; j++) { signal[j] = * instances.get(i).value(j); } double[][] spectrogram = spectrogram(signal, * windowLength, overlap, nfft); Instances spectrogramsInstances = * MatrixToInstances(spectrogram, instances.classAttribute(), * instances.get(i).classValue()); return null; */ // TODO: Not sure on how to convert this for a single instance. throw new NotImplementedException("This is not implemented for single transformation"); } public Instances transform(Instances instances) { double[][] spectrogram = null; Instances[] spectrogramsInstances = new Instances[instances.numInstances()]; double[] signal = null; for (int i = 0; i < instances.size(); i++) { signal = new double[instances.get(i).numAttributes() - 1]; for (int j = 0; j < instances.get(i).numAttributes() - 1; j++) { signal[j] = instances.get(i).value(j); } spectrogram = spectrogram(signal, windowLength, overlap, nfft); spectrogramsInstances[i] = MatrixToInstances(spectrogram, instances.classAttribute(), instances.get(i).classValue()); } // Rearrange data Instances[] temp = new Instances[spectrogramsInstances[0].size()]; for (int i = 0; i < temp.length; i++) { temp[i] = new Instances(spectrogramsInstances[0], 0); for (int j = 0; j < spectrogramsInstances.length; j++) { temp[i].add(spectrogramsInstances[j].get(i)); } } return MultivariateInstanceTools.concatinateInstances(temp); } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { List<TimeSeries> out = new ArrayList<>(); for (TimeSeries ts : inst) { double[] signal = ts.toValueArray(); double [][] spectrogram = spectrogram(signal, windowLength, overlap, nfft); for(double[] spec : spectrogram){ out.add(new TimeSeries(spec)); } } return new TimeSeriesInstance(inst.getLabelIndex(), out); } public int getNumWindows(int signalLength) { return (int) Math.floor((signalLength - overlap) / (windowLength - overlap)); } private void checkParameters(int signalLength) { windowLength = windowLength < (int) (signalLength * 0.5) ? windowLength : (int) (signalLength * 0.5); overlap = overlap < (int) (windowLength * 0.5) ? overlap : (windowLength / 2); } public double[][] spectrogram(double[] signal, int windowWidth, int overlap, int nfft) { checkParameters(signal.length); int numWindows = getNumWindows(signal.length); FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); double[][] spectrogram = new double[numWindows][nfft / 2]; Complex[] STFFT = null; for (int i = 0; i < numWindows; i++) { STFFT = new Complex[nfft]; for (int j = 0; j < nfft; j++) { STFFT[j] = new Complex(0.0, 0.0); } for (int j = 0; j < windowLength; j++) { double temp = signal[j + (i * (this.windowLength - this.overlap))] * (0.56 - 0.46 * Math.cos(2 * Math.PI * ((double) j / (double) this.windowLength))); STFFT[j] = new Complex(temp, 0.0); } STFFT = fft.transform(STFFT, TransformType.FORWARD); for (int j = 0; j < nfft / 2; j++) { spectrogram[i][j] = STFFT[j].abs(); } } return spectrogram; } private Instances MatrixToInstances(double[][] data, Attribute classAttribute, double classValue) { Instances instances = null; FastVector<Attribute> attributes = new FastVector<>(data[0].length); for (int i = 0; i < data[0].length; i++) { attributes.addElement(new Attribute("attr" + String.valueOf(i + 1))); } attributes.addElement(classAttribute); instances = new Instances("", attributes, data.length); double[] temp = null; for (int i = 0; i < data.length; i++) { temp = new double[instances.numAttributes()]; for (int j = 0; j < data[i].length; j++) { temp[j] = data[i][j]; } temp[temp.length - 1] = classValue; instances.add(new DenseInstance(1.0, temp)); } instances.setClassIndex(instances.numAttributes() - 1); return instances; } public static void main(String[] args) { Spectrogram spec = new Spectrogram(75, 70, 256); Instances[] data = new Instances[2]; data[0] = loadDataNullable(args[0] + args[1] + "/" + args[1] + "_TRAIN.arff"); data[1] = loadDataNullable(args[0] + args[1] + "/" + args[1] + "_TEST.arff"); System.out.println(data[0].get(0).toString()); data[1] = spec.transform(data[0]); System.out.println(); for (int i = 0; i < data[1].size(); i++) { Instance[] temp = MultivariateInstanceTools.splitMultivariateInstanceWithClassVal(data[1].get(i)); System.out.println(temp[0]); } System.out.println(); System.out.println("Signal length:" + (data[0].numAttributes() - 1)); System.out.println("Window length: " + spec.windowLength); System.out.println("Overlap: " + spec.overlap); System.out.println("NFFT: " + spec.nfft); } }
8,374
35.894273
110
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Subsequences.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import java.util.ArrayList; import java.util.Arrays; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.utilities.TimeSeriesSummaryStatistics; /** * This class is used to extract subsequences (default length = 30) of a time * series by extracting neighbouring data points about each data point. For * example, if a time series has data points 1,2,3,4,5 and subsequenceLength is * 3, This transformer would produce the following output: * * {{1,1,2},{1,2,3},{2,3,4},{3,4,5},{4,5,5}} * * Used mainly by ShapeDTW1NN. * */ public class Subsequences implements Transformer { private int subsequenceLength; private Instances relationalHeader; private boolean normalise = true; public Subsequences() {this.subsequenceLength = 30;} public Subsequences(int subsequenceLength) { this.subsequenceLength = subsequenceLength; } public void setNormalise(boolean normalise) {this.normalise = normalise;} public boolean getNormalise() {return normalise;} @Override public Instance transform(Instance inst) { double[] timeSeries = inst.toDoubleArray(); checkParameters(); // remove class label double[] temp; int c = inst.classIndex(); if (inst.classIndex() > 0) { temp = new double[timeSeries.length - 1]; System.arraycopy(timeSeries, 0, temp, 0, c); // assumes class attribute is in last index timeSeries = temp; } // Normalise the time series double[] temp2; if (normalise) { temp2 = new double[timeSeries.length]; System.arraycopy(timeSeries, 0, temp2, 0, timeSeries.length - 1); double mean = calculateMean(temp2); double sd = calculateSD(temp2, mean); timeSeries = normaliseArray(temp2, mean, sd); } // Extract the subsequences. double[][] subsequences = extractSubsequences(timeSeries); // Create the instance - contains only 2 attributes, the relation and the class // value. Instance newInstance = new DenseInstance(2); // Create the relation object. Instances relation = createRelation(timeSeries.length); // Add the subsequences to the relation object for (double[] list : subsequences) { Instance newSubsequence = new DenseInstance(1.0, list); relation.add(newSubsequence); } // set the dataset for the newInstance newInstance.setDataset(this.relationalHeader); // Add the relation to the first attribute. int index = newInstance.attribute(0).addRelation(relation); newInstance.setValue(0, index); // Add the class value newInstance.setValue(1, inst.classValue()); return newInstance; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i =0; for(TimeSeries ts : inst){ // Extract the subsequences. double[][] subsequences = extractSubsequences(TimeSeriesSummaryStatistics.standardNorm(ts).toValueArray()); //stack subsequences if we're multivariate. for(double[] d : subsequences) out[i++] = d; } return new TimeSeriesInstance(out, inst.getLabelIndex()); } /** * Method to extract all subsequences given a time series. * * @param timeSeries - the time series to transform. * @return a 2D array of subsequences. */ private double[][] extractSubsequences(double[] timeSeries) { int padAmount = (int) Math.floor(subsequenceLength / 2); double[] paddedTimeSeries = padTimeSeries(timeSeries, padAmount); double[][] subsequences = new double[timeSeries.length][subsequenceLength]; for (int i = 0; i < timeSeries.length; i++) { subsequences[i] = Arrays.copyOfRange(paddedTimeSeries, i, i + subsequenceLength); } return subsequences; } /** * Private method for padding the time series on either end by padAmount times. * The beginning is padded by the first value of the time series and the end is * padded by the last element in the time series. * * @param timeSeries * @param padAmount * @return */ private double[] padTimeSeries(double[] timeSeries, int padAmount) { double[] newTimeSeries = new double[timeSeries.length + padAmount * 2]; double valueToAdd; for (int i = 0; i < newTimeSeries.length; i++) { // Add the first element if (i < padAmount) { valueToAdd = timeSeries[0]; } else if (i >= padAmount && i < (padAmount + timeSeries.length)) { // Add the original time series element valueToAdd = timeSeries[i - padAmount]; } else { // Add the last element valueToAdd = timeSeries[timeSeries.length - 1]; } newTimeSeries[i] = valueToAdd; } return newTimeSeries; } @Override public Instances determineOutputFormat(Instances inputFormat) throws IllegalArgumentException { if (inputFormat.classIndex() != inputFormat.numAttributes() - 1) { throw new IllegalArgumentException("cannot handle class values not at end"); } // Set up instances size and format. // Create the relation. Instances relation = createRelation(inputFormat.numAttributes() - 1); // Create an arraylist of 2 containing the relational attribute and the class // label. ArrayList<Attribute> newAtts = new ArrayList<>(); newAtts.add(new Attribute("relationalAtt", relation)); newAtts.add(inputFormat.classAttribute()); // Put them into a new Instances object. Instances newFormat = new Instances("Subsequences", newAtts, inputFormat.numInstances()); newFormat.setRelationName("Subsequences_" + inputFormat.relationName()); newFormat.setClassIndex(newFormat.numAttributes() - 1); this.relationalHeader = newFormat; return newFormat; } /** * Private function to calculate the mean of an array. * * @param arr * @return */ private double calculateMean(double[] arr) { double sum = 0.0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum / (double) arr.length; } /** * Private function to calculate the standard deviation of an array. * * @param arr * @return */ private double calculateSD(double[] arr, double mean) { double sum = 0.0; for (int i = 0; i < arr.length; i++) { sum += Math.pow(arr[i] - mean, 2); } sum = sum / (double) arr.length; return Math.sqrt(sum); } /** * Private function for normalising an array. * * @param arr * @param mean * @param sd * @return */ private double[] normaliseArray(double[] arr, double mean, double sd) { double[] normalisedArray = new double[arr.length]; for (int i = 0; i < arr.length; i++) { normalisedArray[i] = (arr[i] - mean) / sd; } return normalisedArray; } /** * Private method for creating the relation as it always has the same dimensions * - numAtts() = subsequenceLength and numInsts() = timeSeriesLength. * * @return */ private Instances createRelation(int timeSeriesLength) { ArrayList<Attribute> attributes = new ArrayList<>(); // Add the original elements for (int i = 0; i < this.subsequenceLength; i++) attributes.add(new Attribute("Subsequence_element_" + i)); // Number of instances is equal to the length of the time series (as that's the // number of // subsequences you extract) Instances relation = new Instances("Subsequences", attributes, timeSeriesLength); return relation; } private void checkParameters() { if (this.subsequenceLength < 1) { throw new IllegalArgumentException("subsequenceLength cannot be less than 1."); } } public static void main(String[] args) { Instances data = createData(); // test bad SubsequenceLength // has to be greater than 0. int[] badSubsequenceLengths = new int[] { -1, 0, -99999999 }; for (int badSubsequenceLength : badSubsequenceLengths) { try { Subsequences s = new Subsequences(badSubsequenceLength); s.transform(data); System.out.println("Test failed."); } catch (IllegalArgumentException e) { System.out.println("Test passed."); } } // test good SubsequenceLength int[] goodSubsequenceLengths = new int[] { 1, 50, 999 }; for (int goodSubsequenceLength : goodSubsequenceLengths) { try { Subsequences s = new Subsequences(goodSubsequenceLength); s.transform(data); System.out.println("Test passed."); } catch (IllegalArgumentException e) { System.out.println("Test failed."); } } // check output Subsequences s = new Subsequences(5); Instances res = s.transform(data); Instances inst = res.get(0).relationalValue(0); double[] resArr = inst.get(0).toDoubleArray(); System.out.println(Arrays.equals(resArr, new double[] { 1, 1, 1, 2, 3 })); resArr = inst.get(1).toDoubleArray(); System.out.println(Arrays.equals(resArr, new double[] { 1, 1, 2, 3, 4 })); resArr = inst.get(2).toDoubleArray(); System.out.println(Arrays.equals(resArr, new double[] { 1, 2, 3, 4, 5 })); resArr = inst.get(3).toDoubleArray(); System.out.println(Arrays.equals(resArr, new double[] { 2, 3, 4, 5, 5 })); resArr = inst.get(4).toDoubleArray(); System.out.println(Arrays.equals(resArr, new double[] { 3, 4, 5, 5, 5 })); } /** * Function to create data for testing purposes. * * @return */ private static Instances createData() { // Create the attributes ArrayList<Attribute> atts = new ArrayList<>(); for (int i = 0; i < 5; i++) { atts.add(new Attribute("test_" + i)); } // Create the class values ArrayList<String> classes = new ArrayList<>(); classes.add("1"); classes.add("0"); atts.add(new Attribute("class", classes)); Instances newInsts = new Instances("Test_dataset", atts, 5); newInsts.setClassIndex(newInsts.numAttributes() - 1); // create the test data double[] test = new double[] { 1, 2, 3, 4, 5 }; createInst(test, "1", newInsts); test = new double[] { 1, 1, 2, 3, 4 }; createInst(test, "1", newInsts); test = new double[] { 2, 2, 2, 3, 4 }; createInst(test, "0", newInsts); test = new double[] { 2, 3, 4, 5, 6 }; createInst(test, "0", newInsts); test = new double[] { 0, 1, 1, 1, 2 }; createInst(test, "1", newInsts); return newInsts; } /** * private function for creating an instance from a double array. Used for * testing purposes. * * @param arr * @return */ private static void createInst(double[] arr, String classValue, Instances dataset) { Instance inst = new DenseInstance(arr.length + 1); for (int i = 0; i < arr.length; i++) { inst.setValue(i, arr[i]); } inst.setDataset(dataset); inst.setClassValue(classValue); dataset.add(inst); } }
12,868
36.301449
119
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/SummaryStats.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import experiments.data.DatasetLoading; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.utilities.TimeSeriesSummaryStatistics; import utilities.InstanceTools; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.filters.Filter; import weka.filters.SimpleBatchFilter; import java.io.File; import java.io.IOException; import java.util.ArrayList; /* simple Filter that just summarises the series * copyright: Anthony Bagnall * Global stats: * mean, variance, skewness, kurtosis, slope, min, max * */ public class SummaryStats implements Transformer { private int numMoments; private final String[] moment_names = { "mean", "variance", "skewness", "kurtosis", "slope", "min", "max" }; public SummaryStats() { this(5); } public SummaryStats(int numM) { numMoments = Math.max(Math.min(numM, 5), 0); // no less than 0 } public Instances determineOutputFormat(Instances inputFormat) { // Set up instances size and format. ArrayList<Attribute> atts = new ArrayList<>(); String source = inputFormat.relationName(); String name; for (int i = 0; i < moment_names.length; i++) { name = source + "Moment_" + moment_names[i]; atts.add(new Attribute(name)); } if (inputFormat.classIndex() >= 0) { // Classification set, set class // Get the class values as a fast vector Attribute target = inputFormat.attribute(inputFormat.classIndex()); ArrayList<String> vals = new ArrayList<>(target.numValues()); for (int i = 0; i < target.numValues(); i++) vals.add(target.value(i)); atts.add(new Attribute(inputFormat.attribute(inputFormat.classIndex()).name(), vals)); } Instances result = new Instances("Moments" + inputFormat.relationName(), atts, inputFormat.numInstances()); if (inputFormat.classIndex() >= 0) { result.setClassIndex(result.numAttributes() - 1); } return result; } @Override public Instance transform(Instance inst) { // 1. Get series: double[] d = InstanceTools.ConvertInstanceToArrayRemovingClassValue(inst); double[] moments = new double[numMoments + 2]; double max = InstanceTools.max(inst); double min = InstanceTools.min(inst); double sum = InstanceTools.sum(inst); double sumSq = InstanceTools.sumSq(inst); moments[0] = sum / d.length; double totalVar = 0; double totalSkew = 0; double totalKur = 0; double p = 0; // Find variance if (numMoments > 0) { for (int j = 0; j < d.length; j++) { p = (d[j] - moments[0]) * (d[j] - moments[0]); // ^2 totalVar += p; p *= (d[j] - moments[0]); // ^3 totalSkew += p; p *= (d[j] - moments[0]); // ^4 totalKur += p; } moments[1] = totalVar / (d.length - 1); double standardDeviation = Math.sqrt(moments[1]); moments[1] = standardDeviation; if (numMoments > 1) { double std3 = Math.pow(standardDeviation, 3); double skew = totalSkew / (std3); moments[2] = skew / d.length; if (numMoments > 2) { double kur = totalKur / (std3 * standardDeviation); moments[3] = kur / d.length; if (numMoments > 3) { // slope moments[4] = standardDeviation != 0 ? InstanceTools.slope(inst, sum, sumSq) : 0; } } } } double[] atts = new double[numMoments + 2 + (inst.classIndex() >= 0 ? 1 : 0)]; for (int j = 0; j < numMoments; j++) { atts[j] = moments[j]; } atts[numMoments] = min; atts[numMoments + 1] = max; if (inst.classIndex() >= 0) atts[atts.length - 1] = inst.classValue(); return new DenseInstance(1.0, atts); } public static void main(String[] args) throws IOException { String localPath = "src/main/java/experiments/data/tsc/"; // path for testing. String datasetName = "ChinaTown"; Instances train = DatasetLoading.loadData(localPath + datasetName + File.separator + datasetName+"_TRAIN.ts"); Instances test = DatasetLoading.loadData(localPath + datasetName + File.separator + datasetName+"_TEST.ts"); // Instances filter=new SummaryStats().process(test); SummaryStats m = new SummaryStats(); Instances filter = m.transform(test); System.out.println(filter); } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { double[][] out = new double[inst.getNumDimensions()][]; int i=0; for(TimeSeries ts : inst){ TimeSeriesSummaryStatistics stats = new TimeSeriesSummaryStatistics(ts); //{ "mean", "variance", "skewness", "kurtosis", "slope", "min", "max" }; int j=0; out[i] = new double[numMoments + 2]; if (numMoments >= 0){ out[i][j++] = stats.getMean(); if (numMoments >= 1){ out[i][j++] = stats.getVariance(); if (numMoments >= 2){ out[i][j++] = stats.getSkew(); if (numMoments >= 3){ out[i][j++] = stats.getKurtosis(); if (numMoments >= 4){ out[i][j++] = stats.getSlope(); } } } } } out[i][j++] = stats.getMin(); out[i][j++] = stats.getMax(); i++; } return new TimeSeriesInstance(out, inst.getLabelIndex()); } }
6,923
35.634921
118
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/TrainableTransformer.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import tsml.data_containers.TimeSeriesInstances; import tsml.data_containers.utilities.Converter; import weka.core.Instances; /** * Interface for time series transformers that require training, extending Transformer interface, * which does not require a fit stage * * @author Aaron Bostrom, Tony Bagnall * */ public interface TrainableTransformer extends Transformer { /** * @return true if the the training (fitting) has already happened */ boolean isFit(); /********* Instances ************/ /** * Build the transform model from train data, storing the necessary info internally. * @param data */ void fit(Instances data); /** * * @param data * @return */ default Instances fitTransform(Instances data){ fit(data); return transform(data); } default TimeSeriesInstances fitTransformConverter(Instances data){ return Converter.fromArff(fitTransform(data)); } /** * main transform method. This automatically fits the model if it has not already been fit * it effectively implements fitAndTransform. The assumption is that if a Transformer is Trainable, * it is not usable until it has been trained/fit * @param data * @return */ @Override default Instances transform(Instances data){ if(!isFit()) fit(data); return Transformer.super.transform(data); } /********* TimeSeriesInstances ************/ /** * Build the transform model from train data, storing the necessary info internally. * @param data */ void fit(TimeSeriesInstances data); /** * * @param data * @return */ default TimeSeriesInstances fitTransform(TimeSeriesInstances data){ fit(data); return transform(data); } default Instances fitTransformConverter(TimeSeriesInstances data){ return fitTransform(Converter.toArff(data)); } /** * main transform method. This automatically fits the model if it has not already been fit * it effectively implements fitAndTransform. The assumption is that if a Transformer is Trainable, * it is not usable until it has been trained/fit * @param data * @return */ @Override default TimeSeriesInstances transform(TimeSeriesInstances data){ if(!isFit()) fit(data); return Transformer.super.transform(data); } }
3,275
27.486957
103
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/TransformPipeline.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import org.junit.Assert; import scala.collection.mutable.StringBuilder$; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import weka.core.Instances; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TransformPipeline extends BaseTrainableTransformer { private List<Transformer> transformers; public TransformPipeline() { this(new ArrayList<>()); } public TransformPipeline(List<Transformer> transformers) { setTransformers(transformers); } public TransformPipeline(Transformer... transformers) { this(new ArrayList<>(Arrays.asList(transformers))); } public List<Transformer> getTransformers() { return transformers; } public void setTransformers(final List<Transformer> transformers) { Assert.assertNotNull(transformers); this.transformers = transformers; } public void fit(TimeSeriesInstances data) { super.fit(data); int lastFitIndex = 0; // the index of the transformer last fitted for(int i = 0; i < transformers.size(); i++) { final Transformer transformer = transformers.get(i); if(transformer instanceof TrainableTransformer) { // in order to fit the transformer, we need to transform the data up to the point of the fittable // transformer // so transform the data from the previous transform up to this transformer for(int j = lastFitIndex; j < i; j++) { final Transformer previous = transformers.get(j); // replace the data with the data from applying a previous transform data = previous.transform(data); } // this is now the most recently fit transformer in the pipeline lastFitIndex = i; } } } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { for(Transformer transformer : transformers) { inst = transformer.transform(inst); } return inst; } @Override public Instances determineOutputFormat(Instances data) throws IllegalArgumentException { for (Transformer transformer : transformers) { data = transformer.determineOutputFormat(data); } return data; } public boolean add(Transformer transformer) { return transformers.add(transformer); } /** * * @param a the transformer to append to. If this is already a pipeline * transformer then b is added to the list of transformers. If not, a * new pipeline transformer is created and a and b are added to the * list of transformers (in that order!). * @param b * @return */ public static Transformer add(Transformer a, Transformer b) { if (a == null) { return b; } if (b == null) { return a; } if (a instanceof TransformPipeline) { ((TransformPipeline) a).add(b); return a; } else { return new TransformPipeline(a, b); } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); for(int i = 0; i < transformers.size() - 1; i++) { final Transformer transformer = transformers.get(i); sb.append(transformer); sb.append("_"); } sb.append(transformers.get(transformers.size() - 1)); return sb.toString(); } }
4,446
32.946565
113
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Transformer.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import java.io.Serializable; import tsml.classifiers.distance_based.utils.collections.params.ParamHandler; import tsml.data_containers.TSCapabilities; import tsml.data_containers.TSCapabilitiesHandler; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.data_containers.utilities.Converter; import weka.core.Capabilities; import weka.core.CapabilitiesHandler; import weka.core.Instance; import weka.core.Instances; /** * Interface for time series transformers. * * Previously, we have used weka filters for time series transforms. This redesign * is to make our code more like sktime and reduce our Weka dependency. The Filter * mechanism has some down sides * * Ultimately this will include the new data model * * @author Tony Bagnall 1/1/2020, Aaron Bostrom * */ public interface Transformer extends TSCapabilitiesHandler, ParamHandler, Serializable { /********* Instances ************/ /** * perform the transform process. Some algorithms may require a fit before transform * (e.g. shapelets, PCA) others may not (FFT, PAA etc). * Should we throw an exception? Default to calling instance transform? * Need to determine where to setOut * @return Instances of transformed data */ default Instances transform(Instances data){ Instances output = determineOutputFormat(data); for(Instance inst : data){ output.add(transform(inst)); } return output; } default TimeSeriesInstances transformConverter(Instances data){ return transform(Converter.fromArff(data)); } /** * Transform a new instance into the format described in determineOutputFormat * @param Instance inst * @return transformed Instance */ default Instance transform(Instance inst){ throw new UnsupportedOperationException("Legacy: In general this function should be used or implemented."); } /** * Method that constructs a holding Instances for transformed data, without doing the transform * @param Instances data to derive the format from * @return empty Instances to hold transformed Instance objects * @throws IllegalArgumentException */ Instances determineOutputFormat(Instances data) throws IllegalArgumentException; /** * setOptions can be implemented and used in the Tuning mechanism that classifiers employ. * It does not have to be implemented though, so there is a default method that throws an exception * if it is called * @param String array of options that should be in the format of flag,value * @throws Exception */ default void setOptions(String[] options) throws Exception{ throw new UnsupportedOperationException("calling default method of setOptions in Transformer interface, it has not been implemented for class "+this.getClass().getSimpleName()); } /** * getCapabilities determines what type of data this Transformer can handle. Default is * all numeric attributes, nominal class, no missing values * @return */ default TSCapabilities getTSCapabilities(){ TSCapabilities result = new TSCapabilities(this); result.enable(TSCapabilities.EQUAL_LENGTH) .enable(TSCapabilities.MULTI_OR_UNIVARIATE) .enable(TSCapabilities.NO_MISSING_VALUES); return result; } /********* TimeSeriesInstances ************/ /** * perform the transform process. Some algorithms may require a fit before transform * (e.g. shapelets, PCA) others may not (FFT, PAA etc). * Should we throw an exception? Default to calling instance transform? * Need to determine where to setOut * @return Instances of transformed data */ default TimeSeriesInstances transform(TimeSeriesInstances data){ //when cloning skeleton of TSInstances, copy across classLabels. TimeSeriesInstances output = new TimeSeriesInstances(data.getClassLabels()); for(TimeSeriesInstance inst : data){ output.add(transform(inst)); } return output; } default Instances transformConverter(TimeSeriesInstances data){ return Converter.toArff(transform(data)); } /** * Transform a new instance into the format described in determineOutputFormat * @param Instance inst * @return transformed Instance */ TimeSeriesInstance transform(TimeSeriesInstance inst); }
5,307
36.380282
185
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/Truncator.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers; import experiments.data.DatasetLists; import experiments.data.DatasetLoading; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import weka.core.Instance; import weka.core.Instances; import java.io.IOException; import java.util.ArrayList; import java.util.stream.IntStream; /** * Class to truncate series to make them all equal length. In Weka unequal length series are padded with missing values * to avoid ragged arrays. This class removes observations from the series to make them all as short as the shortest in * the train data This may have involved some prior preprocessing. * there is an edge case where the shortest in the test data is shorter than the shortest in the Train data. In this scenario * the solution is to pad the particular test series with this characteristic. * Assumptions: * 1. Data loaded from ARFF format are already padded to be the same length for Train and Test. * 2. All missing values at the end of a series are padding * * todo: implement univariate * todo: implement multivariate * todo: test inc edge cases * todo: decide on whether to clone or not * @author Tony Bagnall 1/1/2020 */ public class Truncator implements TrainableTransformer{ int shortestSeriesLength=Integer.MAX_VALUE; private boolean isFit; /** * Determine the length of the shortest series in the data * store internally in shortestSeriesLength * @param data: either univariate or multivariate time series classification problem */ @Override public void fit(Instances data) { if(data.attribute(0).isRelationValued()) { //Multivariate for(Instance ins:data){ Instances d=ins.relationalValue(0); for(Instance internal:d){ int l=findLength(internal,false); if (l < shortestSeriesLength) shortestSeriesLength = l; } } } else{ for(Instance ins:data) { int l = findLength(ins, true); if (l < shortestSeriesLength) shortestSeriesLength = l; } } isFit = true; } /** * Shortens * @param data * @return */ @Override public Instances transform(Instances data) { if(data.attribute(0).isRelationValued()) { //Multivariate for(Instance ins:data){ while (ins.numAttributes() > shortestSeriesLength) ins.deleteAttributeAt(ins.numAttributes() ); } } else { while (data.numAttributes() - 2 >= shortestSeriesLength) data.deleteAttributeAt(data.numAttributes() - 2); } return data; } @Override public Instance transform(Instance ins) { if(ins.attribute(0).isRelationValued()) { //Multivariate while (ins.numAttributes() > shortestSeriesLength) ins.deleteAttributeAt(ins.numAttributes() ); } else { while (ins.numAttributes() - 1 > shortestSeriesLength) ins.deleteAttributeAt(ins.numAttributes() - 1); } return ins; } @Override public Instances determineOutputFormat(Instances data) throws IllegalArgumentException { throw new IllegalArgumentException(" determine Output Format is not implemented for Truncator, there is no need"); } public static void testTruncateUnivariateData(String problemPath) throws IOException { Instances train = DatasetLoading.loadData(problemPath+"AllGestureWiimoteX/AllGestureWiimoteX_TRAIN"); Instances test = DatasetLoading.loadData(problemPath+"AllGestureWiimoteX/AllGestureWiimoteX_TEST"); System.out.println(" Test on unequal length series AllGestureWiimoteX: Min series length should be 11 in train and 2 in test "); Truncator t = new Truncator(); t.fit(train); train=t.transform(train); test=t.transform(test); System.out.print("Num atts ="+train.numAttributes()+"\n Train instance 1 = "); double[] d= train.instance(0).toDoubleArray(); for(double x:d) System.out.print(x+","); System.out.print("\n"); String[] probs=DatasetLists.variableLengthUnivariate; System.out.print("Num atts ="+(test.numAttributes()-1)+"\n Test instance 1 = "); double[] d2= test.instance(0).toDoubleArray(); for(double x:d2) System.out.print(x+","); System.out.print("\n"); // String[] probs=DatasetLists.variableLengthUnivariate; } /** * find the length of the series ins by counting missing values from the end * @param ins * @param classValuePresent * @return */ public static int findLength(Instance ins, boolean classValuePresent){ int seriesLength = classValuePresent?ins.numAttributes()-2:ins.numAttributes()-1; while(seriesLength>0 && ins.isMissing(seriesLength)) seriesLength--; seriesLength++;//Correct for zero index return seriesLength; } public static int[] univariateSeriesLengths(String problemPath) throws IOException { String[] probs=DatasetLists.variableLengthUnivariate; System.out.println(" Total number of problesm = "+probs.length); int[][] minMax=new int[probs.length][4]; // String[] probs=DatasetLists.variableLength2018Problems; // String[] probs=new String[]{"AllGestureWiimoteX"}; // OutFile of=new OutFile(problemPath+"Unqu"); int count=0; for(String str:probs){ Instances train = DatasetLoading.loadData(problemPath+str+"/"+str+"_TRAIN"); Instances test = DatasetLoading.loadData(problemPath+str+"/"+str+"_TEST"); int min=Integer.MAX_VALUE; int max=0; for(Instance ins:train){ int length=findLength(ins,true); if(length>max) max=length; if(length<min) min=length; // System.out.println("Length ="+length+" last value = "+ins.value(length-1)+" one after = "+ins.value(length)); } if(min!=max) System.out.print(" PROBLEM "+str+"\t\tTRAIN MIN ="+min+"\t Max ="+max); minMax[count][0]=min; minMax[count][1]=max; min=Integer.MAX_VALUE; max=0; for(Instance ins:test){ int length=findLength(ins,true); if(length>max) max=length; if(length<min) min=length; // System.out.println("Length ="+length+" last value = "+ins.value(length-1)+" one after = "+ins.value(length)); } if(min!=max) System.out.println("\t"+str+"\t TEST MIN ="+min+"\t Max ="+max); minMax[count][2]=min; minMax[count][3]=max; count++; } for(int i=0;i<probs.length;i++){ System.out.println("{"+minMax[i][0]+","+minMax[i][1]+","+minMax[i][2]+","+minMax[i][3]+"},"); } return null; } public static int[] multivariateSeriesLengths(String problemPath) throws IOException { String[] probs=DatasetLists.variableLengthMultivariate; ArrayList<String> names=new ArrayList<>(); int[][] minMax=new int[probs.length][4]; System.out.println(" Total number of problems = "+probs.length); // String[] probs=DatasetLists.variableLength2018Problems; // String[] probs=new String[]{"AllGestureWiimoteX"}; // OutFile of=new OutFile(problemPath+"Unqu"); int count=0; for(String str:probs){ // System.out.print(" PROBLEM "+str); Instances train = DatasetLoading.loadData(problemPath+str+"/"+str+"_TRAIN"); Instances test = DatasetLoading.loadData(problemPath+str+"/"+str+"_TEST"); int min=Integer.MAX_VALUE; int max=0; for(Instance ins:train){ Instances cs=ins.relationalValue(0); for(Instance in:cs) { int length = findLength(in, true); if (length > max) max = length; if (length < min) min = length; } // System.out.println("Length ="+length+" last value = "+ins.value(length-1)+" one after = "+ins.value(length)); } if(min!=max) { System.out.print("\t\tTRAIN MIN =" + min + "\t Max =" + max); names.add(str); } minMax[count][0]=min; minMax[count][1]=max; min=Integer.MAX_VALUE; max=0; for(Instance ins:test){ Instances cs=ins.relationalValue(0); for(Instance in:cs) { int length = findLength(in, true); if (length > max) max = length; if (length < min) min = length; } } minMax[count][2]=min; minMax[count][3]=max; if(min!=max) System.out.println("\t"+str+"\t TEST MIN ="+min+"\t Max ="+max); count++; } for(String str:names) System.out.print("\""+str+"\","); for(int i=0;i<probs.length;i++){ System.out.println("{"+minMax[i][0]+","+minMax[i][1]+","+minMax[i][2]+","+minMax[i][3]+"},"); } return null; } public static void main(String[] args) throws IOException { String path = "src/main/java/experiments/data/tsc/"; // path for testing. String path2="src/main/java/experiments/data/mtsc/"; // String path="Z:\\ArchiveData\\Univariate_arff\\"; multivariateSeriesLengths(path2); // univariateSeriesLengths(path); System.exit(0); System.out.println(" Test 1, univariate data with padding"); testTruncateUnivariateData(path); System.exit(0); System.out.println(" Test 2, univariate data with no padding"); System.out.println(" Test 3, multivariate data with padding"); testTruncateUnivariateData(""); System.out.println(" Test 2, multivariate data with no padding"); } @Override public boolean isFit() { return isFit; } @Override public TimeSeriesInstance transform(TimeSeriesInstance inst) { return inst.getVSlice(IntStream.range(0, shortestSeriesLength).toArray()); } @Override public void fit(TimeSeriesInstances data) { shortestSeriesLength = data.getMinLength(); isFit = true; } }
11,683
37.308197
147
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/DefaultShapeletOptions.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import static tsml.transformers.shapelet_tools.ShapeletTransformTimingUtilities.nanoToOp; import tsml.filters.shapelet_filters.ShapeletFilter; import tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import static tsml.transformers.shapelet_tools.search_functions.ShapeletSearch.SearchType.FULL; import static tsml.transformers.shapelet_tools.search_functions.ShapeletSearch.SearchType.IMPROVED_RANDOM; import static tsml.transformers.shapelet_tools.search_functions.ShapeletSearch.SearchType.MAGNIFY; import static tsml.transformers.shapelet_tools.search_functions.ShapeletSearch.SearchType.TABU; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instances; import utilities.TriFunction; /** * * @author raj09hxu */ public class DefaultShapeletOptions { public static final Map<String, Function<Instances, ShapeletTransformFactoryOptions>> FACTORY_OPTIONS; static { Map<String, Function<Instances, ShapeletTransformFactoryOptions>> map = new HashMap(); map.put("INDEPENDENT", DefaultShapeletOptions::createIndependentShapeletSearch); map.put("SHAPELET_I", DefaultShapeletOptions::createSHAPELET_I); map.put("SHAPELET_D", DefaultShapeletOptions::createSHAPELET_D); FACTORY_OPTIONS = Collections.unmodifiableMap(map); } public static final Map<String, TriFunction<Instances, Long, Long, ShapeletTransformFactoryOptions>> TIMED_FACTORY_OPTIONS; static { Map<String, TriFunction<Instances, Long, Long, ShapeletTransformFactoryOptions>> map = new HashMap(); map.put("INDEPENDENT", DefaultShapeletOptions::createIndependentShapeletSearch_TIMED); map.put("SHAPELET_I", DefaultShapeletOptions::createSHAPELET_I_TIMED); map.put("SHAPELET_D", DefaultShapeletOptions::createSHAPELET_D_TIMED); map.put("SKIPPING", DefaultShapeletOptions::createSKIPPING_TIMED); map.put("TABU", DefaultShapeletOptions::createTABU_TIMED); map.put("RANDOM", DefaultShapeletOptions::createRANDOM_TIMED); map.put("MAGNIFY", DefaultShapeletOptions::createMAGNIFY_TIMED); TIMED_FACTORY_OPTIONS = Collections.unmodifiableMap(map); } /** * * When calculating the timing for the number of shapelets. * Its better to treat the timign as a univariate problem because in essence it is the same. * We just have more shapelets to consider, but calculating a single one is the same as unvariate times. * So the number we can calculate in a given time is the same. * * @param train * @param time * @param seed * @return */ public static ShapeletTransformFactoryOptions createIndependentShapeletSearch_TIMED(Instances train, long time, long seed){ int n = train.numInstances(); int m = utilities.multivariate_tools.MultivariateInstanceTools.channelLength(train); //create our search options. ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder(); searchBuilder.setMin(3); searchBuilder.setMax(m); searchBuilder.setSearchType(FULL); //default to FULL, if we need to sample will get overwrote. searchBuilder.setNumDimensions(utilities.multivariate_tools.MultivariateInstanceTools.numDimensions(train)); //clamp K to 2000. int K = n > 2000 ? 2000 : n; long numShapelets; //how much time do we have vs. how long our algorithm will take. BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp)); BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1); if(opCount.compareTo(opCountTarget) == 1){ System.out.println("initiate timed"); BigDecimal oct = new BigDecimal(opCountTarget); BigDecimal oc = new BigDecimal(opCount); BigDecimal prop = oct.divide(oc, MathContext.DECIMAL64); //if we've not set a shapelet count, calculate one, based on the time set. numShapelets = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(n,m,3,m); numShapelets *= prop.doubleValue(); //we need to find atleast one shapelet in every series. searchBuilder.setSeed(seed); searchBuilder.setSearchType(IMPROVED_RANDOM); searchBuilder.setNumShapeletsToEvaluate(numShapelets); // can't have more final shapelets than we actually search through. K = numShapelets > K ? K : (int) numShapelets; } ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setKShapelets(K) .setSearchOptions(searchBuilder.build()) .setDistanceType(ShapeletDistance.DistanceType.DIMENSION) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createSHAPELET_I_TIMED(Instances train, long time, long seed){ int n = train.numInstances(); int m = utilities.multivariate_tools.MultivariateInstanceTools.channelLength(train); //create our search options. ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder(); searchBuilder.setMin(3); searchBuilder.setMax(m); //clamp K to 2000. int K = n > 2000 ? 2000 : n; long numShapelets; //how much time do we have vs. how long our algorithm will take. BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp)); BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1); //multiple the total opCount by K becauise for each comparison we do across dimensions. opCount = opCount.multiply(BigInteger.valueOf(utilities.multivariate_tools.MultivariateInstanceTools.numDimensions(train))); if(opCount.compareTo(opCountTarget) == 1){ BigDecimal oct = new BigDecimal(opCountTarget); BigDecimal oc = new BigDecimal(opCount); BigDecimal prop = oct.divide(oc, MathContext.DECIMAL64); //if we've not set a shapelet count, calculate one, based on the time set. numShapelets = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(n,m,3,m); numShapelets *= prop.doubleValue(); //we need to find atleast one shapelet in every series. searchBuilder.setSeed(seed); searchBuilder.setSearchType(IMPROVED_RANDOM); searchBuilder.setNumShapeletsToEvaluate(numShapelets); // can't have more final shapelets than we actually search through. K = numShapelets > K ? K : (int) numShapelets; } ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setKShapelets(K) .setSearchOptions(searchBuilder.build()) .setDistanceType(ShapeletDistance.DistanceType.INDEPENDENT) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createSHAPELET_D_TIMED(Instances train, long time, long seed){ int n = train.numInstances(); int m = utilities.multivariate_tools.MultivariateInstanceTools.channelLength(train); //create our search options. ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder(); searchBuilder.setMin(3); searchBuilder.setMax(m); //clamp K to 2000. int K = n > 2000 ? 2000 : n; long numShapelets; //how much time do we have vs. how long our algorithm will take. BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp)); BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1); opCount = opCount.multiply(BigInteger.valueOf(utilities.multivariate_tools.MultivariateInstanceTools.numDimensions(train))); //multiple the total opCount by K becauise for each comparison we do across dimensions. if(opCount.compareTo(opCountTarget) == 1){ BigDecimal oct = new BigDecimal(opCountTarget); BigDecimal oc = new BigDecimal(opCount); BigDecimal prop = oct.divide(oc, MathContext.DECIMAL64); //if we've not set a shapelet count, calculate one, based on the time set. numShapelets = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(n,m,3,m); numShapelets *= prop.doubleValue(); //we need to find atleast one shapelet in every series. searchBuilder.setSeed(seed); searchBuilder.setSearchType(IMPROVED_RANDOM); searchBuilder.setNumShapeletsToEvaluate(numShapelets); // can't have more final shapelets than we actually search through. K = numShapelets > K ? K : (int) numShapelets; } ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setKShapelets(K) .setSearchOptions(searchBuilder.build()) .setDistanceType(ShapeletDistance.DistanceType.DEPENDENT) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createSKIPPING_TIMED(Instances train, long time, long seed){ int n = train.numInstances(); int m = train.numAttributes()-1; //create our search options. ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder(); searchBuilder.setMin(3); searchBuilder.setMax(m); //clamp K to 2000. int K = n > 2000 ? 2000 : n; //how much time do we have vs. how long our algorithm will take. BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp)); BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1); //multiple the total opCount by K becauise for each comparison we do across dimensions. if(opCount.compareTo(opCountTarget) == 1){ //we need to find atleast one shapelet in every series. searchBuilder.setSeed(seed); searchBuilder.setSearchType(FULL); //find skipping values. int i = 1; while(ShapeletTransformTimingUtilities.calc(n, m, 3, m, i, i) > opCountTarget.doubleValue()) i++; System.out.println(i); searchBuilder.setPosInc(i); searchBuilder.setLengthInc(i); } ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setKShapelets(K) .setSearchOptions(searchBuilder.build()) .setDistanceType(ShapeletDistance.DistanceType.CACHED) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createTABU_TIMED(Instances train, long time, long seed){ int n = train.numInstances(); int m = train.numAttributes()-1; //create our search options. ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder(); searchBuilder.setMin(3); searchBuilder.setMax(m); //clamp K to 2000. int K = n > 2000 ? 2000 : n; long numShapelets; //how much time do we have vs. how long our algorithm will take. BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp)); BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1); //multiple the total opCount by K becauise for each comparison we do across dimensions. if(opCount.compareTo(opCountTarget) == 1){ BigDecimal oct = new BigDecimal(opCountTarget); BigDecimal oc = new BigDecimal(opCount); BigDecimal prop = oct.divide(oc, MathContext.DECIMAL64); //if we've not set a shapelet count, calculate one, based on the time set. numShapelets = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(n,m,3,m); numShapelets *= prop.doubleValue(); //we need to find atleast one shapelet in every series. searchBuilder.setSeed(seed); searchBuilder.setSearchType(TABU); searchBuilder.setNumShapeletsToEvaluate(numShapelets); // can't have more final shapelets than we actually search through. K = numShapelets > K ? K : (int) numShapelets; } ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setKShapelets(K) .setSearchOptions(searchBuilder.build()) .setDistanceType(ShapeletDistance.DistanceType.CACHED) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createRANDOM_TIMED(Instances train, long time, long seed){ int n = train.numInstances(); int m = train.numAttributes()-1; //create our search options. ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder(); searchBuilder.setMin(3); searchBuilder.setMax(m); //clamp K to 2000. int K = n > 2000 ? 2000 : n; long numShapelets; //how much time do we have vs. how long our algorithm will take. BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp)); BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1); //multiple the total opCount by K becauise for each comparison we do across dimensions. if(opCount.compareTo(opCountTarget) == 1){ BigDecimal oct = new BigDecimal(opCountTarget); BigDecimal oc = new BigDecimal(opCount); BigDecimal prop = oct.divide(oc, MathContext.DECIMAL64); //if we've not set a shapelet count, calculate one, based on the time set. numShapelets = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(n,m,3,m); numShapelets *= prop.doubleValue(); //we need to find atleast one shapelet in every series. searchBuilder.setSeed(seed); searchBuilder.setSearchType(IMPROVED_RANDOM); searchBuilder.setNumShapeletsToEvaluate(numShapelets); // can't have more final shapelets than we actually search through. K = numShapelets > K ? K : (int) numShapelets; } ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setKShapelets(K) .setSearchOptions(searchBuilder.build()) .setDistanceType(ShapeletDistance.DistanceType.CACHED) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createMAGNIFY_TIMED(Instances train, long time, long seed){ int n = train.numInstances(); int m = train.numAttributes()-1; //create our search options. ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder(); searchBuilder.setMin(3); searchBuilder.setMax(m); //clamp K to 2000. int K = n > 2000 ? 2000 : n; long numShapelets; //how much time do we have vs. how long our algorithm will take. BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp)); BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1); //multiple the total opCount by K becauise for each comparison we do across dimensions. if(opCount.compareTo(opCountTarget) == 1){ BigDecimal oct = new BigDecimal(opCountTarget); BigDecimal oc = new BigDecimal(opCount); BigDecimal prop = oct.divide(oc, MathContext.DECIMAL64); //if we've not set a shapelet count, calculate one, based on the time set. numShapelets = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(n,m,3,m); numShapelets *= prop.doubleValue(); //we need to find atleast one shapelet in every series. searchBuilder.setSeed(seed); searchBuilder.setSearchType(MAGNIFY); searchBuilder.setNumShapeletsToEvaluate(numShapelets); // can't have more final shapelets than we actually search through. K = numShapelets > K ? K : (int) numShapelets; } ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setKShapelets(K) .setSearchOptions(searchBuilder.build()) .setDistanceType(ShapeletDistance.DistanceType.CACHED) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createIndependentShapeletSearch(Instances train){ ShapeletSearchOptions sOps = new ShapeletSearchOptions.Builder() .setMin(3) .setMax(utilities.multivariate_tools.MultivariateInstanceTools.channelLength(train)) .setSearchType(ShapeletSearch.SearchType.FULL) .setNumDimensions(utilities.multivariate_tools.MultivariateInstanceTools.numDimensions(train)) .build(); ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setSearchOptions(sOps) .setDistanceType(ShapeletDistance.DistanceType.DIMENSION) .setKShapelets(Math.min(2000,train.numInstances())) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createSHAPELET_I(Instances train){ ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setMinLength(3) .setMaxLength(utilities.multivariate_tools.MultivariateInstanceTools.channelLength(train)) .setDistanceType(ShapeletDistance.DistanceType.INDEPENDENT) .setKShapelets(Math.min(2000,train.numInstances())) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static ShapeletTransformFactoryOptions createSHAPELET_D(Instances train){ ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .setMinLength(3) .setMaxLength(utilities.multivariate_tools.MultivariateInstanceTools.channelLength(train)) .setDistanceType(ShapeletDistance.DistanceType.DEPENDENT) .setKShapelets(Math.min(2000,train.numInstances())) .useBinaryClassValue() .useClassBalancing() .useCandidatePruning() .build(); return options; } public static void main(String[] args){ Instances train = null; ShapeletTransformFactoryOptions options = TIMED_FACTORY_OPTIONS.get("RANDOM").apply(train, 100000l, 0l); ShapeletFilter st = new ShapeletTransformFactory(options).getFilter(); } }
23,992
50.267094
134
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/OrderLineObj.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools; import java.io.Serializable; /** * copyright: Anthony Bagnall * A simple class to store <distance,classValue> pairs for calculating the quality of a shapelet. */ public final class OrderLineObj implements Comparable<OrderLineObj>, Serializable { private double distance; private double classVal; /** * Constructor to build an orderline object with a given distance and class value * @param distance distance from the obj to the shapelet that is being assessed * @param classVal the class value of the object that is represented by this OrderLineObj */ public OrderLineObj(double distance, double classVal){ this.distance = distance; this.classVal = classVal; } /** * Accessor for the distance field * @return this OrderLineObj's distance */ public double getDistance(){ return this.distance; } /** * Accessor for the class value field of the object * @return this OrderLineObj's class value */ public double getClassVal(){ return this.classVal; } /** * Mutator for the distance field * @param distance new distance for this OrderLineObj */ public void setDistance(double distance){ this.distance = distance; } /** * Mutator for the class value field of the object * @param classVal new class value for this OrderLineObj */ public void setClassVal(double classVal){ this.classVal = classVal; } /** * Comparator for two OrderLineObj objects, used when sorting an orderline * @param o the comparison OrderLineObj * @return the order of this compared to o: -1 if less, 0 if even, and 1 if greater. */ @Override public int compareTo(OrderLineObj o) { // return distance - o.distance. compareTo doesnt care if its -1 or -inf. likewise +1 or +inf. if(o.distance > this.distance){ return -1; }else if(o.distance==this.distance){ return 0; } return 1; } @Override public String toString() { return distance + "," + classVal; } }
3,241
33.126316
108
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/Shapelet.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools; /** * * @author raj09hxu */ /* * A legacy shapelet class to recreate the results from the following paper: * Classification of Time Series by Shapelet Transformation, * Hills, J., Lines, J., Baranauskas, E., Mapp, J., and Bagnall, A. * Data Mining and Knowledge Discovery (2013) * */ import java.io.Serializable; import java.util.Comparator; import java.util.List; import utilities.class_counts.ClassCounts; import tsml.transformers.shapelet_tools.quality_measures.ShapeletQualityMeasure; /** * * @author Aaron Bostrom, modified from Jon Hills */ public class Shapelet implements Comparable<Shapelet>, Serializable { public double separationGap; /*It is optional whether to store the whole shapelet or not. It is much more memory efficient not to, but it does make life a little easier. */ public ShapeletCandidate content; public int numDimensions = 1; public int dimension = 0; public int length; public int seriesId; public int startPos; public ShapeletQualityMeasure qualityType; public double qualityValue; public boolean hasContent = true; boolean useSeparationGap = false; public double classValue; public double splitThreshold; public void setUseSeparationGap(boolean b) { useSeparationGap = true; } public ShapeletCandidate getContent() { return content; } public int getLength(){ return length; } public int getNumDimensions(){ if (content != null) { numDimensions = content.getNumChannels(); } return numDimensions; } public int getDimension(){ return dimension; } public double getQualityValue() { return qualityValue; } public int getSeriesId() { return seriesId; } public int getStartPos() { return startPos; } public void setSeriesID(int a) { seriesId = a; } public Shapelet(ShapeletCandidate content) { this.content = content; numDimensions = content.getNumChannels(); length = content.getLength(); } public Shapelet(int seriesId, int startPos, ShapeletQualityMeasure qualityChoice) { this.seriesId = seriesId; this.startPos = startPos; this.qualityType = qualityChoice; this.content = null; length = 0; this.hasContent = false; } public Shapelet(ShapeletCandidate content, double qualValue, int seriesId, int startPos) { this.content = content; numDimensions = content.getNumChannels(); length = content.getLength(); this.seriesId = seriesId; this.startPos = startPos; this.qualityValue = qualValue; } public Shapelet(ShapeletCandidate content, double qualValue, int seriesId, int startPos, double sepGap) { this.content = content; numDimensions = content.getNumChannels(); length = content.getLength(); this.seriesId = seriesId; this.startPos = startPos; this.qualityValue = qualValue; this.separationGap = sepGap; } public Shapelet(ShapeletCandidate content, int seriesId, int startPos, ShapeletQualityMeasure qualityChoice) { this.content = content; length = content.getLength(); numDimensions = content.getNumChannels(); this.seriesId = seriesId; this.startPos = startPos; this.qualityType = qualityChoice; } //this rertuns the first channel. public double[] getUnivariateShapeletContent(){ return content.getShapeletContent(0); } public void clearContent() { this.length = content.getLength(); this.content = null; this.hasContent = false; } public void calculateQuality(List<OrderLineObj> orderline, ClassCounts classDistribution) { qualityValue = qualityType.calculateQuality(orderline, classDistribution); this.qualityValue = this.qualityType.calculateQuality(orderline, classDistribution); } public void calculateSeperationGap(List<OrderLineObj> orderline ){ this.separationGap = this.qualityType.calculateSeperationGap(orderline); } @Override public int compareTo(Shapelet shapelet) { //compare by quality, if there quality is equal we sort by the shorter shapelets. int compare1 = Double.compare(qualityValue, shapelet.qualityValue); int compare2 = Double.compare(content.getLength(), shapelet.getLength()); return compare1 != 0 ? compare1 : compare2; } @Override public String toString() { String str = seriesId + "," + startPos + "," + length + "," + dimension + "," + qualityValue; return str; } public static class ShortOrder implements Comparator<Shapelet>, Serializable{ @Override public int compare(Shapelet s1, Shapelet s2) { int compare1 = Double.compare(s2.qualityValue, s1.qualityValue); // prefer higher info gain int compare2 = (s2.getLength() - s1.getLength()); //prefer the short ones. return compare1 != 0 ? compare1 : compare2; } } public static class LongOrder implements Comparator<Shapelet>, Serializable { @Override public int compare(Shapelet s1, Shapelet s2) { int compare1 = Double.compare(s2.qualityValue, s1.qualityValue); //prefer higher info gain int compare2 = (s1.getLength() - s2.getLength()); //prefer the long ones. return compare1 != 0 ? compare1 : compare2; } } public static class ReverseSeparationGap implements Comparator<Shapelet>, Serializable { @Override public int compare(Shapelet s1, Shapelet s2) { return -(new SeparationGap().compare(s1, s2)); } } public static class SeparationGap implements Comparator<Shapelet>, Serializable { @Override public int compare(Shapelet s1, Shapelet s2) { int compare1 = Double.compare(s1.qualityValue, s2.qualityValue); if(compare1 != 0) return compare1; int compare2 = Double.compare(s1.separationGap, s2.separationGap); if(compare2 != 0) return compare2; int compare3 = Double.compare(s1.getLength(), s2.getLength()); return compare3; } } }
7,336
28.348
112
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/ShapeletCandidate.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools; import java.io.Serializable; /** * * @author raj09hxu */ public class ShapeletCandidate implements Serializable{ double[][] content; int numChannels; //if no dimension, assume univariate public ShapeletCandidate(){ numChannels = 1; content = new double[numChannels][]; } public ShapeletCandidate(int numChans){ numChannels = numChans; content = new double[numChannels][]; } public ShapeletCandidate(double[] cont){ numChannels = 1; content = new double[numChannels][]; content[0] = cont; } //if no dimension, assume univariate public void setShapeletContent(double[] cont){ content[0] = cont; } public void setShapeletContent(int channel, double[] cont){ content[channel] = cont; } public double[] getShapeletContent(int channel){ return content[channel]; } public double[] getShapeletContent(){ return content[0]; } public int getLength(){ return content[0].length; } public int getNumChannels(){ return numChannels; } }
1,966
26.319444
76
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/ShapeletTransformFactory.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; import tsml.filters.shapelet_filters.BalancedClassShapeletFilter; import tsml.filters.shapelet_filters.ShapeletFilter; import tsml.transformers.ShapeletTransform; import tsml.transformers.shapelet_tools.distance_functions.*; import tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance; import tsml.transformers.shapelet_tools.class_value.BinaryClassValue; import tsml.transformers.shapelet_tools.class_value.NormalClassValue; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchFactory; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType; import utilities.rescalers.NoRescaling; import utilities.rescalers.SeriesRescaler; import utilities.rescalers.ZNormalisation; import utilities.rescalers.ZStandardisation; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.CACHED; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.DEPENDENT; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.DIMENSION; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.IMPROVED_ONLINE; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.INDEPENDENT; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.NORMAL; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.ONLINE; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.ONLINE_CACHED; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.RescalerType.*; /** * * @author Aaron */ public class ShapeletTransformFactory { private static final Map<DistanceType, Supplier<ShapeletDistance>> distanceFunctions = createDistanceTable(); private static Map<DistanceType, Supplier<ShapeletDistance>> createDistanceTable(){ //DistanceType{NORMAL, ONLINE, IMP_ONLINE, CACHED, ONLINE_CACHED, DEPENDENT, INDEPENDENT}; Map<DistanceType, Supplier<ShapeletDistance>> dCons = new HashMap<DistanceType, Supplier<ShapeletDistance>>(); dCons.put(NORMAL, ShapeletDistance::new); dCons.put(ONLINE, OnlineShapeletDistance::new); dCons.put(IMPROVED_ONLINE, ImprovedOnlineShapeletDistance::new); dCons.put(CACHED, CachedShapeletDistance::new); dCons.put(ONLINE_CACHED, OnlineCachedShapeletDistance::new); dCons.put(DEPENDENT, MultivariateDependentDistance::new); dCons.put(INDEPENDENT, MultivariateIndependentDistance::new); dCons.put(DIMENSION, DimensionDistance::new); return dCons; } private static final Map<ShapeletDistance.RescalerType, Supplier<SeriesRescaler>> rescalingFunctions = createRescalerTable(); private static Map<ShapeletDistance.RescalerType, Supplier<SeriesRescaler>> createRescalerTable(){ //RescalerType{NONE, NORMALISATION, STANDARDISATION}; Map<ShapeletDistance.RescalerType, Supplier<SeriesRescaler>> dCons = new HashMap<ShapeletDistance.RescalerType, Supplier<SeriesRescaler>>(); dCons.put(NONE, NoRescaling::new); dCons.put(NORMALISATION, ZNormalisation::new); dCons.put(STANDARDISATION, ZStandardisation::new); return dCons; } ShapeletTransformFactoryOptions options; public ShapeletTransformFactory(ShapeletTransformFactoryOptions op){ options = op; } public ShapeletFilter getFilter(){ //build shapelet transform based on options. ShapeletFilter st = createFilter(options.isBalanceClasses()); // ShapeletTransform st = createTransform(options.isBalanceClasses()); st.setUseBalancedClasses(options.isBalanceClasses()); st.setClassValue(createClassValue(options.isBinaryClassValue())); st.setShapeletMinAndMax(options.getMinLength(), options.getMaxLength()); st.setNumberOfShapelets(options.getkShapelets()); st.setSubSeqDistance(createDistance(options.getDistance())); st.setRescaler(createRescaler(options.getRescalerType())); st.setSearchFunction(createSearch(options.getSearchOptions())); st.setQualityMeasure(options.getQualityChoice()); st.setRoundRobin(options.useRoundRobin()); st.setCandidatePruning(options.useCandidatePruning()); st.setNumberOfShapelets(options.getkShapelets()); st.setShapeletMinAndMax(options.getMinLength(),options.getMaxLength()); //st.supressOutput(); return st; } public ShapeletTransform getTransform(){ //build shapelet transform based on options. ShapeletTransform st = new ShapeletTransform();//Removed the balance type st.setUseBalancedClasses(options.isBalanceClasses()); st.setClassValue(createClassValue(options.isBinaryClassValue())); st.setShapeletMinAndMax(options.getMinLength(), options.getMaxLength()); st.setNumberOfShapelets(options.getkShapelets()); st.setShapeletDistance(createDistance(options.getDistance())); st.setRescaler(createRescaler(options.getRescalerType())); st.setSearchFunction(createSearch(options.getSearchOptions())); st.setQualityMeasure(options.getQualityChoice()); st.setRoundRobin(options.useRoundRobin()); st.setCandidatePruning(options.useCandidatePruning()); st.setNumberOfShapelets(options.getkShapelets()); st.setShapeletMinAndMax(options.getMinLength(),options.getMaxLength()); //st.supressOutput(); return st; } //time, number of cases, and length of series public static ShapeletFilter createDefaultTimedTransform(long numShapeletsToEvaluate, int n, int m, long seed){ ShapeletSearchOptions sOp = new ShapeletSearchOptions.Builder() .setMin(3) .setMax(m) .setSearchType(ShapeletSearch.SearchType.IMPROVED_RANDOM) .setNumShapeletsToEvaluate(numShapeletsToEvaluate) .setSeed(seed) .build(); ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .useClassBalancing() .useBinaryClassValue() .useCandidatePruning() .setKShapelets(Math.min(2000, n)) .setDistanceType(DistanceType.NORMAL) .setSearchOptions(sOp) .setRescalerType(NORMALISATION) .build(); return new ShapeletTransformFactory(options).getFilter(); } private ShapeletSearch createSearch(ShapeletSearchOptions sOp){ return new ShapeletSearchFactory(sOp).getShapeletSearch(); } private NormalClassValue createClassValue(boolean classValue){ return classValue ? new BinaryClassValue() : new NormalClassValue(); } private ShapeletFilter createFilter(boolean balance){ return balance ? new BalancedClassShapeletFilter() : new ShapeletFilter(); } private ShapeletDistance createDistance(DistanceType dist){ return distanceFunctions.get(dist).get(); } private SeriesRescaler createRescaler(ShapeletDistance.RescalerType rescalerType) { return rescalingFunctions.get(rescalerType).get(); } public static void main(String[] args) { ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions() .useClassBalancing() .setKShapelets(1000) .setDistanceType(NORMAL) .setRescalerType(NORMALISATION) .setMinLength(3) .setMaxLength(100) .build(); ShapeletTransformFactory factory = new ShapeletTransformFactory(options); ShapeletFilter st = factory.getFilter(); } }
9,421
49.385027
148
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/ShapeletTransformFactoryOptions.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools; import tsml.transformers.shapelet_tools.quality_measures.ShapeletQuality.ShapeletQualityChoice; import static tsml.transformers.shapelet_tools.quality_measures.ShapeletQuality.ShapeletQualityChoice.INFORMATION_GAIN; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.DistanceType.NORMAL; import tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.RescalerType; import static tsml.transformers.shapelet_tools.distance_functions.ShapeletDistance.RescalerType.NORMALISATION; /** * * @author Aaron * This is a holder for the shapelet options which are then used to build the Transform in ShapeletTransformFactory. * We have a Builder class, that clones the Options class, that sets up the Factory class, that builds the Transform * * I knew an old lady who swallowed a fly, perhaps she'll die? This could usefully be restructured .... */ public class ShapeletTransformFactoryOptions { private final int minLength; private final int maxLength; private final int kShapelets; private final boolean balanceClasses; private final boolean binaryClassValue; private final boolean roundRobin; private final boolean candidatePruning; private final DistanceType distance; private final ShapeletQualityChoice qualityChoice; private final ShapeletSearchOptions searchOptions; private final RescalerType rescalerType; private ShapeletTransformFactoryOptions(ShapeletTransformOptions options){ minLength = options.minLength; maxLength = options.maxLength; kShapelets = options.kShapelets; balanceClasses = options.balanceClasses; binaryClassValue = options.binaryClassValue; distance = options.dist; qualityChoice = options.qualityChoice; searchOptions = options.searchOptions; roundRobin = options.roundRobin; candidatePruning = options.candidatePruning; rescalerType = options.rescalerType; } public RescalerType getRescalerType(){ return rescalerType; } public boolean isBalanceClasses() { return balanceClasses; } public boolean isBinaryClassValue() { return binaryClassValue; } public int getMinLength() { return minLength; } public int getMaxLength() { return maxLength; } public int getkShapelets() { return kShapelets; } public DistanceType getDistance() { return distance; } public boolean useRoundRobin(){ return roundRobin; } public boolean useCandidatePruning(){ return candidatePruning; } public ShapeletSearchOptions getSearchOptions(){ return searchOptions; } public ShapeletQualityChoice getQualityChoice(){ return qualityChoice; } @Override public String toString(){ return minLength + " " + maxLength + " " + kShapelets + " " + balanceClasses; } /** Funny inner class that serves no purpose but to confuse ... and why does everything return this?!? * */ public static class ShapeletTransformOptions { private int minLength; private int maxLength; private int kShapelets; private boolean balanceClasses; private boolean binaryClassValue; private boolean roundRobin; private boolean candidatePruning; private DistanceType dist; private ShapeletQualityChoice qualityChoice; private ShapeletSearchOptions searchOptions; private RescalerType rescalerType; public ShapeletTransformOptions useRoundRobin(){ roundRobin = true; return this; } public ShapeletTransformOptions useCandidatePruning(){ candidatePruning = true; return this; } public ShapeletTransformOptions setRoundRobin(boolean b){ roundRobin = b; return this; } public ShapeletTransformOptions setCandidatePruning(boolean b){ candidatePruning = b; return this; } public ShapeletTransformOptions setSearchOptions(ShapeletSearchOptions sOp){ searchOptions = sOp; return this; } public ShapeletTransformOptions setQualityMeasure(ShapeletQualityChoice qm){ qualityChoice = qm; return this; } public ShapeletTransformOptions setMinLength(int min){ minLength = min; return this; } public ShapeletTransformOptions setMaxLength(int max){ maxLength = max; return this; } public int getMaxLength() { return maxLength; } public int getMinLength() { return minLength; } public ShapeletTransformOptions setKShapelets(int k){ kShapelets = k; return this; } public ShapeletTransformOptions setClassBalancing(boolean b){ balanceClasses = b; return this; } public ShapeletTransformOptions setBinaryClassValue(boolean b){ binaryClassValue = b; return this; } public ShapeletTransformOptions useClassBalancing(){ balanceClasses = true; return this; } public ShapeletTransformOptions useBinaryClassValue(){ binaryClassValue = true; return this; } public ShapeletTransformOptions setDistanceType(DistanceType dis){ dist = dis; return this; } public ShapeletTransformOptions setRescalerType(RescalerType type){ rescalerType = type; return this; } public ShapeletTransformFactoryOptions build(){ setDefaults(); return new ShapeletTransformFactoryOptions(this); } private void setDefaults(){ //if there is no search options. use default params; if(searchOptions == null){ searchOptions = new ShapeletSearchOptions.Builder() .setMin(minLength) .setMax(maxLength) .setSearchType(ShapeletSearch.SearchType.FULL) .build(); } if(qualityChoice == null){ qualityChoice = INFORMATION_GAIN; } if(rescalerType == null){ rescalerType = NORMALISATION; } if(dist == null){ dist = NORMAL; } } public String toString(){ String str="DistType,"+dist+",QualityMeasure,"+qualityChoice+",RescaleType,"+rescalerType; str+=",UseRoundRobin,"+roundRobin+",useCandidatePruning,"+candidatePruning+",UseClassBalancing,"+balanceClasses; str+=",useBinaryClassValue,"+binaryClassValue+",minShapeletLength,"+minLength+",maxShapeletLength,"+maxLength; return str; } } }
8,302
33.452282
124
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/ShapeletTransformTimingUtilities.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Random; import tsml.filters.shapelet_filters.BalancedClassShapeletFilter; import tsml.filters.shapelet_filters.ShapeletFilter; import tsml.transformers.ShapeletTransform; import utilities.InstanceTools; import utilities.generic_storage.Pair; import weka.core.Instances; import tsml.transformers.shapelet_tools.class_value.BinaryClassValue; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import tsml.transformers.shapelet_tools.distance_functions.CachedShapeletDistance; import tsml.transformers.shapelet_tools.distance_functions.OnlineShapeletDistance; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchFactory; /** * Shapelet Factory: determines shapelet type and parameters based on the input * 1. distance caching: used if there is enough memory. * Distance caching requires O(nm^2) * 2. number of shapelets: * Set to n*m/10, with a max size max(1000,2*m,2*n) . Assume we will post process cluster * 3. shapelet length range: 3 to train.numAttributes()-1 * * @author Aaron Bostrom */ public class ShapeletTransformTimingUtilities { //this is an arbritary cutoff value for whether we should start subsampling. It's about 7 days(ish). TODO: test. public static final long opCountThreshold = 1000000000000000l; public static final long dayNano = 86400000000000l; public static final long nanoToOp = 10l; //1 op takes 10 nanoseconds. //we create the Map using params jon found. //lazy way to avoid reading a text file. //it is immutable. public static final Map<String, Pair<Integer, Integer>> shapeletParams; static{ shapeletParams = new HashMap<>(); shapeletParams.put("Adiac", new Pair(3,10)); shapeletParams.put("ArrowHead", new Pair(17,90)); shapeletParams.put("Beef", new Pair(8,30)); shapeletParams.put("BeetleFly", new Pair(30,101)); shapeletParams.put("BirdChicken", new Pair(30,101)); shapeletParams.put("Car", new Pair(16,57)); shapeletParams.put("CBF", new Pair(46,90)); shapeletParams.put("ChlorineConcentration", new Pair(7,20)); shapeletParams.put("CinCECGtorso", new Pair(697,814)); shapeletParams.put("Coffee", new Pair(18,30)); shapeletParams.put("Computers", new Pair(15,267)); shapeletParams.put("CricketX", new Pair(120,255)); shapeletParams.put("CricketY", new Pair(132,262)); shapeletParams.put("CricketZ", new Pair(118,257)); shapeletParams.put("DiatomSizeReduction", new Pair(7,16)); shapeletParams.put("DistalPhalanxOutlineAgeGroup", new Pair(7,31)); shapeletParams.put("DistalPhalanxOutlineCorrect", new Pair(6,16)); shapeletParams.put("DistalPhalanxTW", new Pair(17,31)); shapeletParams.put("Earthquakes", new Pair(24,112)); shapeletParams.put("ECGFiveDays", new Pair(24,76)); shapeletParams.put("FaceAll", new Pair(70,128)); shapeletParams.put("FaceFour", new Pair(20,120)); shapeletParams.put("FacesUCR", new Pair(47,128)); shapeletParams.put("Fiftywords", new Pair(170,247)); shapeletParams.put("Fish", new Pair(22,60)); shapeletParams.put("FordA", new Pair(50,298)); shapeletParams.put("FordB", new Pair(38,212)); shapeletParams.put("GunPoint", new Pair(24,55)); shapeletParams.put("Haptics", new Pair(21,103)); shapeletParams.put("Herrings", new Pair(30,101)); shapeletParams.put("InlineSkate", new Pair(750,896)); shapeletParams.put("ItalyPowerDemand", new Pair(7,14)); shapeletParams.put("LargeKitchenAppliances", new Pair(13,374)); shapeletParams.put("Lightning2", new Pair(47,160)); shapeletParams.put("Lightning7", new Pair(20,80)); shapeletParams.put("Mallat", new Pair(52,154)); shapeletParams.put("MedicalImages", new Pair(9,35)); shapeletParams.put("MiddlePhalanxOutlineAgeGroup", new Pair(8,31)); shapeletParams.put("MiddlePhalanxOutlineCorrect", new Pair(5,12)); shapeletParams.put("MiddlePhalanxTW", new Pair(7,31)); shapeletParams.put("MoteStrain", new Pair(16,31)); shapeletParams.put("NonInvasiveFatalECGThorax1", new Pair(5,61)); shapeletParams.put("NonInvasiveFatalECGThorax2", new Pair(12,58)); shapeletParams.put("OliveOil", new Pair(8,27)); shapeletParams.put("OSULeaf", new Pair(141,330)); shapeletParams.put("PhalangesOutlinesCorrect", new Pair(5,14)); shapeletParams.put("Plane", new Pair(18,109)); shapeletParams.put("ProximalPhalanxOutlineAgeGroup", new Pair(7,31)); shapeletParams.put("ProximalPhalanxOutlineCorrect", new Pair(5,12)); shapeletParams.put("ProximalPhalanxTW", new Pair(9,31)); shapeletParams.put("PtNDeviceGroups", new Pair(51,261)); shapeletParams.put("PtNDevices", new Pair(100,310)); shapeletParams.put("RefrigerationDevices", new Pair(13,65)); shapeletParams.put("ScreenType", new Pair(11,131)); shapeletParams.put("ShapeletSim", new Pair(25,35)); shapeletParams.put("SmallKitchenAppliances", new Pair(31,443)); shapeletParams.put("SonyAIBORobotSurface1", new Pair(15,36)); shapeletParams.put("SonyAIBORobotSurface2", new Pair(22,57)); shapeletParams.put("StarlightCurves", new Pair(68,650)); shapeletParams.put("SwedishLeaf", new Pair(11,45)); shapeletParams.put("Symbols", new Pair(52,155)); shapeletParams.put("SyntheticControl", new Pair(20,56)); shapeletParams.put("ToeSegmentation1", new Pair(39,153)); shapeletParams.put("ToeSegmentation2", new Pair(100,248)); shapeletParams.put("Trace", new Pair(62,232)); shapeletParams.put("TwoLeadECG", new Pair(7,13)); shapeletParams.put("TwoPatterns", new Pair(20,71)); shapeletParams.put("UWaveGestureLibraryX", new Pair(113,263)); shapeletParams.put("UWaveGestureLibraryY", new Pair(122,273)); shapeletParams.put("UWaveGestureLibraryZ", new Pair(135,238)); shapeletParams.put("Wafer", new Pair(29,152)); shapeletParams.put("WordSynonyms", new Pair(137,238)); shapeletParams.put("Worms", new Pair(93,382)); shapeletParams.put("WormsTwoClass", new Pair(46,377)); shapeletParams.put("Yoga", new Pair(12,132)); Collections.unmodifiableMap(shapeletParams); } public static final double MEM_CUTOFF = 0.5; public static final int MAX_NOS_SHAPELETS = 1000; public static ShapeletFilter createCachedTransform() { ShapeletFilter st = new ShapeletFilter(); st.setSubSeqDistance(new CachedShapeletDistance()); return st; } public static ShapeletFilter createOnlineTransform() { ShapeletFilter st = new ShapeletFilter(); st.setSubSeqDistance(new OnlineShapeletDistance()); return st; } public static ShapeletFilter createBasicTransform(int n, int m){ ShapeletFilter fst = new ShapeletFilter(); fst.setNumberOfShapelets(n); fst.setShapeletMinAndMax(3, m); fst.supressOutput(); return fst; } public static ShapeletFilter createTransform(Instances train){ int numClasses = train.numClasses(); int numInstances = train.numInstances() <= 2000 ? train.numInstances() : 2000; int numAttributes = train.numAttributes()-1; ShapeletFilter transform; if(numClasses == 2){ transform = new ShapeletFilter(); }else{ transform = new BalancedClassShapeletFilter(); transform.setClassValue(new BinaryClassValue()); } //transform.setSubSeqDistance(new ImprovedOnlineShapeletDistance()); transform.setShapeletMinAndMax(3, numAttributes); transform.setNumberOfShapelets(numInstances); transform.useCandidatePruning(); transform.turnOffLog(); transform.setRoundRobin(true); transform.supressOutput(); return transform; } long getAvailableMemory() { Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); long maxMemory = runtime.maxMemory(); long usedMemory = totalMemory - freeMemory; long availableMemory = maxMemory - usedMemory; return availableMemory; } // Method to estimate min/max shapelet length for a given data public static int[] estimateMinAndMax(Instances data, ShapeletFilter st) { ShapeletFilter st1 = null; try { //we need to clone the FST. st1 = st.getClass().newInstance(); st1.setClassValue(st.classValue.getClass().newInstance()); st1.setSubSeqDistance(st.subseqDistance.getClass().newInstance()); } catch (InstantiationException | IllegalAccessException ex) { System.out.println("Exception: "); } if(st1 == null) st1 = new ShapeletFilter(); st1.supressOutput(); ArrayList<Shapelet> shapelets = new ArrayList<>(); st.supressOutput(); st.turnOffLog(); Instances randData = new Instances(data); Instances randSubset; for (int i = 0; i < 10; i++) { randData.randomize(new Random()); randSubset = new Instances(randData, 0, 10); shapelets.addAll(st1.findBestKShapeletsCache(10, randSubset, 3, randSubset.numAttributes() - 1)); } Collections.sort(shapelets, new ShapeletLengthComparator()); int min = shapelets.get(24).getLength(); int max = shapelets.get(74).getLength(); return new int[]{min,max}; } //bog standard min max estimation. public static int[] estimateMinAndMax(Instances data) { return estimateMinAndMax(data, new ShapeletFilter()); } //Class implementing comparator which compares shapelets according to their length public static class ShapeletLengthComparator implements Comparator<Shapelet>{ @Override public int compare(Shapelet shapelet1, Shapelet shapelet2){ int shapelet1Length = shapelet1.getLength(); int shapelet2Length = shapelet2.getLength(); return Integer.compare(shapelet1Length, shapelet2Length); } } public static long calculateNumberOfShapelets(Instances train, int minShapeletLength, int maxShapeletLength){ return calculateNumberOfShapelets(train.numInstances(), train.numAttributes()-1, minShapeletLength, maxShapeletLength); } /** * calculateNumberOfShapelets: finds the total possible number of shapelets in a data set //verified on Trace dataset from Ye2011 with 7,480,200 shapelets : page 158. * @param numInstances * @param numAttributes * @param minShapeletLength * @param maxShapeletLength * @return */ public static long calculateNumberOfShapelets(int numInstances, int numAttributes, int minShapeletLength, int maxShapeletLength){ long numShapelets=0; //calculate number of shapelets in a single instance. for (int length = minShapeletLength; length <= maxShapeletLength; length++) { numShapelets += numAttributes - length + 1; } numShapelets*=numInstances; return numShapelets; } public static long calculateShapeletsFromOpCount(int numInstances, int numAttributes, long opCount){ return (long)((6.0* (double)opCount) / ( numAttributes * ((numAttributes*numAttributes) + (3*numAttributes) + 2)*(numInstances-1))); } public static long calculateOperations(Instances train, int minShapeletLength, int maxShapeletLength){ return calculateOperations(train.numInstances(), train.numAttributes()-1, minShapeletLength, maxShapeletLength); } //verified correct by counting ops in transform public static long calculateOperations(int numInstances, int numAttributes, int minShapeletLength, int maxShapeletLength){ return calculateOperationsWithSkipping(numInstances, numAttributes, minShapeletLength, maxShapeletLength, 1,1, 1.0f); } public static long calculateOperationsWithProportion(Instances train, int minShapeletLength, int maxShapeletLength, float proportion){ return calculateOperationsWithSkipping(train.numInstances(), train.numAttributes()-1, minShapeletLength, maxShapeletLength,1,1,proportion); } //verified correct by counting ops in transform //not exact with shapelet proportion, because of nondeterministic nature. public static long calculateOperationsWithSkipping(int numInstances, int numAttributes, int minShapeletLength, int maxShapeletLength, int posSkip, int lengthSkip, float Shapeletproportion){ long numOps=0; int shapelets =0; //calculate number of shapelets in a single instance. for (int length = minShapeletLength; length <= maxShapeletLength; length+=lengthSkip) { long shapeletsLength = (long) (((numAttributes - length + 1) / posSkip) * Shapeletproportion); shapelets+=shapeletsLength; //System.out.println(shapeletsLength); long shapeletsCompared = (numAttributes - length + 1); //each shapelet gets compared to all other subsequences, and they make l operations per comparison for every series.. long comparisonPerSeries = shapeletsLength * shapeletsCompared * length * (numInstances-1); numOps +=comparisonPerSeries; } //for every series. numOps *= numInstances; return numOps; } public static double calc(int n, int m, int min, int max, int pos, int len) { double numOps =0; //-1 from max because we index from 0. for(int length = 0; length <= ((max-min)/len); length++){ int currentLength = (len*length) + min; double shapeletsLength = Math.ceil((double)(m - currentLength + 1) / (double) pos); //shapelts found. double shapeletsCompared = (m - currentLength + 1); numOps += shapeletsLength*shapeletsCompared*currentLength; } numOps*= n * (n-1); return numOps; } public static long calcShapelets(int n, int m, int min, int max, int pos, int len) { long numOps =0; //-1 from max because we index from 0. for(int length = 0; length <= ((max-min)/len); length++){ int currentLength = (len*length) + min; long shapeletsLength = (long) Math.ceil((double)(m - currentLength + 1) / (double) pos); //shapelts found. numOps += shapeletsLength; } numOps*= n; return numOps; } public static BigInteger calculateOps(int n, int m, int posS, int lenS){ BigInteger nSqd = new BigInteger(Long.toString(n)); nSqd = nSqd.pow(2); long lenSqd = lenS*lenS; BigInteger mSqd = new BigInteger(Long.toString(m)); mSqd = mSqd.pow(2); BigInteger temp1 = mSqd; temp1 = mSqd.multiply(new BigInteger(Long.toString(m))); BigInteger temp2 = mSqd.multiply(new BigInteger("7")); BigInteger temp3 = new BigInteger(Long.toString(m*(lenSqd - (18*lenS) + 27))); BigInteger temp4 = new BigInteger(Long.toString(lenS*((5*lenS) - 24) + 27)); BigInteger bg = new BigInteger("0"); bg = bg.add(temp1); bg = bg.add(temp2); bg = bg.subtract(temp3); bg = bg.add(temp4); bg = bg.multiply(nSqd.subtract(new BigInteger(Long.toString(n)))); bg = bg.multiply(new BigInteger(Long.toString((m-3)))); bg = bg.divide(new BigInteger(Long.toString((12 * posS * lenS)))); return bg; } public static double calculateN(int n, int m, long time){ long opCount = time / nanoToOp; BigDecimal numerator = new BigDecimal(Long.toString(12*opCount)); BigInteger temp1 = new BigInteger(Long.toString(m*m)); temp1 = temp1.multiply(new BigInteger(Long.toString(m))); BigInteger temp2 = new BigInteger(Long.toString(7*m*m)); BigInteger temp3 = new BigInteger(Long.toString(10*m)); BigInteger temp4 = new BigInteger(Long.toString(8)); temp1 = temp1.add(temp2); temp1 = temp1.subtract(temp3); temp1 = temp1.add(temp4); temp1 = temp1.multiply(new BigInteger(Long.toString(m-3))); BigDecimal denominator = new BigDecimal(temp1); BigDecimal result = utilities.StatisticalUtilities.sqrt(numerator.divide(denominator, MathContext.DECIMAL32), MathContext.DECIMAL32); //sqrt result. result = result.divide(new BigDecimal(n), MathContext.DECIMAL32); return Math.min(result.doubleValue(), 1.0); //return the proportion of n. } // added by JAL - both edited versions of ShapeletTransformClassifier.createTransformData // param changed to hours from nanos to make it human readable // seed included; set to 0 by default in ShapeletTransformClassifier, so same behaviour included unless specified public static ShapeletFilter createTransformWithTimeLimit(Instances train, double hours){ return createTransformWithTimeLimit(train, hours, 0); } public static ShapeletFilter createTransformWithTimeLimit(Instances train, double hours, int seed){ int minimumRepresentation = ShapeletTransform.minimumRepresentation; long nanoPerHour = 3600000000000l; long time = (long)(nanoPerHour*hours); int n = train.numInstances(); int m = train.numAttributes()-1; ShapeletFilter transform; //construct shapelet classifiers from the factory. transform = ShapeletTransformTimingUtilities.createTransform(train); //Stop it printing everything transform.supressOutput(); //at the moment this could be overrided. //transform.setSearchFunction(new LocalSearch(3, m, 10, seed)); BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp)); BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1); //we need to resample. if(opCount.compareTo(opCountTarget) == 1){ double recommendedProportion = ShapeletTransformTimingUtilities.calculateN(n, m, time); //calculate n for minimum class rep of 25. int small_sf = InstanceTools.findSmallestClassAmount(train); double proportion = 1.0; if (small_sf>minimumRepresentation){ proportion = (double)minimumRepresentation/(double)small_sf; } //if recommended is smaller than our cutoff threshold set it to the cutoff. if(recommendedProportion < proportion){ recommendedProportion = proportion; } //subsample out dataset. Instances subsample = utilities.InstanceTools.subSampleFixedProportion(train, recommendedProportion, seed); int i=1; //if we've properly resampled this should pass on first go. IF we haven't we'll try and reach our target. //calculate N is an approximation, so the subsample might need to tweak q and p just to bring us under. while(ShapeletTransformTimingUtilities.calculateOps(subsample.numInstances(), m, i, i).compareTo(opCountTarget) == 1){ i++; } double percentageOfSeries = (double)i/(double)m * 100.0; //we should look for less shapelets if we've resampled. //e.g. Eletric devices can be sampled to from 8000 for 2000 so we should be looking for 20,000 shapelets not 80,000 transform.setNumberOfShapelets(subsample.numInstances()); ShapeletSearchOptions sOptions = new ShapeletSearchOptions.Builder().setMin(3).setMax(m).setLengthInc(i).setPosInc(i).build(); transform.setSearchFunction(new ShapeletSearchFactory(sOptions).getShapeletSearch()); transform.process(subsample); } return transform; } public static void main(String[] args) throws IOException { /*System.out.println(calculateOperationsWithSkipping(67, 23, 3, 23, 1, 1, 1.0f)); System.out.println(calculateNumberOfShapelets(67,23,3,23)); System.out.println((int) (calculateNumberOfShapelets(67,23,3,23) * 0.5f)); System.out.println(calculateOperationsWithSkipping(67, 23, 3, 23, 1, 1, 0.5f));*/ /*String dirPath = "F:\\Dropbox\\TSC Problems (1)\\"; File dir = new File(dirPath); for(File dataset : dir.listFiles()){ if(!dataset.isDirectory()) continue; String f = dataset.getPath()+ File.separator + dataset.getName() + "_TRAIN.arff"; Instances train = ClassifierTools.loadData(f); long shapelets = calculateNumberOfShapelets(train, 3, train.numAttributes()-1); //long ops = calculateOperations(train, 3, train.numAttributes()-1); System.out.print(dataset.getName() + ","); System.out.print(train.numAttributes()-1 + ","); System.out.print(train.numInstances() + ","); int min = 3; int max = train.numAttributes()-1; int pos = 1; int len = 1; FullShapeletTransform transform = new FullShapeletTransform(); transform.setSearchFunction(new ShapeletSearch(min,max,len, pos)); transform.setSubSeqDistance(new ShapeletDistance()); transform.supressOutput(); transform.process(train); long ops3 = transform.getCount(); long ops4 = calc(train.numInstances(), train.numAttributes()-1, min, max,pos,len); double n = calculateN(train.numInstances(), train.numAttributes()-1, dayNano); //calculate n for minimum class rep of 25. int small_sf = InstanceTools.findSmallestClassAmount(train); double proportion = 1.0; if (small_sf>25){ proportion = (double)25/(double)small_sf; } System.out.print(ops4 + ","); System.out.print(n + ","); System.out.print(proportion + "\n"); }*/ } }
24,206
42.694946
193
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/class_value/BinaryClassValue.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.class_value; import tsml.data_containers.TimeSeriesInstances; import utilities.class_counts.ClassCounts; import utilities.class_counts.TreeSetClassCounts; import weka.core.Instance; import weka.core.Instances; /** * * @author raj09hxu */ public class BinaryClassValue extends NormalClassValue{ ClassCounts[] binaryClassDistribution; @Override public void init(Instances inst) { //this inits the classDistributions. super.init(inst); binaryClassDistribution = createBinaryDistributions(); } @Override public void init(TimeSeriesInstances inst) { //this inits the classDistributions. super.init(inst); binaryClassDistribution = createBinaryDistributions(); } @Override public ClassCounts getClassDistributions() { return binaryClassDistribution[(int)shapeletValue]; } @Override public double getClassValue(Instance in) { return in.classValue() == shapeletValue ? 0.0 : 1.0; } private ClassCounts[] createBinaryDistributions() { ClassCounts[] binaryMapping = new ClassCounts[classDistributions.size()]; //for each classVal build a binary distribution map. int i=0; for(double key : classDistributions.keySet()) { binaryMapping[i++] = binariseDistributions(key); } return binaryMapping; } private ClassCounts binariseDistributions(double shapeletClassVal) { //binary distribution only needs to be size 2. ClassCounts binaryDistribution = new TreeSetClassCounts(); Integer shapeletClassCount = classDistributions.get(shapeletClassVal); binaryDistribution.put(0.0, shapeletClassCount); int sum = 0; for(double i : classDistributions.keySet()) { sum += classDistributions.get(i); } //remove the shapeletsClass count. Rest should be all the other classes. sum -= shapeletClassCount; binaryDistribution.put(1.0, sum); return binaryDistribution; } }
2,940
29.957895
81
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/class_value/NormalClassValue.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.class_value; import java.io.Serializable; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import utilities.class_counts.ClassCounts; import utilities.class_counts.TreeSetClassCounts; import weka.core.Instance; import weka.core.Instances; /** * * @author raj09hxu */ public class NormalClassValue implements Serializable{ double shapeletValue; ClassCounts classDistributions; public void init(Instances inst) { classDistributions = new TreeSetClassCounts(inst); } public void init(TimeSeriesInstances inst) { classDistributions = new TreeSetClassCounts(inst); } public ClassCounts getClassDistributions() { return classDistributions; } //this will get updated as and when we work with a new shapelet. public void setShapeletValue(Instance shapeletSeries) { shapeletValue = shapeletSeries.classValue(); } //this will get updated as and when we work with a new shapelet. public void setShapeletValue(TimeSeriesInstance shapeletSeries) { shapeletValue = shapeletSeries.getLabelIndex(); } public double getClassValue(Instance in){ return in.classValue(); } public double getClassValue(TimeSeriesInstance in){ return in.getLabelIndex(); } public double getShapeletValue() { return shapeletValue; } }
2,251
27.871795
76
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/CachedShapeletDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; import weka.core.Instances; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author raj09hxu */ public class CachedShapeletDistance extends ShapeletDistance { protected Stats stats; protected double[][] data; @Override public void init(Instances dataInst) { stats = new Stats(); //Normalise all time series for further processing int dataSize = dataInst.numInstances(); data = new double[dataSize][]; for (int i = 0; i < dataSize; i++) { data[i] = seriesRescaler.rescaleSeries(dataInst.get(i).toDoubleArray(), true); } } @Override public void setShapelet(Shapelet shp) { super.setShapelet(shp); //for transforming we don't want to use the stats. it doesn't make sense. stats = null; } @Override public void setSeries(int seriesId) { super.setSeries(seriesId); //do some extra stats. stats.computeStats(seriesId, data); } @Override public double calculate(double[] timeSeries, int timeSeriesId) { //if the stats object is null, use normal calculations. if(stats == null) return super.calculate(timeSeries,timeSeriesId); //the series we're comparing too. stats.setCurrentY(timeSeriesId); double minSum = Double.MAX_VALUE; int subLength = length; double xMean = stats.getMeanX(startPos, subLength); double xStdDev = stats.getStdDevX(startPos, subLength); double yMean; double yStdDev; double crossProd; // Scan through all possible subsequences of two for (int v = 0; v < timeSeries.length - subLength; v++) { yMean = stats.getMeanY(v, subLength); yStdDev = stats.getStdDevY(v, subLength); crossProd = stats.getSumOfProds(startPos, v, subLength); double cXY = 0.0; if (xStdDev != 0 && yStdDev != 0) { cXY = (crossProd - (subLength * xMean * yMean)) / ((double)subLength * xStdDev * yStdDev); } double dist = 2.0 * (1.0 - cXY); if (dist < minSum) { minSum = dist; } } return minSum; } /** * A class for holding relevant statistics for any given candidate series * and all time series TO DO: CONVERT IT ALL TO FLOATS * Aaron: Changed to floats, why? */ public static class Stats { private double[][] cummSums; private double[][] cummSqSums; private double[][][] crossProds; private int xIndex; private int yIndex; /** * Default constructor */ public Stats() { cummSums = null; cummSqSums = null; crossProds = null; xIndex = -1; yIndex = -1; } /** * A method to retrieve cumulative sums for all time series processed so * far * * @return cumulative sums */ public double[][] getCummSums() { return cummSums; } /** * A method to retrieve cumulative square sums for all time series * processed so far * * @return cumulative square sums */ public double[][] getCummSqSums() { return cummSqSums; } /** * A method to retrieve cross products for candidate series. The cross * products are computed between candidate and all time series. * * @return cross products */ public double[][][] getCrossProds() { return crossProds; } /** * A method to set current time series that is being examined. * * @param yIndex time series index */ public void setCurrentY(int yIndex) { this.yIndex = yIndex; } /** * A method to retrieve the mean value of a whole candidate sub-series. * * @param startPos start position of the candidate * @param subLength length of the candidate * @return mean value of sub-series */ public double getMeanX(int startPos, int subLength) { double diff = cummSums[xIndex][startPos + subLength] - cummSums[xIndex][startPos]; return diff / (double) subLength; } /** * A method to retrieve the mean value for time series sub-series. Note * that the current Y must be set prior invoking this method. * * @param startPos start position of the sub-series * @param subLength length of the sub-series * @return mean value of sub-series */ public double getMeanY(int startPos, int subLength) { double diff = cummSums[yIndex][startPos + subLength] - cummSums[yIndex][startPos]; return diff / (double) subLength; } /** * A method to retrieve the standard deviation of a whole candidate * sub-series. * * @param startPos start position of the candidate * @param subLength length of the candidate * @return standard deviation of the candidate sub-series */ public double getStdDevX(int startPos, int subLength) { double diff = cummSqSums[xIndex][startPos + subLength] - cummSqSums[xIndex][startPos]; double meanSqrd = getMeanX(startPos, subLength) * getMeanX(startPos, subLength); double temp = diff / (double) subLength; double temp1 = temp - meanSqrd; return Math.sqrt(temp1); } /** * A method to retrieve the standard deviation for time series * sub-series. Note that the current Y must be set prior invoking this * method. * * @param startPos start position of the sub-series * @param subLength length of the sub-series * @return standard deviation of sub-series */ public double getStdDevY(int startPos, int subLength) { double diff = cummSqSums[yIndex][startPos + subLength] - cummSqSums[yIndex][startPos]; double meanSqrd = getMeanX(startPos, subLength) * getMeanX(startPos, subLength); double temp = diff / (double) subLength; double temp1 = temp - meanSqrd; return Math.sqrt(temp1); } /** * A method to retrieve the cross product of whole candidate sub-series * and time series sub-series. Note that the current Y must be set prior * invoking this method. * * @param startX start position of the whole candidate sub-series * @param startY start position of the time series sub-series * @param length length of the both sub-series * @return sum of products for a given overlap between two sub=series */ public double getSumOfProds(int startX, int startY, int length) { return crossProds[yIndex][startX + length][startY + length] - crossProds[yIndex][startX][startY]; } private double[][] computeCummSums(double[] currentSeries) { double[][] output = new double[2][]; output[0] = new double[currentSeries.length]; output[1] = new double[currentSeries.length]; output[0][0] = 0; output[1][0] = 0; //Compute stats for a given series instance for (int i = 1; i < currentSeries.length; i++) { output[0][i] = (double) (output[0][i - 1] + currentSeries[i - 1]); //Sum of vals output[1][i] = (double) (output[1][i - 1] + (currentSeries[i - 1] * currentSeries[i - 1])); //Sum of squared vals } return output; } private double[][] computeCrossProd(double[] x, double[] y) { //im assuming the starting from 1 with -1 is because of class values at the end. double[][] output = new double[x.length][y.length]; for (int u = 1; u < x.length; u++) { for (int v = 1; v < y.length; v++) { int t; //abs(u-v) if (v < u) { t = u - v; output[u][v] = (double) (output[u - 1][v - 1] + (x[v - 1 + t] * y[v - 1])); } else {//else v >= u t = v - u; output[u][v] = (double) (output[u - 1][v - 1] + (x[u - 1] * y[u - 1 + t])); } } } return output; } /** * A method to compute statistics for a given candidate series index and * normalised time series * * @param candidateInstIndex index of the candidate within the time * series database * @param data the normalised database of time series */ public void computeStats(int candidateInstIndex, double[][] data) { xIndex = candidateInstIndex; //Initialise stats caching arrays if (cummSums == null || cummSqSums == null) { cummSums = new double[data.length][]; cummSqSums = new double[data.length][]; } crossProds = new double[data.length][][]; //Process all instances for (int i = 0; i < data.length; i++) { //Check if cummulative sums are already stored for corresponding instance if (cummSums[i] == null || cummSqSums[i] == null) { double[][] sums = computeCummSums(data[i]); cummSums[i] = sums[0]; cummSqSums[i] = sums[1]; } //Compute cross products between candidate series and current series crossProds[i] = computeCrossProd(data[candidateInstIndex], data[i]); } } } }
11,253
31.906433
130
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/DimensionDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; import java.io.Serializable; import weka.core.Instance; /** * * @author raj09hxu */ public class DimensionDistance extends ImprovedOnlineShapeletDistance implements Serializable{ @Override public double calculate(Instance timeSeries, int timeSeriesId){ //split the timeSeries up and pass in the specific shapelet dim. Instance[] dimensions = utilities.multivariate_tools.MultivariateInstanceTools.splitMultivariateInstance(timeSeries); return calculate(dimensions[dimension].toDoubleArray(), timeSeriesId); } }
1,387
35.526316
125
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/ImprovedOnlineShapeletDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; import java.util.Arrays; /** * * @author raj09hxu */ public class ImprovedOnlineShapeletDistance extends OnlineShapeletDistance { @Override public double calculate(double[] timeSeries, int timeSeriesId) { DoubleWrapper sumPointer = new DoubleWrapper(); DoubleWrapper sum2Pointer = new DoubleWrapper(); //Generate initial subsequence that starts at the same position our candidate does. double[] subseq = new double[length]; System.arraycopy(timeSeries, startPos, subseq, 0, subseq.length); subseq = zNormalise(subseq, false, sumPointer, sum2Pointer); double bestDist = 0.0; double temp; //Compute initial distance. from the startPosition the candidate was found. for (int i = 0; i < length; i++) { temp = cand.getShapeletContent()[i] - subseq[i]; bestDist = bestDist + (temp * temp); incrementCount(); } int i=1; double currentDist; int[] pos = new int[2]; double[] sum = {sumPointer.get(), sumPointer.get()}; double[] sumsq = {sum2Pointer.get(), sum2Pointer.get()}; boolean[] traverse = {true,true}; while(traverse[0] || traverse[1]) { //i will be 0 and 1. for(int j=0; j<2; j++) { int modifier = j==0 ? -1 : 1; pos[j] = startPos + (modifier*i); //if we're going left check we're greater than 0 if we're going right check we've got room to move. traverse[j] = j==0 ? pos[j] >= 0 : pos[j] < timeSeries.length - length; //if we can't traverse in that direction. skip it. if(!traverse[j] ) continue; //either take off nothing, or take off 1. This gives us our offset. double start = timeSeries[pos[j]-j]; double end = timeSeries[pos[j]-j + length]; sum[j] = sum[j] + (modifier*end) - (modifier*start); sumsq[j] = sumsq[j] + (modifier *(end * end)) - (modifier*(start * start)); currentDist = calculateBestDistance(pos[j], timeSeries, bestDist, sum[j], sumsq[j]); if (currentDist < bestDist) { bestDist = currentDist; } } i++; } bestDist = (bestDist == 0.0) ? 0.0 : (1.0 / length * bestDist); return bestDist; } public static void main(String[] args) { double[] series1 = {-2.35883,-2.35559,-2.35454,-2.34338,-2.31736,-2.30061,-2.28114,-2.26463,-2.21722,-2.17778,-2.14637,-2.12312,-2.09685,-2.04244,-1.99365,-1.93976,-1.89255,-1.82506,-1.73738,-1.6517,-1.60714,-1.50672,-1.42336,-1.32344,-1.27373,-1.18805,-1.10609,-0.986926,-0.889897,-0.872755,-0.809654,-0.740608,-0.677319,-0.661043,-0.644438,-0.607948,-0.576844,-0.557063,-0.548549,-0.517287,-0.475963,-0.425143,-0.388282,-0.342208,-0.320914,-0.248243,-0.256056,-0.229242,-0.202671,-0.228913,-0.228913,-0.217255,-0.217255,-0.230399,-0.205525,-0.180597,-0.168731,-0.183076,-0.197396,-0.210728,-0.226991,-0.282901,-0.339088,-0.369761,-0.409539,-0.453912,-0.520932,-0.540419,-0.550083,-0.629803,-0.673184,-0.71053,-0.745705,-0.825118,-0.87774,-0.918719,-0.94649,-0.962059,-0.98006,-0.974878,-0.966522,-0.954408,-0.962079,-0.982794,-1.03389,-1.07145,-1.16734,-1.23652,-1.30709,-1.34664,-1.39151,-1.42981,-1.46628,-1.50096,-1.48963,-1.52224,-1.53894,-1.55475,-1.55603,-1.58377,-1.6362,-1.64837,-1.64773,-1.65881,-1.67234,-1.65998,-1.64605,-1.65811,-1.62909,-1.5969,-1.55926,-1.54559,-1.52193,-1.53264,-1.48983,-1.46406,-1.45693,-1.43192,-1.41055,-1.36412,-1.34024,-1.32582,-1.38311,-1.43392,-1.46834,-1.52228,-1.55677,-1.53852,-1.52125,-1.47655,-1.44466,-1.41865,-1.42403,-1.42253,-1.44458,-1.43527,-1.43042,-1.43727,-1.45044,-1.46462,-1.49365,-1.51564,-1.53976,-1.54639,-1.55239,-1.5708,-1.58798,-1.59122,-1.59561,-1.56971,-1.55544,-1.55304,-1.52571,-1.49402,-1.49165,-1.51285,-1.47432,-1.45199,-1.43318,-1.40902,-1.39751,-1.36967,-1.33461,-1.29077,-1.22598,-1.21902,-1.1612,-1.10525,-0.990312,-0.86719,-0.784717,-0.781386,-0.772976,-0.794816,-0.815942,-0.822881,-0.821923,-0.772969,-0.725666,-0.649244,-0.65261,-0.598976,-0.590117,-0.552959,-0.541044,-0.466437,-0.433354,-0.415578,-0.390976,-0.385024,-0.325496,-0.306833,-0.289861,-0.262262,-0.233975,-0.244979,-0.230901,-0.230901,-0.227787,-0.213816,-0.175148,-0.210728,-0.210728,-0.232092,-0.257803,-0.259303,-0.271433,-0.282124,-0.323476,-0.390974,-0.406311,-0.45172,-0.487394,-0.558741,-0.633816,-0.653986,-0.70906,-0.719124,-0.734661,-0.761652,-0.777301,-0.807103,-0.856996,-0.873969,-0.973638,-1.04752,-1.1376,-1.20518,-1.24089,-1.3293,-1.43616,-1.51857,-1.55937,-1.64382,-1.72967,-1.80862,-1.84535,-1.91542,-1.97986,-2.03545,-2.08808,-2.12186,-2.16653,-2.20642,-2.22625,-2.25462,-2.28279,-2.30963,-2.32282,-2.33439,-2.32517}; double[] series = {-2.42362,-2.42037,-2.40958,-2.38444,-2.34403,-2.31221,-2.2892,-2.26257,-2.20698,-2.17146,-2.11826,-2.06019,-2.00828,-1.93929,-1.91255,-1.8356,-1.75096,-1.6679,-1.57946,-1.49402,-1.39886,-1.30113,-1.20721,-1.10977,-1.04827,-0.957522,-0.883125,-0.827823,-0.766507,-0.711107,-0.685959,-0.628028,-0.574652,-0.525584,-0.480532,-0.439185,-0.401229,-0.37882,-0.339959,-0.343965,-0.312258,-0.293985,-0.278957,-0.243371,-0.231714,-0.244979,-0.23318,-0.208815,-0.196886,-0.209385,-0.197396,-0.185348,-0.185348,-0.173246,-0.161092,-0.161092,-0.161389,-0.173885,-0.161638,-0.174126,-0.186602,-0.174313,-0.174313,-0.174313,-0.186774,-0.149627,-0.137236,-0.174529,-0.162138,-0.162138,-0.162138,-0.149697,-0.177295,-0.206157,-0.251899,-0.28713,-0.32119,-0.365304,-0.390937,-0.442299,-0.451622,-0.503908,-0.531645,-0.608071,-0.657744,-0.657889,-0.708626,-0.759941,-0.797898,-0.834918,-0.858439,-0.89341,-0.940762,-0.97362,-1.00531,-1.03584,-1.05895,-1.10343,-1.13883,-1.20385,-1.2482,-1.30396,-1.36946,-1.43629,-1.50389,-1.56006,-1.64095,-1.70827,-1.75326,-1.81769,-1.87946,-1.93278,-1.97697,-1.9933,-1.98434,-1.98565,-1.97273,-1.96788,-1.9614,-1.95312,-1.94286,-1.92576,-1.93088,-1.92907,-1.90104,-1.90063,-1.93433,-1.93088,-1.94543,-1.95767,-1.96773,-1.97576,-1.99609,-1.98372,-1.98688,-1.97552,-1.9766,-1.96922,-1.95075,-1.90502,-1.84486,-1.79476,-1.73013,-1.66389,-1.6091,-1.54106,-1.4723,-1.40435,-1.3378,-1.26845,-1.20531,-1.14497,-1.07307,-1.02905,-1.00664,-1.00899,-0.963046,-0.95229,-0.918405,-0.883434,-0.859901,-0.822881,-0.797245,-0.746109,-0.719001,-0.695168,-0.645495,-0.588003,-0.546026,-0.49474,-0.45239,-0.418832,-0.349027,-0.309276,-0.272255,-0.263512,-0.243407,-0.214545,-0.199307,-0.149627,-0.137151,-0.149511,-0.137024,-0.137024,-0.14935,-0.124528,-0.136854,-0.136854,-0.149143,-0.161389,-0.161389,-0.173591,-0.185745,-0.185745,-0.197847,-0.209895,-0.184896,-0.196886,-0.184391,-0.19632,-0.171903,-0.195697,-0.207496,-0.219226,-0.20675,-0.217531,-0.229038,-0.255529,-0.282229,-0.289666,-0.305647,-0.338269,-0.353253,-0.412735,-0.451207,-0.492984,-0.52593,-0.550202,-0.603562,-0.636349,-0.698716,-0.766634,-0.815266,-0.882392,-0.943598,-1.03275,-1.11739,-1.2127,-1.28884,-1.38657,-1.46949,-1.55501,-1.64894,-1.73423,-1.8083,-1.88701,-1.9614,-2.01711,-2.04854,-2.10683,-2.16052,-2.20698,-2.25171,-2.29107,-2.31355,-2.35681,-2.38557,-2.41029,-2.41197,-2.42345,-2.42408}; int startPos = 60; int length = 17; double[] subseq = Arrays.copyOfRange(series1, startPos, startPos+length); ImprovedOnlineShapeletDistance iosd = new ImprovedOnlineShapeletDistance(); //iosd.setCandidate(subseq, series.length-subseq.length); double leftToRight = iosd.calculate(series, 1); //iosd.setCandidate(subseq, startPos); double rightToLeft = iosd.calculate(series, 1); //iosd.setCandidate(subseq, startPos); //double middleOut = iosd.calculate(series, 1); //System.out.println("<----->"); System.out.println(leftToRight); System.out.println(rightToLeft); //System.out.println(middleOut); OnlineShapeletDistance osd = new OnlineShapeletDistance(); //osd.setCandidate(subseq, 0); double original = osd.calculate(series, 1); System.out.println(original); } }
9,353
66.782609
2,399
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/MultivariateDependentDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; import java.io.Serializable; import tsml.data_containers.TimeSeriesInstance; import tsml.transformers.shapelet_tools.Shapelet; import static utilities.multivariate_tools.MultivariateInstanceTools.convertMultiInstanceToArrays; import static utilities.multivariate_tools.MultivariateInstanceTools.splitMultivariateInstance; import weka.core.Instance; /** * * @author raj09hxu */ public class MultivariateDependentDistance extends MultivariateDistance implements Serializable{ @Override public double calculate(Instance inst, int timeSeriesId){ return calculate(convertMultiInstanceToArrays(splitMultivariateInstance(inst)), timeSeriesId); } @Override public double calculate(TimeSeriesInstance timeSeries, int timeSeriesId){ return calculate(timeSeries.toValueArray(), timeSeriesId); } @Override public double distanceToShapelet(Shapelet otherShapelet){ double sum = 0; double temp; //loop through all the channels. for(int j=0; j< numChannels; j++){ for (int k = 0; k < length; k++) { temp = (cand.getShapeletContent(j)[k] - otherShapelet.getContent().getShapeletContent(j)[k]); sum = sum + (temp * temp); } } double dist = (sum == 0.0) ? 0.0 : (1.0 / length * sum); return dist; } //we take in a start pos, but we also start from 0. public double calculate(double[][] timeSeries, int timeSeriesId) { double bestSum = Double.MAX_VALUE; double sum; double[] subseq; double temp; //m-l+1 //multivariate instances that are split dont have a class value on them. for (int i = 0; i < seriesLength - length + 1; i++) { sum = 0; //loop through all the channels. for(int j=0; j< numChannels; j++){ //copy a section of one of the series from the channel. subseq = new double[length]; System.arraycopy(timeSeries[j], i, subseq, 0, length); subseq = seriesRescaler.rescaleSeries(subseq, false); // Z-NORM HERE for (int k = 0; k < length; k++) { //count ops incrementCount(); temp = (cand.getShapeletContent(j)[k] - subseq[k]); sum = sum + (temp * temp); } } if (sum < bestSum) { bestSum = sum; //System.out.println(i); } } double dist = (bestSum == 0.0) ? 0.0 : (1.0 / length * bestSum); return dist; } }
3,559
33.563107
109
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/MultivariateDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; import java.io.Serializable; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.transformers.shapelet_tools.ShapeletCandidate; import static utilities.multivariate_tools.MultivariateInstanceTools.convertMultiInstanceToArrays; import static utilities.multivariate_tools.MultivariateInstanceTools.splitMultivariateInstance; import weka.core.Instance; import weka.core.Instances; /** * * @author raj09hxu */ public class MultivariateDistance extends ShapeletDistance implements Serializable{ protected int numChannels; protected int seriesLength; @Override public void init(Instances data) { count =0; numChannels = utilities.multivariate_tools.MultivariateInstanceTools.numDimensions(data); seriesLength = utilities.multivariate_tools.MultivariateInstanceTools.channelLength(data); } public void init(TimeSeriesInstances data) { count =0; numChannels = data.getMaxNumDimensions(); seriesLength = data.getMaxLength(); } protected double[][] candidateArray2; @Override public void setCandidate(Instance inst, int start, int len, int dim) { //extract shapelet and nomrliase. cand = new ShapeletCandidate(numChannels); startPos = start; length = len; //only call to double array when we've changed series. if(candidateInst==null || candidateInst != inst){ candidateArray2 = convertMultiInstanceToArrays(splitMultivariateInstance(inst)); candidateInst = inst; } for(int i=0; i< numChannels; i++){ double[] temp = new double[length]; //copy the data from the whole series into a candidate. System.arraycopy(candidateArray2[i], start, temp, 0, length); temp = seriesRescaler.rescaleSeries(temp, false); //normalise each series. cand.setShapeletContent(i, temp); } } @Override public void setCandidate(TimeSeriesInstance inst, int start, int len, int dim) { //extract shapelet and nomrliase. cand = new ShapeletCandidate(numChannels); startPos = start; length = len; dimension = dim; if(candidateInst==null || candidateInst != inst){ candidateArray2 = inst.toValueArray(); candidateTSInst = inst; } for(int i=0; i< numChannels; i++){ double[] temp = inst.get(dimension).getVSliceArray(start, start+length); temp = seriesRescaler.rescaleSeries(temp, false); //normalise each series. cand.setShapeletContent(i, temp); } } }
3,558
35.316327
98
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/MultivariateIndependentDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; import java.io.Serializable; import tsml.data_containers.TimeSeriesInstance; import tsml.transformers.shapelet_tools.Shapelet; import weka.core.Instance; /** * * @author raj09hxu */ public class MultivariateIndependentDistance extends MultivariateDistance implements Serializable{ //calculate the minimum distance for each channel, and then average. @Override public double calculate(Instance timeSeries, int timeSeriesId){ Instance[] channel = utilities.multivariate_tools.MultivariateInstanceTools.splitMultivariateInstance(timeSeries); double cumulative_distance=0; for(int i=0; i< channel.length; i++){ cumulative_distance += calculate(cand.getShapeletContent(i), channel[i].toDoubleArray()); } //return candidate back into the holder and the instance it comes from. return cumulative_distance; } //calculate the minimum distance for each channel, and then average. @Override public double calculate(TimeSeriesInstance timeSeries, int timeSeriesId){ double[][] data = timeSeries.toValueArray(); double cumulative_distance=0; for(int i=0; i< data.length; i++){ cumulative_distance += calculate(cand.getShapeletContent(i), data[i]); } //return candidate back into the holder and the instance it comes from. return cumulative_distance; } @Override public double distanceToShapelet(Shapelet otherShapelet){ double sum = 0; //loop through all the channels. for(int j=0; j< numChannels; j++){ sum += super.distanceToShapelet(otherShapelet); } double dist = (sum == 0.0) ? 0.0 : (1.0 / length * sum); return dist; } //we take in a start pos, but we also start from 0. public double calculate(double[] shape, double[] timeSeries) { double bestSum = Double.MAX_VALUE; double sum; double[] subseq; double temp; //m-l+1 //multivariate instances that are split dont have a class value on them. for (int i = 0; i < timeSeries.length - length + 1; i++) { sum = 0; // get subsequence of two that is the same lengh as one subseq = new double[length]; System.arraycopy(timeSeries, i, subseq, 0, length); subseq = seriesRescaler.rescaleSeries(subseq, false); // Z-NORM HERE for (int j = 0; j < length; j++) { //count ops incrementCount(); temp = (shape[j] - subseq[j]); sum = sum + (temp * temp); } if (sum < bestSum) { bestSum = sum; } } double dist = (bestSum == 0.0) ? 0.0 : (1.0 / length * bestSum); return dist; } }
3,779
33.678899
122
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/OnlineCachedShapeletDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import weka.core.Instances; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author raj09hxu */ public class OnlineCachedShapeletDistance extends ShapeletDistance { protected Stats stats; protected double[][] data; @Override public void init(Instances dataInst) { stats = new Stats(); //Normalise all time series for further processing int dataSize = dataInst.numInstances(); data = new double[dataSize][]; for (int i = 0; i < dataSize; i++) { data[i] = seriesRescaler.rescaleSeries(dataInst.get(i).toDoubleArray(), true); } } @Override public void setShapelet(Shapelet shp) { super.setShapelet(shp); //for transforming we don't want to use the stats. it doesn't make sense. stats = null; } @Override public void setSeries(int seriesId) { super.setSeries(seriesId); //do some extra stats. stats.computeStats(seriesId, data); } @Override public double calculate(double[] timeSeries, int timeSeriesId) { //if the stats object is null, use normal calculations. if(stats == null) return super.calculate(timeSeries,timeSeriesId); //the series we're comparing too. stats.setCurrentY(timeSeriesId, data); double minSum = Double.MAX_VALUE; int subLength = length; double xMean = stats.getMeanX(startPos, subLength); double xStdDev = stats.getStdDevX(startPos, subLength); double yMean; double yStdDev; double crossProd; // Scan through all possible subsequences of two for (int v = 0; v < timeSeries.length - subLength; v++) { yMean = stats.getMeanY(v, subLength); yStdDev = stats.getStdDevY(v, subLength); crossProd = stats.getSumOfProds(startPos, v, subLength); double cXY = 0.0; if (xStdDev != 0 && yStdDev != 0) { cXY = (crossProd - (subLength * xMean * yMean)) / ((double)subLength * xStdDev * yStdDev); } double dist = 2.0 * (1.0 - cXY); if (dist < minSum) { minSum = dist; } } return minSum; } /** * A class for holding relevant statistics for any given candidate series * and all time series TO DO: CONVERT IT ALL TO FLOATS * Aaron: Changed to floats, why? */ public static class Stats { private double[] cummSumsX; private double[] cummSqSumsX; private double[]cummSumsY; private double[]cummSqSumsY; private double[][] crossProdsY; private int xIndex; /** * Default constructor */ public Stats() { cummSumsX = null; cummSqSumsX = null; cummSumsY = null; cummSqSumsY = null; crossProdsY = null; xIndex = -1; } /** * A method to set current time series that is being examined. * * @param yIndex time series index */ public void setCurrentY(int yIndex, double[][] data) { //calculate the cumulative sums for the new series. double[][] sums = computeCummSums(data[yIndex]); cummSumsY = sums[0]; cummSqSumsY = sums[1]; //Compute cross products between candidate series and current series crossProdsY = computeCrossProd(data[xIndex], data[yIndex]); } /** * A method to retrieve the mean value of a whole candidate sub-series. * * @param startPos start position of the candidate * @param subLength length of the candidate * @return mean value of sub-series */ public double getMeanX(int startPos, int subLength) { double diff = cummSumsX[startPos + subLength] - cummSumsY[startPos]; return diff / (double) subLength; } /** * A method to retrieve the mean value for time series sub-series. Note * that the current Y must be set prior invoking this method. * * @param startPos start position of the sub-series * @param subLength length of the sub-series * @return mean value of sub-series */ public double getMeanY(int startPos, int subLength) { double diff = cummSumsY[startPos + subLength] - cummSumsY[startPos]; return diff / (double) subLength; } /** * A method to retrieve the standard deviation of a whole candidate * sub-series. * * @param startPos start position of the candidate * @param subLength length of the candidate * @return standard deviation of the candidate sub-series */ public double getStdDevX(int startPos, int subLength) { double diff = cummSqSumsX[startPos + subLength] - cummSqSumsX[startPos]; double meanSqrd = getMeanX(startPos, subLength) * getMeanX(startPos, subLength); double temp = diff / (double) subLength; double temp1 = temp - meanSqrd; return Math.sqrt(temp1); } /** * A method to retrieve the standard deviation for time series * sub-series. Note that the current Y must be set prior invoking this * method. * * @param startPos start position of the sub-series * @param subLength length of the sub-series * @return standard deviation of sub-series */ public double getStdDevY(int startPos, int subLength) { double diff = cummSqSumsY[startPos + subLength] - cummSqSumsY[startPos]; double meanSqrd = getMeanX(startPos, subLength) * getMeanX(startPos, subLength); double temp = diff / (double) subLength; double temp1 = temp - meanSqrd; return Math.sqrt(temp1); } /** * A method to retrieve the cross product of whole candidate sub-series * and time series sub-series. Note that the current Y must be set prior * invoking this method. * * @param startX start position of the whole candidate sub-series * @param startY start position of the time series sub-series * @param length length of the both sub-series * @return sum of products for a given overlap between two sub=series */ public double getSumOfProds(int startX, int startY, int length) { return crossProdsY[startX + length][startY + length] - crossProdsY[startX][startY]; } private double[][] computeCummSums(double[] currentSeries) { double[][] output = new double[2][]; output[0] = new double[currentSeries.length]; output[1] = new double[currentSeries.length]; output[0][0] = 0; output[1][0] = 0; //Compute stats for a given series instance for (int i = 1; i < currentSeries.length; i++) { output[0][i] = (double) (output[0][i - 1] + currentSeries[i - 1]); //Sum of vals output[1][i] = (double) (output[1][i - 1] + (currentSeries[i - 1] * currentSeries[i - 1])); //Sum of squared vals } return output; } private double[][] computeCrossProd(double[] x, double[] y) { //im assuming the starting from 1 with -1 is because of class values at the end. double[][] output = new double[x.length][y.length]; for (int u = 1; u < x.length; u++) { for (int v = 1; v < y.length; v++) { int t; //abs(u-v) if (v < u) { t = u - v; output[u][v] = (double) (output[u - 1][v - 1] + (x[v - 1 + t] * y[v - 1])); } else {//else v >= u t = v - u; output[u][v] = (double) (output[u - 1][v - 1] + (x[u - 1] * y[u - 1 + t])); } } } return output; } /** * A method to compute statistics for a given candidate series index and * normalised time series * * @param candidateInstIndex index of the candidate within the time * series database * @param data the normalised database of time series */ public void computeStats(int candidateInstIndex, double[][] data) { xIndex = candidateInstIndex; double[][] sums = computeCummSums(data[xIndex]); cummSumsX = sums[0]; cummSqSumsX = sums[1]; } } }
10,206
32.13961
130
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/OnlineShapeletDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; import java.util.Arrays; import tsml.transformers.shapelet_tools.Shapelet; import static utilities.rescalers.ZNormalisation.ROUNDING_ERROR_CORRECTION; import weka.core.Instance; /** * * @author raj09hxu */ public class OnlineShapeletDistance extends ShapeletDistance { protected double[][] sortedIndices; @Override public void setShapelet(Shapelet shp) { super.setShapelet(shp); sortedIndices = sortIndexes(cand.getShapeletContent()); } @Override public void setCandidate(Instance inst, int start, int length, int dim) { super.setCandidate(inst, start, length, dim); sortedIndices = sortIndexes(cand.getShapeletContent()); } //we take in a start pos, but we also start from 0. @Override public double calculate(double[] timeSeries, int timeSeriesId) { DoubleWrapper sumPointer = new DoubleWrapper(); DoubleWrapper sumsqPointer = new DoubleWrapper(); //Generate initial subsequence double[] subseq = new double[length]; System.arraycopy(timeSeries, 0, subseq, 0, subseq.length); subseq = zNormalise(subseq, false, sumPointer, sumsqPointer); //Keep count of fundamental ops for experiment double sum = sumPointer.get(); double sumsq = sumsqPointer.get(); double bestDist = 0.0; double temp; int bestPos =0; //Compute initial distance for (int i = 0; i < length; i++) { temp = cand.getShapeletContent()[i] - subseq[i]; bestDist = bestDist + (temp * temp); } double currentDist, start, end; // Scan through all possible subsequences of two for (int i = 1; i < timeSeries.length - length; i++) { //Update the running sums start = timeSeries[i - 1]; end = timeSeries[i - 1 + length]; //get rid of the start and add on the ends. sum = sum + end - start; sumsq = sumsq + (end * end) - (start * start); currentDist = calculateBestDistance(i, timeSeries, bestDist, sum, sumsq); if (currentDist < bestDist) { bestDist = currentDist; bestPos = i; } } bestDist = (bestDist == 0.0) ? 0.0 : (1.0 / length * bestDist); return bestDist; } protected double calculateBestDistance(int i, double[] timeSeries, double bestDist, double sum, double sum2) { //Compute the stats for new series double mean = sum / length; //Get rid of rounding errors double stdv2 = (sum2 - (mean * mean * length)) / length; double stdv = (stdv2 < ROUNDING_ERROR_CORRECTION) ? 0.0 : Math.sqrt(stdv2); //calculate the normalised distance between the series int j = 0; double currentDist = 0.0; double toAdd; int reordedIndex; double normalisedVal = 0.0; boolean dontStdv = (stdv == 0.0); while (j < length && currentDist < bestDist) { //count ops incrementCount(); reordedIndex = (int) sortedIndices[j][0]; //if our stdv isn't done then make it 0. normalisedVal = dontStdv ? 0.0 : ((timeSeries[i + reordedIndex] - mean) / stdv); toAdd = cand.getShapeletContent()[reordedIndex] - normalisedVal; currentDist = currentDist + (toAdd * toAdd); j++; } return currentDist; } /** * Z-Normalise a time series * * @param input the input time series to be z-normalised * @param classValOn specify whether the time series includes a class value * (e.g. an full instance might, a candidate shapelet wouldn't) * @param sum * @param sum2 * @return a z-normalised version of input */ final double[] zNormalise(double[] input, boolean classValOn, DoubleWrapper sum, DoubleWrapper sum2) { double mean; double stdv; double classValPenalty = classValOn ? 1 : 0; double[] output = new double[input.length]; double seriesTotal = 0; double seriesTotal2 = 0; for (int i = 0; i < input.length - classValPenalty; i++) { seriesTotal += input[i]; seriesTotal2 += (input[i] * input[i]); } if (sum != null && sum2 != null) { sum.set(seriesTotal); sum2.set(seriesTotal2); } mean = seriesTotal / (input.length - classValPenalty); double num = (seriesTotal2 - (mean * mean * (input.length - classValPenalty))) / (input.length - classValPenalty); stdv = (num <= ROUNDING_ERROR_CORRECTION) ? 0.0 : Math.sqrt(num); for (int i = 0; i < input.length - classValPenalty; i++) { output[i] = (stdv == 0.0) ? 0.0 : (input[i] - mean) / stdv; } if (classValOn) { output[output.length - 1] = input[input.length - 1]; } return output; } protected static class DoubleWrapper { private double d; public DoubleWrapper() { d = 0.0; } public DoubleWrapper(double d) { this.d = d; } public void set(double d) { this.d = d; } public double get() { return d; } } /** * A method to sort the array indeces according to their corresponding * values * * @param series a time series, which indeces need to be sorted * @return */ public static double[][] sortIndexes(double[] series) { //Create an boxed array of values with corresponding indexes double[][] sortedSeries = new double[series.length][2]; for (int i = 0; i < series.length; i++) { sortedSeries[i][0] = i; sortedSeries[i][1] = Math.abs(series[i]); } //this is the lamda expression. //Arrays.sort(sortedSeries, (double[] o1, double[] o2) -> Double.compare(o1[1],o2[1])); Arrays.sort(sortedSeries, (double[] o1, double[] o2) -> Double.compare(o2[1], o1[1])); return sortedSeries; } }
7,140
31.166667
122
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/distance_functions/ShapeletDistance.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.distance_functions; import java.io.Serializable; import weka.core.Instances; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.transformers.shapelet_tools.Shapelet; import tsml.transformers.shapelet_tools.ShapeletCandidate; import utilities.rescalers.SeriesRescaler; import utilities.rescalers.ZNormalisation; import weka.core.Instance; /** * * @author Aaron, who does not like commenting code * * this implements the basic functionality of sDist in various ways */ public class ShapeletDistance implements Serializable{ //Each enum represents a class in this package public enum DistanceType{ NORMAL, // Standard full scan (with early abandon) is this class ONLINE, // Faster normalisation for extracted subsequences (avoids a call to RescalerType IMPROVED_ONLINE, // online calculation with variable start and bespoke abandon SEE DAWAK PAPER CACHED, // Mueen's pre-cached version see Logical Shapelets paper ONLINE_CACHED, // Untested hybrid between online and caching, unpublished, TO REMOVE // These three are for multivariate DEPENDENT, // Uses pointwise distance over dimensions INDEPENDENT, // Uses the average over individual dimensions DIMENSION // Aaron's weird one: slide single series over all dimensions }; //And this? public enum RescalerType{NONE, STANDARDISATION, NORMALISATION}; //Should the seriesRescaler not depend on RescalerType?? public SeriesRescaler seriesRescaler = new ZNormalisation(); protected TimeSeriesInstance candidateTSInst; protected Instance candidateInst; protected double[] candidateArray; protected Shapelet shapelet; protected ShapeletCandidate cand; protected int seriesId; protected int startPos; protected int length; protected int dimension; protected long count; public void init(Instances data) { count =0; } public void init(TimeSeriesInstances data) { count =0; } final void incrementCount(){ count++;} public long getCount() {return count;} public ShapeletCandidate getCandidate(){ return cand; } public void setShapelet(Shapelet shp) { shapelet = shp; startPos = shp.startPos; cand = shp.getContent(); length = shp.getLength(); dimension = shp.getDimension(); } public void setCandidate(Instance inst, int start, int len, int dim) { //extract shapelet and nomrliase. cand = new ShapeletCandidate(); startPos = start; length = len; dimension = dim; //only call to double array when we've changed series. if(candidateInst==null || candidateInst != inst){ candidateArray = inst.toDoubleArray(); candidateInst = inst; } double[] temp = new double[length]; //copy the data from the whole series into a candidate. System.arraycopy(candidateArray, start, temp, 0, length); cand.setShapeletContent(temp); // znorm candidate here so it's only done once, rather than in each distance calculation cand.setShapeletContent(seriesRescaler.rescaleSeries(cand.getShapeletContent(), false)); } public void setCandidate(TimeSeriesInstance inst, int start, int len, int dim) { //extract shapelet and nomrliase. cand = new ShapeletCandidate(); startPos = start; length = len; dimension = dim; //only call to double array when we've changed series. if(candidateTSInst==null || candidateTSInst != inst){ candidateArray = inst.get(dimension).toValueArray(); candidateTSInst = inst; } double[] temp = inst.get(dimension).getVSliceArray(start, start+length); cand.setShapeletContent(temp); // znorm candidate here so it's only done once, rather than in each distance calculation cand.setShapeletContent(seriesRescaler.rescaleSeries(cand.getShapeletContent(), false)); } public void setSeries(int srsId) { seriesId = srsId; } public double calculate(Instance timeSeries, int timeSeriesId){ return calculate(timeSeries.toDoubleArray(), timeSeriesId); } public double calculate(TimeSeriesInstance timeSeriesInstance, int timeSeriesId) { return calculate(timeSeriesInstance.get(dimension).toValueArray(), timeSeriesId); } public double distanceToShapelet(Shapelet otherShapelet){ double temp; double sum = 0; for (int j = 0; j < length; j++) { temp = (cand.getShapeletContent()[j] - otherShapelet.getContent().getShapeletContent()[j]); sum = sum + (temp * temp); } double dist = (sum == 0.0) ? 0.0 : (1.0 / length * sum); return dist; } //we take in a start pos, but we also start from 0. public double calculate(double[] timeSeries, int timeSeriesId) { double bestSum = Double.MAX_VALUE; double sum; double[] subseq; double temp; for (int i = 0; i < timeSeries.length - length; i++) { sum = 0; // get subsequence of two that is the same lengh as one subseq = new double[length]; System.arraycopy(timeSeries, i, subseq, 0, length); subseq = seriesRescaler.rescaleSeries(subseq, false); // Z-NORM HERE for (int j = 0; j < length; j++) { //count ops count++; temp = (cand.getShapeletContent()[j] - subseq[j]); sum = sum + (temp * temp); } if (sum < bestSum) { bestSum = sum; } } double dist = (bestSum == 0.0) ? 0.0 : (1.0 / length * bestSum); return dist; } }
6,915
33.40796
106
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/FStat.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import utilities.class_counts.ClassCounts; import tsml.transformers.shapelet_tools.OrderLineObj; /** * * @author raj09hxu */ /** * A class for calculating the F-Statistic of a shapelet, according to the * set of distances from the shapelet to a dataset. */ public class FStat implements ShapeletQualityMeasure, Serializable { protected FStat(){ } /** * A method to calculate the quality of a FullShapeletTransform, given * the orderline produced by computing the distance from the shapelet to * each element of the dataset. * * @param orderline the pre-computed set of distances for a dataset to a * single shapelet * @param classDistribution the distibution of all possible class values * in the orderline * @return a measure of shapelet quality according to f-stat */ @Override public double calculateQuality(List<OrderLineObj> orderline, ClassCounts classDistribution) { Collections.sort(orderline); int numClasses = classDistribution.size(); int numInstances = orderline.size(); double[] sums = new double[numClasses]; double[] sumsSquared = new double[numClasses]; double[] sumOfSquares = new double[numClasses]; for (int i = 0; i < numClasses; i++) { sums[i] = 0; sumsSquared[i] = 0; sumOfSquares[i] = 0; } for (OrderLineObj orderline1 : orderline) { int c = (int) orderline1.getClassVal(); double thisDist = orderline1.getDistance(); sums[c] += thisDist; sumOfSquares[c] += thisDist * thisDist; } for (int i = 0; i < numClasses; i++) { sumsSquared[i] = sums[i] * sums[i]; } double ssTotal = 0; double part1 = 0; double part2 = 0; for (int i = 0; i < numClasses; i++) { part1 += sumOfSquares[i]; part2 += sums[i]; } part2 *= part2; part2 /= numInstances; ssTotal = part1 - part2; double ssAmoung = 0; part1 = 0; part2 = 0; for (int i = 0; i < numClasses; i++) { part1 += (double) sumsSquared[i] / classDistribution.get((double) i);//.data[i].size(); part2 += sums[i]; } ssAmoung = part1 - (part2 * part2) / numInstances; double ssWithin = ssTotal - ssAmoung; int dfAmoung = numClasses - 1; int dfWithin = numInstances - numClasses; double msAmoung = ssAmoung / dfAmoung; double msWithin = ssWithin / dfWithin; double f = msAmoung / msWithin; return Double.isNaN(f) ? 0.0 : f; } /** * * @param orderline * @param classDistribution * @return a va */ public double calculateQualityNew(List<OrderLineObj> orderline, Map<Double, Integer> classDistribution) { Collections.sort(orderline); int numClasses = classDistribution.size(); int numInstances = orderline.size(); double[] sums = new double[numClasses]; double[] sumsSquared = new double[numClasses]; double[] sumOfSquares = new double[numClasses]; for (int i = 0; i < orderline.size(); i++) { int c = (int) orderline.get(i).getClassVal(); double thisDist = orderline.get(i).getDistance(); sums[c] += thisDist; sumOfSquares[c] += thisDist * thisDist; } double ssTotal = 0; double part1 = 0; double part2 = 0; for (int i = 0; i < numClasses; i++) { sumsSquared[i] = sums[i] * sums[i]; part1 += sumOfSquares[i]; part2 += sums[i]; } part2 *= part2; part2 /= numInstances; ssTotal = part1 - part2; double ssAmoung = 0; part1 = 0; part2 = 0; for (int i = 0; i < numClasses; i++) { part1 += (double) sumsSquared[i] / classDistribution.get((double) i);//.data[i].size(); part2 += sums[i]; } ssAmoung = part1 - (part2 * part2) / numInstances; double ssWithin = ssTotal - ssAmoung; int dfAmoung = numClasses - 1; int dfWithin = numInstances - numClasses; double msAmoung = ssAmoung / dfAmoung; double msWithin = ssWithin / dfWithin; double f = msAmoung / msWithin; return f; } @Override public double calculateSeperationGap(List<OrderLineObj> orderline) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
6,173
32.372973
139
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/FStatBound.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.util.ArrayList; import java.util.Collections; import java.util.List; import utilities.class_counts.ClassCounts; import tsml.transformers.shapelet_tools.OrderLineObj; /** * * @author raj09hxu */ /** * A class for calculating the f-stat statistic bound of a shapelet, according to * the set of distances from the shapelet to a dataset. */ public class FStatBound extends ShapeletQualityBound{ private double[] sums; private double[] sumsSquared; private double[] sumOfSquares; private List<OrderLineObj> meanDistOrderLine; private double minDistance; private double maxDistance; /** * Constructor to construct FStatBound * @param classDist class distribution of the data currently being processed * @param percentage percentage of data required to be processed before * bounding mechanism is used. */ protected FStatBound(ClassCounts classDist, int percentage){ initParentFields(classDist, percentage); int numClasses = parentClassDist.size(); sums = new double[numClasses]; sumsSquared = new double[numClasses]; sumOfSquares = new double[numClasses]; meanDistOrderLine = new ArrayList<>(numClasses); minDistance = -1.0; maxDistance = -1.0; } @Override public void updateOrderLine(OrderLineObj orderLineObj){ super.updateOrderLine(orderLineObj); int c = (int) orderLineObj.getClassVal(); double thisDist = orderLineObj.getDistance(); sums[c] += thisDist; sumOfSquares[c] += thisDist * thisDist; sumsSquared[c] = sums[c] * sums[c]; //Update min/max distance observed so far if(orderLineObj.getDistance() != 0.0){ if(minDistance == -1 || minDistance > orderLineObj.getDistance()){ minDistance = orderLineObj.getDistance(); } if(maxDistance == -1 || maxDistance < orderLineObj.getDistance()){ maxDistance = orderLineObj.getDistance(); } } //Update mean distance orderline boolean isUpdated = false; for (OrderLineObj meanDistOrderLine1 : meanDistOrderLine) { if (meanDistOrderLine1.getClassVal() == orderLineObj.getClassVal()) { meanDistOrderLine1.setDistance(sums[(int)orderLineObj.getClassVal()] / orderLineClassDist.get(orderLineObj.getClassVal())); isUpdated = true; break; } } if(!isUpdated){ meanDistOrderLine.add(new OrderLineObj(sums[(int)orderLineObj.getClassVal()] / orderLineClassDist.get(orderLineObj.getClassVal()), orderLineObj.getClassVal())); } } /** * Method to calculate the quality bound for the current orderline * @return F-stat statistic bound */ @Override public double calculateBestQuality() { int numClasses = parentClassDist.size(); //Sort the mean distance orderline Collections.sort(meanDistOrderLine); //Find approximate minimum orderline objects OrderLineObj min = new OrderLineObj(-1.0, 0.0); for(Double d : parentClassDist.keySet()){ int unassignedObjs = parentClassDist.get(d) - orderLineClassDist.get(d); double distMin = (sums[d.intValue()] + (unassignedObjs * minDistance)) / parentClassDist.get(d); if(min.getDistance() == -1.0 || distMin < min.getDistance()){ min.setDistance(distMin); min.setClassVal(d); } } //Find approximate maximum orderline objects OrderLineObj max = new OrderLineObj(-1.0, 0.0); for(Double d : parentClassDist.keySet()){ int unassignedObjs = parentClassDist.get(d) - orderLineClassDist.get(d); double distMax = (sums[d.intValue()] + (unassignedObjs * maxDistance)) / parentClassDist.get(d); if(d != min.getClassVal() && (max.getDistance() == -1.0 || distMax > max.getDistance())){ max.setDistance(distMax); max.setClassVal(d); } } //Adjust running sums double increment = (max.getDistance() - min.getDistance()) / (numClasses-1); int multiplyer = 1; for (OrderLineObj currentObj : meanDistOrderLine) { double thisDist; int unassignedObjs = parentClassDist.get(currentObj.getClassVal()) - orderLineClassDist.get(currentObj.getClassVal()); if(currentObj.getClassVal() == min.getClassVal()){ thisDist = minDistance; }else if(currentObj.getClassVal() == max.getClassVal()){ thisDist = maxDistance; }else{ thisDist = minDistance + (increment * multiplyer); multiplyer++; } sums[(int)currentObj.getClassVal()] += thisDist * unassignedObjs; sumOfSquares[(int)currentObj.getClassVal()] += thisDist * thisDist * unassignedObjs; sumsSquared[(int)currentObj.getClassVal()] = sums[(int)currentObj.getClassVal()] * sums[(int)currentObj.getClassVal()]; } double ssTotal; double part1 = 0; double part2 = 0; for (int i = 0; i < numClasses; i++) { part1 += sumOfSquares[i]; part2 += sums[i]; } part2 *= part2; part2 /= numInstances; ssTotal = part1 - part2; double ssAmoung; part1 = 0; part2 = 0; for (int i = 0; i < numClasses; i++) { part1 += (double) sumsSquared[i] / parentClassDist.get((double) i);//.data[i].size(); part2 += sums[i]; } ssAmoung = part1 - (part2 * part2) / numInstances; double ssWithin = ssTotal - ssAmoung; int dfAmoung = numClasses - 1; int dfWithin = numInstances - numClasses; double msAmoung = ssAmoung / dfAmoung; double msWithin = ssWithin / dfWithin; double f = msAmoung / msWithin; //Reset running sums multiplyer = 1; for (OrderLineObj currentObj : meanDistOrderLine) { double thisDist; int unassignedObjs = parentClassDist.get(currentObj.getClassVal()) - orderLineClassDist.get(currentObj.getClassVal()); if(currentObj.getClassVal() == min.getClassVal()){ thisDist = minDistance; }else if(currentObj.getClassVal() == max.getClassVal()){ thisDist = maxDistance; }else{ thisDist = minDistance + (increment * multiplyer); multiplyer++; } sums[(int)currentObj.getClassVal()] -= thisDist * unassignedObjs; sumOfSquares[(int)currentObj.getClassVal()] -= thisDist * thisDist * unassignedObjs; sumsSquared[(int)currentObj.getClassVal()] = sums[(int)currentObj.getClassVal()] * sums[(int)currentObj.getClassVal()]; } return Double.isNaN(f) ? 0.0 : f; } @Override public boolean pruneCandidate(){ if(orderLine.size() % parentClassDist.size() != 0){ return false; }else{ return super.pruneCandidate(); } } }
8,959
40.674419
176
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/InformationGain.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.List; import utilities.class_counts.ClassCounts; import utilities.class_counts.TreeSetClassCounts; import tsml.transformers.shapelet_tools.OrderLineObj; /** * * @author raj09hxu */ /** * A class for calculating the information gain of a shapelet, according to * the set of distances from the shapelet to a dataset. */ public class InformationGain implements ShapeletQualityMeasure, Serializable { protected InformationGain(){ } /** * A method to calculate the quality of a FullShapeletTransform, given * the orderline produced by computing the distance from the shapelet to * each element of the dataset. * * @param orderline the pre-computed set of distances for a dataset to a * single shapelet * @param classDistribution the distibution of all possible class values * in the orderline * @return a measure of shapelet quality according to information gain */ @Override public double calculateQuality(List<OrderLineObj> orderline, ClassCounts classDistribution) { Collections.sort(orderline); // for each split point, starting between 0 and 1, ending between end-1 and end // addition: track the last threshold that was used, don't bother if it's the same as the last one double lastDist = -1;//orderline.get(0).getDistance(); // must be initialised as not visited(no point breaking before any data!) double thisDist = -1; double bsfGain = -1; double threshold = -1; // initialise class counts ClassCounts lessClasses = new TreeSetClassCounts(); ClassCounts greaterClasses = new TreeSetClassCounts(); // parent entropy will always be the same, so calculate just once double parentEntropy = entropy(classDistribution); int sumOfAllClasses = 0; for (double j : classDistribution.keySet()) { lessClasses.put(j, 0); greaterClasses.put(j, classDistribution.get(j)); sumOfAllClasses += classDistribution.get(j); } int sumOfLessClasses = 0; int sumOfGreaterClasses = sumOfAllClasses; double thisClassVal; int oldCount; for (OrderLineObj ol : orderline) { thisDist = ol.getDistance(); //move the threshold along one (effectively by adding this dist to lessClasses thisClassVal = ol.getClassVal(); oldCount = lessClasses.get(thisClassVal) + 1; lessClasses.put(thisClassVal, oldCount); oldCount = greaterClasses.get(thisClassVal) - 1; greaterClasses.put(thisClassVal, oldCount); // adjust counts - maybe makes more sense if these are called counts, rather than sums! sumOfLessClasses++; sumOfGreaterClasses--; // check to see if the threshold has moved (ie if thisDist isn't the same as lastDist) // important, else gain calculations will be made 'in the middle' of a threshold, resulting in different info gain for // the split point, that won't actually be valid as it is 'on' a distances, rather than 'between' them/ if (thisDist != lastDist) { // calculate the info gain below the threshold double lessFrac = (double) sumOfLessClasses / sumOfAllClasses; double entropyLess = entropy(lessClasses); // calculate the info gain above the threshold double greaterFrac = (double) sumOfGreaterClasses / sumOfAllClasses; double entropyGreater = entropy(greaterClasses); double gain = parentEntropy - lessFrac * entropyLess - greaterFrac * entropyGreater; if (gain > bsfGain) { bsfGain = gain; threshold = (thisDist - lastDist) / 2 + lastDist; } } lastDist = thisDist; } return bsfGain; } public static double calculateSplitThreshold(List<OrderLineObj> orderline, ClassCounts classDistribution){ Collections.sort(orderline); // for each split point, starting between 0 and 1, ending between end-1 and end // addition: track the last threshold that was used, don't bother if it's the same as the last one double lastDist = orderline.get(0).getDistance(); // must be initialised as not visited(no point breaking before any data!) double thisDist = 0; double bsfGain = -1; double threshold = 1; // initialise class counts ClassCounts lessClasses = new TreeSetClassCounts(); ClassCounts greaterClasses = new TreeSetClassCounts(); // parent entropy will always be the same, so calculate just once double parentEntropy = entropy(classDistribution); int sumOfAllClasses = 0; for (double j : classDistribution.keySet()) { lessClasses.put(j, 0); greaterClasses.put(j, classDistribution.get(j)); sumOfAllClasses += classDistribution.get(j); } int sumOfLessClasses = 0; int sumOfGreaterClasses = sumOfAllClasses; double thisClassVal; int oldCount; for (OrderLineObj ol : orderline) { thisDist = ol.getDistance(); //move the threshold along one (effectively by adding this dist to lessClasses thisClassVal = ol.getClassVal(); oldCount = lessClasses.get(thisClassVal) + 1; lessClasses.put(thisClassVal, oldCount); oldCount = greaterClasses.get(thisClassVal) - 1; greaterClasses.put(thisClassVal, oldCount); // adjust counts - maybe makes more sense if these are called counts, rather than sums! sumOfLessClasses++; sumOfGreaterClasses--; // check to see if the threshold has moved (ie if thisDist isn't the same as lastDist) // important, else gain calculations will be made 'in the middle' of a threshold, resulting in different info gain for // the split point, that won't actually be valid as it is 'on' a distances, rather than 'between' them/ if (thisDist != lastDist) { // calculate the info gain below the threshold double lessFrac = (double) sumOfLessClasses / sumOfAllClasses; double entropyLess = entropy(lessClasses); // calculate the info gain above the threshold double greaterFrac = (double) sumOfGreaterClasses / sumOfAllClasses; double entropyGreater = entropy(greaterClasses); double gain = parentEntropy - lessFrac * entropyLess - greaterFrac * entropyGreater; if (gain > bsfGain) { bsfGain = gain; threshold = (thisDist - lastDist) / 2 + lastDist; } } lastDist = thisDist; } return threshold; } public static double entropy(ClassCounts classDistributions) { if (classDistributions.size() == 1) { return 0; } double thisPart; double toAdd; int total = 0; //Aaron: should be simpler than iterating using the keySet. //Values is backed by the Map so it doesn't need to be constructed. Collection<Integer> values = classDistributions.values(); for (Integer d : values) { total += d; } // to avoid NaN calculations, the individual parts of the entropy are calculated and summed. // i.e. if there is 0 of a class, then that part would calculate as NaN, but this can be caught and // set to 0. //Aaron: Instead of using the keyset to loop through, use the underlying Array to iterate through, ordering of calculations doesnt matter. //just that we do them all. so i think previously it was n log n, now should be just n. double entropy = 0; for (Integer d : values) { thisPart = (double) d / total; toAdd = -thisPart * Math.log10(thisPart) / Math.log10(2); //Aaron: if its not NaN we can add it, if it was NaN we'd just add 0. if (!Double.isNaN(toAdd)) { entropy += toAdd; } } return entropy; } @Override public double calculateSeperationGap(List<OrderLineObj> orderline) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
10,357
41.801653
151
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/InformationGainBound.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.util.Map; import java.util.TreeMap; import utilities.class_counts.ClassCounts; import utilities.class_counts.TreeSetClassCounts; /** * * @author raj09hxu */ public class InformationGainBound extends ShapeletQualityBound{ private double parentEntropy; boolean isExact; /** * Constructor to construct InformationGainBound * @param classDist class distribution of the data currently being processed * @param percentage percentage of data required to be processed before * bounding mechanism is used. * * @param isExact * */ protected InformationGainBound(ClassCounts classDist, int percentage, boolean isExact){ initParentFields(classDist, percentage); this.isExact = isExact; parentEntropy = InformationGain.entropy(parentClassDist); } protected InformationGainBound(ClassCounts classDist, int percentage){ this(classDist,percentage,false); } /** * Method to calculate the quality bound for the current orderline * @return information gain bound */ @Override protected double calculateBestQuality(){ Map<Double, Boolean> perms = new TreeMap<>(); double bsfGain = -1; //Cycle through all permutations if(isExact){ //Initialise perms for(Double key : orderLineClassDist.keySet()){ perms.put(key, Boolean.TRUE); } for(int totalCycles = perms.keySet().size(); totalCycles > 1; totalCycles--){ for(int cycle = 0; cycle < totalCycles; cycle++){ int start = 0, count = 0; for(Double key : perms.keySet()){ Boolean val = Boolean.TRUE; if(cycle == start){ val = Boolean.FALSE; int size = perms.keySet().size(); if(totalCycles < size && count < (size - totalCycles)){ count++; start--; } } perms.put(key, val); start++; } //Check quality of current permutation double currentGain = computeIG(perms); if(currentGain > bsfGain){ bsfGain = currentGain; } if(bsfGain > bsfQuality){ break; } } } }else{ double currentGain = computeIG(null); if(currentGain > bsfGain){ bsfGain = currentGain; } } return bsfGain; } private double computeIG(Map<Double, Boolean> perm){ //Initialise class counts TreeSetClassCounts lessClasses = new TreeSetClassCounts(); TreeSetClassCounts greaterClasses = new TreeSetClassCounts(); TreeMap<Double, Boolean> isShifted = new TreeMap<>(); int countOfAllClasses = 0; int countOfLessClasses = 0; int countOfGreaterClasses = 0; for(double j : parentClassDist.keySet()){ int lessVal =0; int greaterVal = parentClassDist.get(j); if(perm != null){ if(perm.get(j) != null && perm.get(j)){ lessVal = parentClassDist.get(j) - orderLineClassDist.get(j); greaterVal = orderLineClassDist.get(j); } countOfLessClasses += lessClasses.get(j); //Assign everything to the right for fast bound }else{ isShifted.put(j, Boolean.FALSE); } lessClasses.put(j, lessVal); greaterClasses.put(j, greaterVal); countOfGreaterClasses += greaterClasses.get(j); countOfAllClasses += parentClassDist.get(j); } double bsfGain = -1; double lastDist = -1; double thisDist; double thisClassVal; int oldCount; for(int i = 0; i < orderLine.size()-1; i++){ thisDist = orderLine.get(i).getDistance(); thisClassVal = orderLine.get(i).getClassVal(); //move the threshold along one (effectively by adding this dist to lessClasses oldCount = lessClasses.get(thisClassVal)+1; lessClasses.put(thisClassVal,oldCount); oldCount = greaterClasses.get(thisClassVal)-1; greaterClasses.put(thisClassVal,oldCount); // adjust counts - maybe makes more sense if these are called counts, rather than sums! countOfLessClasses++; countOfGreaterClasses--; //For fast bound dynamically shift the unassigned objects when majority side changes if(!isExact){ //Check if shift has not already happened if(!isShifted.get(thisClassVal)){ int greaterCount = greaterClasses.get(thisClassVal) - (parentClassDist.get(thisClassVal) - orderLineClassDist.get(thisClassVal)); int lessCount = lessClasses.get(thisClassVal); //Check if shift has happened if(lessCount - greaterCount > 0){ greaterClasses.put(thisClassVal, greaterClasses.get(thisClassVal) - (parentClassDist.get(thisClassVal) - orderLineClassDist.get(thisClassVal))); countOfGreaterClasses -= parentClassDist.get(thisClassVal) - orderLineClassDist.get(thisClassVal); lessClasses.put(thisClassVal, lessClasses.get(thisClassVal) + (parentClassDist.get(thisClassVal) - orderLineClassDist.get(thisClassVal))); countOfLessClasses += parentClassDist.get(thisClassVal) - orderLineClassDist.get(thisClassVal); isShifted.put(thisClassVal, Boolean.TRUE); } } } // check to see if the threshold has moved (ie if thisDist isn't the same as lastDist) // important, else gain calculations will be made 'in the middle' of a threshold, resulting in different info gain for // the split point, that won't actually be valid as it is 'on' a distances, rather than 'between' them/ if(thisDist != lastDist){ // calculate the info gain below the threshold double lessFrac =(double) countOfLessClasses / countOfAllClasses; double entropyLess = InformationGain.entropy(lessClasses); // calculate the info gain above the threshold double greaterFrac =(double) countOfGreaterClasses / countOfAllClasses; double entropyGreater = InformationGain.entropy(greaterClasses); double gain = parentEntropy - lessFrac * entropyLess - greaterFrac * entropyGreater; if(gain > bsfGain){ bsfGain = gain; } } lastDist = thisDist; } return bsfGain; } @Override public boolean pruneCandidate(){ //Check if we at least have observed an object from each class if(orderLine.size() % parentClassDist.size() != 0){ return false; }else{ return super.pruneCandidate(); } } }
9,219
42.286385
172
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/KruskalWallis.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.io.Serializable; import java.util.Collections; import java.util.List; import utilities.class_counts.ClassCounts; import tsml.transformers.shapelet_tools.OrderLineObj; /** * * @author raj09hxu */ /** * A class for calculating the Kruskal-Wallis statistic of a shapelet, * according to the set of distances from the shapelet to a dataset. */ public class KruskalWallis implements ShapeletQualityMeasure, Serializable { protected KruskalWallis(){} /** * A method to calculate the quality of a FullShapeletTransform, given * the orderline produced by computing the distance from the shapelet to * each element of the dataset. * * @param orderline the pre-computed set of distances for a dataset to a * single shapelet * @param classDistribution the distibution of all possible class values * in the orderline * @return a measure of shapelet quality according to Kruskal-Wallis */ @Override public double calculateQuality(List<OrderLineObj> orderline, ClassCounts classDistribution) { // sort Collections.sort(orderline); int numClasses = classDistribution.size(); int[] classRankCounts = new int[numClasses]; double[] classRankMeans = new double[numClasses]; double lastDistance = orderline.get(0).getDistance(); double thisDistance = lastDistance; double classVal = orderline.get(0).getClassVal(); classRankCounts[(int) classVal] += 1; int duplicateCount = 0; for (int i = 1; i < orderline.size(); i++) { thisDistance = orderline.get(i).getDistance(); if (duplicateCount == 0 && thisDistance != lastDistance) { // standard entry classRankCounts[(int) orderline.get(i).getClassVal()] += i + 1; } else if (duplicateCount > 0 && thisDistance != lastDistance) { // non-duplicate following duplicates // set ranks for dupicates double minRank = i - duplicateCount; double maxRank = i; double avgRank = (minRank + maxRank) / 2; for (int j = i - duplicateCount - 1; j < i; j++) { classRankCounts[(int) orderline.get(j).getClassVal()] += avgRank; } duplicateCount = 0; // then set this rank classRankCounts[(int) orderline.get(i).getClassVal()] += i + 1; } else {// thisDistance==lastDistance if (i == orderline.size() - 1) { // last one so must do the avg ranks here (basically copied from above, BUT includes this element too now) double minRank = i - duplicateCount; double maxRank = i + 1; double avgRank = (minRank + maxRank) / 2; for (int j = i - duplicateCount - 1; j <= i; j++) { classRankCounts[(int) orderline.get(j).getClassVal()] += avgRank; } } duplicateCount++; } lastDistance = thisDistance; } //3) overall mean rank double overallMeanRank = (1.0 + orderline.size()) / 2; //4) sum of squared deviations from the overall mean rank double s = 0; for (int i = 0; i < numClasses; i++) { classRankMeans[i] = (double) classRankCounts[i] / classDistribution.get((double) i); s += classDistribution.get((double) i) * (classRankMeans[i] - overallMeanRank) * (classRankMeans[i] - overallMeanRank); } //5) weight s with the scale factor double h = 12.0 / (orderline.size() * (orderline.size() + 1)) * s; return h; } @Override public double calculateSeperationGap(List<OrderLineObj> orderline) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
5,265
38.593985
139
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/KruskalWallisBound.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.util.ArrayList; import java.util.Collections; import utilities.class_counts.ClassCounts; import tsml.transformers.shapelet_tools.OrderLineObj; /** * * @author raj09hxu */ /** * A class for calculating the Kruskal Wallis statistic bound of a shapelet, according to * the set of distances from the shapelet to a dataset. */ public class KruskalWallisBound extends ShapeletQualityBound{ /** * Constructor to construct KruskalWallisBound * @param classDist class distribution of the data currently being processed * @param percentage percentage of data required to be processed before * bounding mechanism is used. */ protected KruskalWallisBound(ClassCounts classDist, int percentage){ initParentFields(classDist, percentage); } @Override public void updateOrderLine(OrderLineObj orderLineObj){ super.updateOrderLine(orderLineObj); numInstances--; } /** * Method to calculate the quality bound for the current orderline * @return Kruskal Wallis statistic bound */ @Override protected double calculateBestQuality() { //1) Find sums of ranks for the observed orderline objects int numClasses = parentClassDist.size(); int[] classRankCounts = new int[numClasses]; double minimumRank = -1.0; double maximumRank = -1.0; double lastDistance = orderLine.get(0).getDistance(); double thisDistance; double classVal = orderLine.get(0).getClassVal(); classRankCounts[(int)classVal]+=1; int duplicateCount = 0; for(int i=1; i< orderLine.size(); i++){ thisDistance = orderLine.get(i).getDistance(); if(duplicateCount == 0 && thisDistance!=lastDistance){ // standard entry classRankCounts[(int)orderLine.get(i).getClassVal()]+=i+1; //Set min/max ranks if(thisDistance > 0.0 && minimumRank == -1.0){ minimumRank = i+1; } maximumRank = i+1; }else if(duplicateCount > 0 && thisDistance!=lastDistance){ // non-duplicate following duplicates // set ranks for dupicates double minRank = i-duplicateCount; double maxRank = i; double avgRank = (minRank+maxRank)/2; for(int j = i-duplicateCount-1; j < i; j++){ classRankCounts[(int)orderLine.get(j).getClassVal()]+=avgRank; } duplicateCount = 0; // then set this rank classRankCounts[(int)orderLine.get(i).getClassVal()]+=i+1; //Set min/max ranks if(thisDistance > 0.0 && minimumRank == -1.0){ minimumRank = i+1; } maximumRank = i+1; } else{// thisDistance==lastDistance if(i == orderLine.size() - 1){ // last one so must do the avg ranks here (basically copied from above, BUT includes this element too now) double minRank = i-duplicateCount; double maxRank = i+1; double avgRank = (minRank+maxRank)/2; for(int j = i-duplicateCount-1; j <= i; j++){ classRankCounts[(int)orderLine.get(j).getClassVal()]+=avgRank; } //Set min/max ranks if(thisDistance > 0.0 && minimumRank == -1.0){ minimumRank = avgRank; } maximumRank = avgRank; } duplicateCount++; } lastDistance = thisDistance; } // 2) Compute mean rank for the obsereved objects ArrayList<OrderLineObj> meanRankOrderLine = new ArrayList<>(); for(int i = 0; i < numClasses; i++){ meanRankOrderLine.add(new OrderLineObj((double)classRankCounts[i]/orderLineClassDist.get((double)i), (double)i)); } Collections.sort(meanRankOrderLine); //Find approximate minimum orderline objects OrderLineObj min = new OrderLineObj(-1.0, 0.0); for (OrderLineObj meanRankOrderLine1 : meanRankOrderLine) { classVal = meanRankOrderLine1.getClassVal(); int unassignedObjs = parentClassDist.get(classVal) - orderLineClassDist.get(classVal); double observed = classRankCounts[(int)classVal]; double predicted = minimumRank * unassignedObjs; double approximateRank = (observed + predicted) / parentClassDist.get(classVal); if(min.getDistance() == -1.0 || approximateRank < min.getDistance()){ min.setDistance(approximateRank); min.setClassVal(classVal); } } //Find approximate maximum orderline objects OrderLineObj max = new OrderLineObj(-1.0, 0.0); for (OrderLineObj meanRankOrderLine1 : meanRankOrderLine) { classVal = meanRankOrderLine1.getClassVal(); int unassignedObjs = parentClassDist.get(classVal) - orderLineClassDist.get(classVal); double observed = classRankCounts[(int)classVal]; double predicted = maximumRank * unassignedObjs; double approximateRank = (observed + predicted) / parentClassDist.get(classVal); if(classVal != min.getClassVal() && (max.getDistance() == -1.0 || approximateRank > max.getDistance())){ max.setDistance(approximateRank); max.setClassVal(classVal); } } //3) overall mean rank double overallMeanRank = (1.0+ orderLine.size() + numInstances)/2; //4) Interpolate mean ranks double increment = (max.getDistance() - min.getDistance()) / (numClasses-1); int multiplyer = 1; for (OrderLineObj currentObj : meanRankOrderLine) { int unassignedObjs = parentClassDist.get(currentObj.getClassVal()) - orderLineClassDist.get(currentObj.getClassVal()); if(currentObj.getClassVal() == min.getClassVal()){ currentObj.setDistance(min.getDistance()); }else if(currentObj.getClassVal() == max.getClassVal()){ currentObj.setDistance(max.getDistance()); }else{ classVal = currentObj.getClassVal(); double observed = classRankCounts[(int)classVal]; double predicted = (minimumRank + (increment * multiplyer)) * unassignedObjs; double approximateRank = (observed + predicted) / parentClassDist.get(classVal); currentObj.setDistance(approximateRank); multiplyer++; } } //5) sum of squared deviations from the overall mean rank double s = 0; for(int i = 0; i < numClasses; i++){ s+= parentClassDist.get((double)i)*(meanRankOrderLine.get(i).getDistance() -overallMeanRank)*(meanRankOrderLine.get(i).getDistance() -overallMeanRank); } //6) weight s with the scale factor int totalInstances = orderLine.size() + numInstances; double h = 12.0/(totalInstances*(totalInstances+1))*s; return h; } @Override public boolean pruneCandidate(){ if(orderLine.size() % parentClassDist.size() != 0){ return false; }else{ return super.pruneCandidate(); } } }
9,130
43.759804
167
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/MoodsMedian.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.io.Serializable; import java.util.Collections; import java.util.List; import utilities.class_counts.ClassCounts; import tsml.transformers.shapelet_tools.OrderLineObj; /** * * @author raj09hxu */ /** * A class for calculating the Mood's Median statistic of a shapelet, * according to the set of distances from the shapelet to a dataset. */ public class MoodsMedian implements ShapeletQualityMeasure, Serializable { protected MoodsMedian(){} /** * A method to calculate the quality of a FullShapeletTransform, given * the orderline produced by computing the distance from the shapelet to * each element of the dataset. * * @param orderline the pre-computed set of distances for a dataset to a * single shapelet * @param classDistributions the distibution of all possible class * values in the orderline * @return a measure of shapelet quality according to Mood's Median */ @Override public double calculateQuality(List<OrderLineObj> orderline, ClassCounts classDistributions) { //naive implementation as a benchmark for finding median - actually faster than manual quickSelect! Probably due to optimised java implementation Collections.sort(orderline); int lengthOfOrderline = orderline.size(); double median; if (lengthOfOrderline % 2 == 0) { median = (orderline.get(lengthOfOrderline / 2 - 1).getDistance() + orderline.get(lengthOfOrderline / 2).getDistance()) / 2; } else { median = orderline.get(lengthOfOrderline / 2).getDistance(); } int totalCount = orderline.size(); int countBelow = 0; int countAbove = 0; int numClasses = classDistributions.size(); int[] classCountsBelowMedian = new int[numClasses]; int[] classCountsAboveMedian = new int[numClasses]; double distance; double classVal; int countSoFar; for (OrderLineObj orderline1 : orderline) { distance = orderline1.getDistance(); classVal = orderline1.getClassVal(); if (distance < median) { countBelow++; classCountsBelowMedian[(int) classVal]++; } else { countAbove++; classCountsAboveMedian[(int) classVal]++; } } double chi = 0; double expectedAbove, expectedBelow; for (int i = 0; i < numClasses; i++) { expectedBelow = (double) (countBelow * classDistributions.get((double) i)) / totalCount; chi += ((classCountsBelowMedian[i] - expectedBelow) * (classCountsBelowMedian[i] - expectedBelow)) / expectedBelow; expectedAbove = (double) (countAbove * classDistributions.get((double) i)) / totalCount; chi += ((classCountsAboveMedian[i] - expectedAbove)) * (classCountsAboveMedian[i] - expectedAbove) / expectedAbove; } if (Double.isNaN(chi)) { chi = 0; // fix for cases where the shapelet is a straight line and chi is calc'd as NaN } return chi; } @Override public double calculateSeperationGap(List<OrderLineObj> orderline) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
4,574
38.102564
157
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/MoodsMedianBound.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import utilities.class_counts.ClassCounts; import utilities.class_counts.SimpleClassCounts; import tsml.transformers.shapelet_tools.OrderLineObj; /** * A class for calculating the moods median statistic bound of a shapelet, according to * the set of distances from the shapelet to a dataset. */ public class MoodsMedianBound extends ShapeletQualityBound{ /** * Constructor to construct MoodsMedianBound * @param classDist class distribution of the data currently being processed * @param percentage percentage of data required to be processed before * bounding mechanism is used. */ protected MoodsMedianBound(ClassCounts classDist, int percentage){ initParentFields(classDist, percentage); } /** * Method to calculate the quality bound for the current orderline * @return Moods Median statistic bound */ @Override protected double calculateBestQuality(){ int lengthOfOrderline = orderLine.size(); double median; if(lengthOfOrderline%2==0){ median = (orderLine.get(lengthOfOrderline/2-1).getDistance()+orderLine.get(lengthOfOrderline/2).getDistance())/2; }else{ median = orderLine.get(lengthOfOrderline/2).getDistance(); } int totalCount = orderLine.size(); int countBelow = 0; int countAbove = 0; int numClasses = parentClassDist.size(); ClassCounts classCountsBelowMedian = new SimpleClassCounts(numClasses); ClassCounts classCountsAboveMedian = new SimpleClassCounts(numClasses); double distance; double classVal; // Count observed class distributions above and below the median for (OrderLineObj orderLine1 : orderLine) { distance = orderLine1.getDistance(); classVal = orderLine1.getClassVal(); if(distance < median){ countBelow++; classCountsBelowMedian.addTo(classVal, 1); //increment by 1 }else{ countAbove++; classCountsAboveMedian.addTo(classVal, 1); } } // Add count of predicted class distributions above and below the median for(double key : orderLineClassDist.keySet()){ int predictedCount = parentClassDist.get(key) - orderLineClassDist.get(key); if(classCountsBelowMedian.get(key) <= classCountsAboveMedian.get(key)){ classCountsAboveMedian.addTo(key, predictedCount); countAbove += predictedCount; }else{ classCountsBelowMedian.addTo(key, predictedCount); countBelow += predictedCount; } totalCount += predictedCount; } double chi = 0; double expectedAbove = 0, expectedBelow; for(int i = 0; i < numClasses; i++){ expectedBelow = (double)(countBelow*parentClassDist.get((double)i))/totalCount; double classCountsBelow = classCountsBelowMedian.get(i) - expectedBelow; double classCountsAbove = classCountsAboveMedian.get(i) - expectedAbove; chi += (classCountsBelow*classCountsBelow)/expectedBelow; expectedAbove = (double)(countAbove*parentClassDist.get((double)i))/totalCount; chi += (classCountsAbove*classCountsAbove)/expectedAbove; } if(Double.isNaN(chi)){ chi = 0; // fix for cases where the shapelet is a straight line and chi is calc'd as NaN } return chi; } @Override public boolean pruneCandidate(){ if(orderLine.size() % parentClassDist.size() != 0){//if(orderLine.size() < parentClassDist.size()){ return false; }else{ return super.pruneCandidate(); } } }
5,077
40.966942
129
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/ShapeletQuality.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Supplier; import tsml.transformers.shapelet_tools.OrderLineObj; import utilities.class_counts.ClassCounts; /** * * @author Aaron Bostrom and comments added by Tony, because Aaron doesnt do comments :) * a container class for a ShapeletQualityMeasure and an optional bounding class. * it is not clear to me what the bounding class does. I *think* it is a (massively over complex) * way of bounding inclusion or not, so shapelet has to surpass a certain bound to be included */ public class ShapeletQuality { public enum ShapeletQualityChoice { /** * Used to specify that the filter will use Information Gain as the * shapelet quality measure (introduced in Ye & Keogh 2009) */ INFORMATION_GAIN, /** * Used to specify that the filter will use F-Stat as the shapelet * quality measure (introduced in Lines et. al 2012) */ F_STAT, /** * Used to specify that the filter will use Kruskal-Wallis as the * shapelet quality measure (introduced in Lines and Bagnall 2012) */ KRUSKALL_WALLIS, /** * Used to specify that the filter will use Mood's Median as the * shapelet quality measure (introduced in Lines and Bagnall 2012) */ MOODS_MEDIAN } public ShapeletQualityChoice getChoice() { return choice; } public ShapeletQualityMeasure getQualityMeasure() { return qualityMeasure; } public Optional<ShapeletQualityBound> getBound() { return bound; } ShapeletQualityChoice choice; ShapeletQualityMeasure qualityMeasure; Optional<ShapeletQualityBound> bound = Optional.empty(); //init static lists of constructors. private static final List<Supplier<ShapeletQualityMeasure>> qualityConstructors = createQuality(); private static final List<BiFunction<ClassCounts, Integer, ShapeletQualityBound>> boundConstructor = createBound(); private static List<Supplier<ShapeletQualityMeasure>> createQuality(){ List<Supplier<ShapeletQualityMeasure>> cons = new ArrayList<>(); cons.add(InformationGain::new); cons.add(FStat::new); cons.add(KruskalWallis::new); cons.add(MoodsMedian::new); return cons; } private static List<BiFunction<ClassCounts, Integer, ShapeletQualityBound>> createBound(){ List<BiFunction<ClassCounts, Integer, ShapeletQualityBound>> cons = new ArrayList<>(); cons.add(InformationGainBound::new); cons.add(FStatBound::new); cons.add(KruskalWallisBound::new); cons.add(MoodsMedianBound::new); return cons; } public ShapeletQuality(ShapeletQualityChoice choice){ this.choice = choice; qualityMeasure = qualityConstructors.get(choice.ordinal()).get(); } public void initQualityBound(ClassCounts classDist, int percentage){ bound = Optional.of(boundConstructor.get(choice.ordinal()).apply(classDist, percentage)); } public void setBsfQuality(double bsf){ bound.ifPresent(shapeletQualityBound -> shapeletQualityBound.setBsfQuality(bsf)); } public boolean pruneCandidate(){ return bound.isPresent() && bound.get().pruneCandidate(); } public void updateOrderLine(OrderLineObj obj){ bound.ifPresent(shapeletQualityBound -> shapeletQualityBound.updateOrderLine(obj)); } }
4,447
35.162602
120
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/ShapeletQualityBound.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import tsml.transformers.shapelet_tools.OrderLineObj; import utilities.class_counts.ClassCounts; import utilities.class_counts.TreeSetClassCounts; /** * * @author raj09hxu */ public abstract class ShapeletQualityBound implements Serializable { /** * Best quality observed so far, which is used for determining if the * candidate can be pruned */ protected double bsfQuality; /** * Orderline of the observed distance, class pairs */ protected List<OrderLineObj> orderLine; /** * Class distribution of the observed distance, class pairs */ protected ClassCounts orderLineClassDist; /** * Class distribution of the dataset, which currently being processed */ protected ClassCounts parentClassDist; /** * Number of instances in the dataset, which is currently being processed */ protected int numInstances; /** * The percentage of data point that must be in the observed orderline * before the bounding mechanism is can be invoked */ protected int percentage; /** * * @param classDist * @param percentage */ protected void initParentFields(ClassCounts classDist, int percentage) { //Initialize the fields bsfQuality = Double.MAX_VALUE; orderLine = new ArrayList<>(); orderLineClassDist = new TreeSetClassCounts(); parentClassDist = classDist; this.percentage = percentage; //Initialize orderline class distribution numInstances = 0; for (Double key : parentClassDist.keySet()) { orderLineClassDist.put(key, 0); numInstances += parentClassDist.get(key); } } /** * Method to set the best quality so far of the shapelet * * @param quality quality of the best so far quality observed */ public void setBsfQuality(double quality) { bsfQuality = quality; } /** * Method to update the ShapeletQualityBound with newly observed * OrderLineObj * * @param orderLineObj newly observed OrderLineObj */ public void updateOrderLine(OrderLineObj orderLineObj) { //Update classDistribution of unprocessed elements orderLineClassDist.put(orderLineObj.getClassVal(), orderLineClassDist.get(orderLineObj.getClassVal()) + 1); //use a binarySearch to update orderLine - rather than a O(n) search. int index = Collections.binarySearch(orderLine, orderLineObj); if (index < 0) { index *= -1; index -= 1; } orderLine.add(index, orderLineObj); } /** * Method to calculate the quality bound for the current orderline * * @return quality bound for the current orderline */ protected abstract double calculateBestQuality(); /** * Method to check if the current candidate can be pruned * * @return true if candidate can be pruned otherwise false */ public boolean pruneCandidate() { //Check if the required amount of data has been observed and //best quality so far set if (bsfQuality == Double.MAX_VALUE || orderLine.size() * 100 / numInstances <= percentage) { return false; } //The precondition is met, so quality bound can be computed return calculateBestQuality() <= bsfQuality; } }
4,337
31.133333
115
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/quality_measures/ShapeletQualityMeasure.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.quality_measures; import java.util.List; import tsml.transformers.shapelet_tools.OrderLineObj; import utilities.class_counts.ClassCounts; /** * * @author raj09hxu */ public interface ShapeletQualityMeasure { public double calculateQuality(List<OrderLineObj> orderline, ClassCounts classDistribution); public double calculateSeperationGap(List<OrderLineObj> orderline); }
1,215
33.742857
100
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/RandomSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions; import java.util.ArrayList; import java.util.Random; import weka.core.Instance; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author Aaron Bostrom and Tony Bagnall * random search of shapelet locations, does not visit the same shapelet twice */ public class RandomSearch extends ShapeletSearch{ protected Random random; protected boolean[][] visited; //boolean array, row is length of shapelet, column is location in series. protected RandomSearch(ShapeletSearchOptions ops) { super(ops); numShapeletsPerSeries = ops.getNumShapeletsToEvaluate(); random = new Random(ops.getSeed()); } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); int numLengths = maxShapeletLength - minShapeletLength /*+ 1*/; //want max value to be inclusive. visited = new boolean[numLengths][]; //Only consider a fixed number of shapelets per series. for(int i = 0; i< numShapeletsPerSeries; i++ ){ int lengthIndex = random.nextInt(numLengths); int length = lengthIndex + minShapeletLength; //offset the index by the min value. int maxPositions = seriesLength - length ; int start = random.nextInt(maxPositions); // can only have valid start positions based on the length. //we haven't constructed the memory for this length yet. initVisitedMemory(seriesLength, length); Shapelet shape = visitCandidate(timeSeries, start, length, checkCandidate); if(shape != null) seriesShapelets.add(shape); } for(int i=0; i<visited.length; i++){ if(visited[i] == null) continue; for(int j=0; j<visited[i].length; j++){ if(visited[i][j]) shapeletsVisited.add(seriesCount+","+(i+minShapeletLength)+","+j); } } seriesCount++; //keep track of the series. return seriesShapelets; } protected void initVisitedMemory(int seriesLength, int length){ int lengthIndex = getLengthIndex(length); if(visited[lengthIndex] == null){ int maxPositions = seriesLength - length; visited[lengthIndex] = new boolean[maxPositions]; } } protected int getLengthIndex(int length){ return length - minShapeletLength; } public long getNumPerSeries(){ return numShapeletsPerSeries;} protected Shapelet visitCandidate(Instance series, int start, int length, ProcessCandidate checkCandidate){ initVisitedMemory(series.numAttributes(), length); int lengthIndex = getLengthIndex(length); Shapelet shape = null; if(!visited[lengthIndex][start]){ shape = checkCandidate.process(series, start, length); visited[lengthIndex][start] = true; } return shape; } }
3,993
35.981481
114
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/ShapeletSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import weka.core.Instance; import weka.core.Instances; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import tsml.transformers.shapelet_tools.Shapelet; import static utilities.multivariate_tools.MultivariateInstanceTools.channelLength; /** * * @author Aaron Bostrom * edited Tony Bagnall 25/11/19 * Base class for ShapeletSearch that uses full enumeration. * Subclasses override SearchForShapeletsInSeries to define how to search a single series */ public class ShapeletSearch implements Serializable{ protected long numShapeletsPerSeries; //Number of shapelets to sample per series, used by the randomised versions //Defines the search technique defined in this package. public enum SearchType {FULL, //Evaluate all shapelets using RANDOM, //ALL of the below are things Aaron tried in his thesis (package aaron_search) //It is not commented and somewhat untested. GENETIC, FS, //Fast shapelets LOCAL, MAGNIFY, TIMED_RANDOM, SKIPPING, TABU, REFINED_RANDOM, IMPROVED_RANDOM, SUBSAMPLE_RANDOM, SKEWED, BO_SEARCH}; //Immutable class to store search params. //avoids using the Triple tuple, which is less clear. //TODO: could have a better name. protected static class CandidateSearchData{ private final int startPosition; private final int length; private final int dimension; //this is optional, for use with multivariate data. // If included it relates to the dimension of the data the shapelet is associated with public CandidateSearchData(int pos,int len){ startPosition = pos; length = len; dimension = 0; } public CandidateSearchData(int pos,int len,int dim){ startPosition = pos; length = len; dimension = dim; } /** * @return the startPosition */ public int getStartPosition() { return startPosition; } /** * @return the length */ public int getLength() { return length; } /** * @return the dimension */ public int getDimension() { return dimension; } } public interface ProcessCandidate{ public default Shapelet process(Instance candidate, int start, int length) {return process(candidate, start, length, 0);} public Shapelet process(Instance candidate, int start, int length, int dimension); } public interface ProcessCandidateTS{ public default Shapelet process(TimeSeriesInstance candidate, int start, int length) {return process(candidate, start, length, 0);} public Shapelet process(TimeSeriesInstance candidate, int start, int length, int dimension); } protected ArrayList<String> shapeletsVisited = new ArrayList<>(); protected int seriesCount; public ArrayList<String> getShapeletsVisited() { return shapeletsVisited; } protected Comparator<Shapelet> comparator; public void setComparator(Comparator<Shapelet> comp){ comparator = comp; } protected int seriesLength; protected int minShapeletLength; protected int maxShapeletLength; protected int numDimensions; protected int lengthIncrement = 1; protected int positionIncrement = 1; protected Instances inputData; protected TimeSeriesInstances inputDataTS; transient protected ShapeletSearchOptions options; public ShapeletSearchOptions getOptions(){ return options;} public long getNumShapeletsPerSeries(){ return numShapeletsPerSeries;} public void setNumShapeletsPerSeries(long t){ numShapeletsPerSeries =t; } public ShapeletSearch(ShapeletSearchOptions ops){ options = ops; minShapeletLength = ops.getMin(); maxShapeletLength = ops.getMax(); lengthIncrement = ops.getLengthIncrement(); positionIncrement = ops.getPosIncrement(); numDimensions = ops.getNumDimensions(); } public void setMinAndMax(int min, int max){ minShapeletLength = min; maxShapeletLength = max; } public int getMin(){ return minShapeletLength; } public int getMax(){ return maxShapeletLength; } public String getSearchType(){ return options.getSearchType().toString(); } public void init(Instances input){ inputData = input; //we need to detect whether it's multivariate or univariate. //this feels like a hack. BOO. //one relational and a class att. seriesLength = setSeriesLength(); } public void init(TimeSeriesInstances input){ inputDataTS = input; seriesLength = inputDataTS.getMaxLength(); } public int getSeriesLength(){ return seriesLength; //we add one here, because lots of code assumes it has a class value on the end/ TO DO: CLARIFY THIS } public int setSeriesLength(){ return inputData.numAttributes() >= maxShapeletLength ? inputData.numAttributes() : channelLength(inputData) + 1; //we add one here, because lots of code assumes it has a class value on the end/ } //given a series and a function to find a shapelet public ArrayList<Shapelet> searchForShapeletsInSeries(TimeSeriesInstance timeSeries, ProcessCandidateTS checkCandidate){ ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); //for univariate this will just evaluate all shapelets for (int length = minShapeletLength; length <= maxShapeletLength; length+=lengthIncrement) { //for all possible starting positions of that length. -1 to remove classValue but would be +1 (m-l+1) so cancel. for (int start = 0; start < seriesLength - length; start+=positionIncrement) { //for univariate this will be just once. for(int dim = 0; dim < numDimensions; dim++) { Shapelet shapelet = checkCandidate.process(timeSeries, start, length, dim); if (shapelet != null) { seriesShapelets.add(shapelet); shapeletsVisited.add(seriesCount+","+length+","+start+","+shapelet.qualityValue); } } } } seriesCount++; return seriesShapelets; } //given a series and a function to find a shapelet public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); //for univariate this will just evaluate all shapelets for (int length = minShapeletLength; length <= maxShapeletLength; length+=lengthIncrement) { //for all possible starting positions of that length. -1 to remove classValue but would be +1 (m-l+1) so cancel. for (int start = 0; start < seriesLength - length; start+=positionIncrement) { //for univariate OR MULTIVARIATE DEPENDENT this will be just once. for(int dim = 0; dim < numDimensions; dim++) { Shapelet shapelet = checkCandidate.process(getTimeSeries(timeSeries,dim), start, length, dim); if (shapelet != null) { seriesShapelets.add(shapelet); shapeletsVisited.add(seriesCount+","+length+","+start+","+shapelet.qualityValue); } } } } seriesCount++; // System.out.println("HERE: shapelet count = "+seriesShapelets.size()+" series count = "+seriesCount); // System.out.println("HERE:min = "+minShapeletLength+" max = = "+maxShapeletLength+" increment = "+lengthIncrement+" series length = "+seriesLength); return seriesShapelets; } public int getMinShapeletLength(){ return minShapeletLength; } public int getMaxShapeletLength(){ return maxShapeletLength; } protected Instance getTimeSeries(Instance timeSeries, int dim){ if(numDimensions > 1) return utilities.multivariate_tools.MultivariateInstanceTools.splitMultivariateInstanceWithClassVal(timeSeries)[dim]; return timeSeries; } }
9,361
38.008333
202
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/ShapeletSearchFactory.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions; /** * * * @author Aaron */ public class ShapeletSearchFactory { ShapeletSearchOptions options; public ShapeletSearchFactory(ShapeletSearchOptions ops){ options = ops; } /** * @return a Shapelet search configured by the options */ public ShapeletSearch getShapeletSearch(){ switch(options.getSearchType()){ case FULL: return new ShapeletSearch(options); case RANDOM: return new RandomSearch(options); default: throw new UnsupportedOperationException(" Currently only FULL and RANDOM shapelet search are allowed" + "you passed" + options.getSearchType()+" the others are in package aaron_search and are not debugged"); } } // private static final List<Function<ShapeletSearchOptions, ShapeletSearch>> searchConstructors = createSearchConstructors(); //{FULL, FS, GENETIC, RANDOM, LOCAL, MAGNIFY, TIMED_RANDOM, SKIPPING, TABU, REFINED_RANDOM, IMP_RANDOM, SUBSAMPLE, SKEWED}; /* //Aaron likes C++. This is just an indexed list of constructors for possible search technique private static List<Function<ShapeletSearchOptions, ShapeletSearch>> createSearchConstructors(){ List<Function<ShapeletSearchOptions, ShapeletSearch>> sCons = new ArrayList(); sCons.add(ShapeletSearch::new); sCons.add(RandomSearch::new); // All the below have been moved to aaron_search. The constructors are all protected for some reason //so that needs refactoring to be used here. sCons.add(BayesianOptimisedSearch::new); sCons.add(FastShapeletSearch::new); sCons.add(GeneticSearch::new); sCons.add(LocalSearch::new); sCons.add(MagnifySearch::new); sCons.add(RandomTimedSearch::new); sCons.add(SkippingSearch::new); sCons.add(TabuSearch::new); sCons.add(RefinedRandomSearch::new); sCons.add(ImprovedRandomSearch::new); sCons.add(SubsampleRandomSearch::new); sCons.add(SkewedRandomSearch::new); return sCons; } */ public static void main(String[] args) { System.out.println(new ShapeletSearchFactory(new ShapeletSearchOptions.Builder() .setSearchType(ShapeletSearch.SearchType.FULL) .build()) .getShapeletSearch()); } }
3,317
39.962963
129
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/ShapeletSearchOptions.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch.SearchType; import static tsml.transformers.shapelet_tools.search_functions.ShapeletSearch.SearchType.FULL; /** * * @author Aaron Bostrom * ANY comments in this are added by Tony * This is a configuration utility for the class ShapeletSearch, used in the complex initialisation method * of Aaron's invention */ public class ShapeletSearchOptions { private final long timeLimit;//Is this in conjunction with numShapelets? private final SearchType searchType; private final int numDimensions; //Number of dimensions in the data private final int min; //Min length of shapelets private final int max; //Max length of shapelets private final long seed; private final long numShapeletsToEvaluate; //The number of shapelets to sample PER SERIES used in RandomSearch and subclasses private final int lengthIncrement; //Defaults to 1 in ShapeletSearch, SkippingSearch will use this to avoid full search private final int posIncrement; //Defaults to 1 in ShapeletSearch, SkippingSearch will use this to avoid full search private final float proportion; // Used in TabuSearch, RefinedRandomSearch, SubsampleRandomSearch, MagnifySearch private final int maxIterations; // Used in LocalSearch to determine the number of search steps to take private final int[] lengthDistribution; // used in SkewedRandomSearch /** * Why a protected constructor? So you have to go through ShapeletSearchOptions.Builder in * order to configure * ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder(); */ protected ShapeletSearchOptions(Builder ops){ min = ops.min; max = ops.max; seed = ops.seed; numShapeletsToEvaluate = ops.numShapeletsToEvaluate; //The number of shapelets to sample PER SERIES lengthIncrement = ops.lengthInc; posIncrement = ops.posInc; proportion = ops.proportion; maxIterations = ops.maxIterations; timeLimit = ops.timeLimit; searchType = ops.searchType; numDimensions = ops.numDimensions; lengthDistribution = ops.lengthDistribution; } public static class Builder{ private int min; private int max; private long seed; private long numShapeletsToEvaluate; //Number of shapelets to evaluate PER SERIES private int lengthInc = 1; private int posInc = 1; private float proportion = 1.0f; private int maxIterations; private long timeLimit; private SearchType searchType; private int[] lengthDistribution; private int numDimensions = 1; //Setters: why do they all return themselves? public Builder setNumDimensions(int dim){ numDimensions = dim; return this; } public Builder setLengthDistribution(int[] lengthDist){ lengthDistribution = lengthDist; return this; } public Builder setSearchType(SearchType st){ searchType = st; return this; } public Builder setTimeLimit(long lim){ timeLimit = lim; return this; } public Builder setMin(int min) { this.min = min; return this; } public Builder setMax(int max) { this.max = max; return this; } public Builder setSeed(long seed) { this.seed = seed; return this; } public Builder setNumShapeletsToEvaluate(long numShapeletsToEvaluate) { this.numShapeletsToEvaluate = numShapeletsToEvaluate; return this; } public Builder setLengthInc(int lengthInc) { this.lengthInc = lengthInc; return this; } public Builder setPosInc(int posInc) { this.posInc = posInc; return this; } public Builder setProportion(float proportion) { this.proportion = proportion; return this; } public Builder setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; return this; } public ShapeletSearchOptions build(){ setDefaults(); return new ShapeletSearchOptions(this); } public void setDefaults(){ if(searchType == null){ searchType = FULL; } } } //Getters public int getMin() { return min; } public int getMax() { return max; } public long getSeed() { return seed; } public long getNumShapeletsToEvaluate() { return numShapeletsToEvaluate; } public int getLengthIncrement() { return lengthIncrement; } public int getPosIncrement() { return posIncrement; } public float getProportion() { return proportion; } public int getMaxIterations() { return maxIterations; } public long getTimeLimit() { return timeLimit; } public SearchType getSearchType(){ return searchType; } public int[] getLengthDistribution() { return lengthDistribution; } public int getNumDimensions(){ return numDimensions; } }
6,303
31.494845
130
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/BayesianOptimisedSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import experiments.data.DatasetLoading; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import tsml.transformers.shapelet_tools.Shapelet; import tsml.filters.shapelet_filters.ShapeletFilter; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchFactory; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import utilities.ClassifierTools; import utilities.numericalmethods.NelderMead; import weka.classifiers.functions.GaussianProcesses; import weka.classifiers.functions.supportVector.RBFKernel; import weka.classifiers.meta.RotationForest; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; /** * * @author a.bostrom1 * * This code has not been integrated into */ public class BayesianOptimisedSearch extends ImprovedRandomSearch { public ArrayList<Shapelet> evaluatedShapelets; //not the right type yet. public int pre_samples = 100; public int num_iterations = 100; public BayesianOptimisedSearch(ShapeletSearchOptions ops) { super(ops); } @Override public void init(Instances data) { super.init(data); } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ShapeletSearch.ProcessCandidate checkCandidate) { evaluatedShapelets = new ArrayList<>(); //do the random presamples. for (int i = 0; i < pre_samples; i++) { ShapeletSearch.CandidateSearchData pair = GetRandomShapelet(); evaluatePair(timeSeries, checkCandidate, pair); } current_gp = new GaussianProcesses(); current_gp.setKernel(new RBFKernel()); //use RBF Kernel. for (int i = 0; i < num_iterations; i++) { try { Instances to_train = ConvertShapeletsToInstances(evaluatedShapelets); current_gp.buildClassifier(to_train); evaluatePair(timeSeries, checkCandidate, GetRandomShapeletFromGP(current_gp)); } catch (Exception ex) { Logger.getLogger(BayesianOptimisedSearch.class.getName()).log(Level.SEVERE, null, ex); } } return evaluatedShapelets; } public Instances ConvertShapeletsToInstances(ArrayList<Shapelet> shapelets) { ArrayList<Attribute> atts = new ArrayList<>(); atts.add(new Attribute("Length")); atts.add(new Attribute("StartPosition")); atts.add(new Attribute("QualityValue")); //same number of xInstances Instances result = new Instances("shapelets", atts, shapelets.size()); for (int i = 0; i < shapelets.size(); i++) { result.add(new DenseInstance(3)); result.instance(i).setValue(0, shapelets.get(i).length); result.instance(i).setValue(1, shapelets.get(i).startPos); result.instance(i).setValue(2, shapelets.get(i).qualityValue); } result.setClassIndex(2); return result; } public Instance ConvertPairToInstance(ShapeletSearch.CandidateSearchData pair) { DenseInstance new_inst = new DenseInstance(3); new_inst.setValue(0, pair.getStartPosition()); new_inst.setValue(1, pair.getLength()); new_inst.setValue(2, 0); //set it as 0, because we don't know it yet. return new_inst; } public Shapelet evaluatePair(Instance timeSeries, ShapeletSearch.ProcessCandidate checkCandidate, ShapeletSearch.CandidateSearchData pair) { Shapelet shape = checkCandidate.process(timeSeries, pair.getStartPosition(), pair.getLength()); System.out.println("quality value: "+ shape.qualityValue); evaluatedShapelets.add(shape); return shape; } public ShapeletSearch.CandidateSearchData GetRandomShapelet() { int numLengths = maxShapeletLength - minShapeletLength; //want max value to be inclusive. int length = random.nextInt(numLengths) + minShapeletLength; //offset the index by the min value. int position = random.nextInt(seriesLength - length); // can only have valid start positions based on the length. (numAtts-1)-l+1 //find the shapelets for that series. //add the random shapelet to the length return new ShapeletSearch.CandidateSearchData(position,length); } public double GetIG(double[] params){ int length = (int)params[1]; //if we have invalid shapelet lengths of positions we want to fail the NelderMead. if (length < 3 || length > seriesLength) return 1E99; if(params[0] < 0 || params[0] >= seriesLength - length) return 1E99; try { DenseInstance new_inst = new DenseInstance(3); new_inst.setValue(0, params[0]); new_inst.setValue(1, params[1]); new_inst.setValue(2, 0); //set it as 0, because we don't know it yet. return 1.0 - current_gp.classifyInstance(new_inst); } catch (Exception ex) { System.out.println("bad"); } return 1E99; } public GaussianProcesses current_gp; public ShapeletSearch.CandidateSearchData GetRandomShapeletFromGP(GaussianProcesses gp) throws Exception { NelderMead nm = new NelderMead(); evaluatedShapelets.sort(comparator); // from 0,3 -> best_current_shapelet, to max length shapelet. double[][] simplex = { {0.0, 3.0}, {evaluatedShapelets.get(0).startPos, evaluatedShapelets.get(0).length}, {0.0, seriesLength} }; nm.descend(this::GetIG, simplex); double[] params = nm.getResult(); ShapeletSearch.CandidateSearchData bsf_pair = new ShapeletSearch.CandidateSearchData((int)params[0], (int)params[1]); double bsf_ig= nm.getScore(); System.out.println("predicted ig" + bsf_ig); System.out.println("bsf" + bsf_pair.getStartPosition() + bsf_pair.getLength()); return bsf_pair; } public static void main(String[] args) throws Exception { String dir = "D:/Research TSC/Data/TSCProblems2018/"; Instances[] data = DatasetLoading.sampleDataset(dir, "FordA", 1); Instances train = data[0]; Instances test = data[1]; int m = train.numAttributes() - 1; ShapeletSearchOptions sops = new ShapeletSearchOptions.Builder() .setSearchType(ShapeletSearch.SearchType.BO_SEARCH) .setMin(3).setMax(m) .setSeed(1) .setNumShapeletsToEvaluate(100) .build(); ShapeletFilter st = new ShapeletFilter(); st.setSearchFunction(new ShapeletSearchFactory(sops).getShapeletSearch()); st.process(train); st.process(test); RotationForest rotf = new RotationForest(); rotf.buildClassifier(train); System.out.println(ClassifierTools.accuracy(test, rotf)); } }
8,056
34.96875
144
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/FastShapeletSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instance; import weka.core.Instances; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author raj09hxu */ //only for Univariate public class FastShapeletSearch extends ShapeletSearch implements Serializable{ int R = 10; int sax_max_len = 15; double percent_mask = 0.25; long seed; Random rand; boolean searched = false; ArrayList<Pair<Integer, Double>> Score_List; HashMap<Integer, USAX_elm_type> USAX_Map; public FastShapeletSearch(ShapeletSearchOptions ops) { super(ops); } @Override public void init(Instances input){ super.init(input); searched = false; } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ int index = utilities.InstanceTools.indexOf(inputData, timeSeries); //becase the fast shapelets does all series rather than incrementally doing each series, we want to abandon further calls. //we index the shapelets in the series they come from, because then we can just grab them as a series is asked for. if(!searched){ calculateShapelets(); searched = true; } int word; int id, pos, len; USAX_elm_type usax; Collections.sort(Score_List, new ScoreComparator()); ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); //for the top K SAX words. for (Pair<Integer, Double> Score_List1 : Score_List) { word = Score_List1.first; usax = USAX_Map.get(word); int kk; //get the first one out. //this is because some sax words represent multiple start positions. for (kk = 0; kk < Math.min(usax.sax_id.size(), 1); kk++) { id = usax.sax_id.get(kk).first; if(id != index) continue; //if the id doesn't match our current asked for one. ignore. pos = usax.sax_id.get(kk).second; len = usax.sax_id.get(kk).third; //init the array list with 0s Shapelet s = checkCandidate.process(inputData.get(id), pos, len); if(s != null){ //put the shapelet in the list from it's series. seriesShapelets.add(s); } } } //definitely think we can reduce the amount of work even more. //by reducing seriesShapelets even more. Not letting it be more than K. etc. return seriesShapelets; } private void calculateShapelets(){ for (int length = minShapeletLength; length <= maxShapeletLength; length+=lengthIncrement) { USAX_Map = new HashMap<>(); Score_List = new ArrayList<>(); int sax_len = sax_max_len; /// Make w and sax_len both integer int w = (int) Math.ceil(1.0 * length / sax_len); sax_len = (int) Math.ceil(1.0 * length / w); createSAXList(length, sax_len, w); randomProjection(R, percent_mask, sax_len); scoreAllSAX(R); } } void createSAXList(int subseq_len, int sax_len, int w) { double ex, ex2, mean, std; double sum_segment[] = new double[sax_len]; int elm_segment[] = new int[sax_len]; int series, j, j_st, k, slot; double d; int word, prev_word; int numAttributes = seriesLength-1; USAX_elm_type ptr; //init the element segments to the W value. for (k = 0; k < sax_len; k++) { elm_segment[k] = w; } elm_segment[sax_len - 1] = subseq_len - (sax_len - 1) * w; double[] timeSeries; for (series = 0; series < inputData.size(); series++) { timeSeries = inputData.get(series).toDoubleArray(); ex = ex2 = 0; prev_word = -1; for (k = 0; k < sax_len; k++) { sum_segment[k] = 0; } // create first subsequence. PAA'ing as we go. for (j = 0; (j < numAttributes) && (j < subseq_len); j++) { d = timeSeries[j]; ex += d; ex2 += d * d; slot = (int) Math.floor((j) / w); sum_segment[slot] += d; } /// Case 2: Slightly Update for (; j <= numAttributes; j++) { j_st = j - subseq_len; mean = ex / subseq_len; std = Math.sqrt(ex2 / subseq_len - mean * mean); /// Create SAX from sum_segment word = createSAXWord(sum_segment, elm_segment, mean, std, sax_len); if (word != prev_word) { prev_word = word; //we're updating the reference so no need to re-add. ptr = USAX_Map.get(word); if (ptr == null) { ptr = new USAX_elm_type(); } ptr.obj_set.add(series); ptr.sax_id.add(new Triplet<>(series, j_st, subseq_len)); USAX_Map.put(word, ptr); } /// For next update if (j < numAttributes) { double temp = timeSeries[j_st]; ex -= temp; ex2 -= temp * temp; for (k = 0; k < sax_len - 1; k++) { sum_segment[k] -= timeSeries[j_st + (k) * w]; sum_segment[k] += timeSeries[j_st + (k + 1) * w]; } sum_segment[k] -= timeSeries[j_st + (k) * w]; sum_segment[k] += timeSeries[j_st + Math.min((k + 1) * w, subseq_len)]; d = timeSeries[j]; ex += d; ex2 += d * d; } } } } // Fix card = 4 here !!! //create a sax word of size 4 here as an int. int createSAXWord(double[] sum_segment, int[] elm_segment, double mean, double std, int sax_len) { int word = 0, val = 0; double d = 0; for (int i = 0; i < sax_len; i++) { d = (sum_segment[i] / elm_segment[i] - mean) / std; if (d < 0) { if (d < -0.67) { val = 0; } else { val = 1; } } else if (d < 0.67) { val = 2; } else { val = 3; } word = (word << 2) | (val); } return word; } // Count the number of occurrences void randomProjection(int R, double percent_mask, int sax_len) { HashMap<Integer, HashSet<Integer>> Hash_Mark = new HashMap<>(); int word, mask_word, new_word; HashSet<Integer> obj_set, ptr; int num_mask = (int) Math.ceil(percent_mask * sax_len); for (int r = 0; r < R; r++) { mask_word = createMaskWord(num_mask, sax_len); /// random projection and mark non-duplicate object for (Map.Entry<Integer, USAX_elm_type> entry : USAX_Map.entrySet()) { word = entry.getKey(); obj_set = entry.getValue().obj_set; //put the new word and set combo in the hash_mark new_word = word | mask_word; ptr = Hash_Mark.get(new_word); if (ptr == null) { Hash_Mark.put(new_word, new HashSet<>(obj_set)); } else { //add onto our ptr, rather than overwrite. ptr.addAll(obj_set); } } /// hash again for keep the count for (Map.Entry<Integer, USAX_elm_type> entry : USAX_Map.entrySet()) { word = entry.getKey(); new_word = word | mask_word; obj_set = Hash_Mark.get(new_word); //increase the histogram for (Integer o_it : obj_set) { Integer count = entry.getValue().obj_count.get(o_it); count = count == null ? 1 : count + 1; entry.getValue().obj_count.put(o_it, count); } } Hash_Mark.clear(); } } // create mask word (two random may give same position, we ignore it) int createMaskWord(int num_mask, int word_len) { int a, b; a = 0; for (int i = 0; i < num_mask; i++) { b = 1 << (word_len / 2); //b = 1 << (rand.nextInt()%word_len); //generate a random number between 0 and the word_len a = a | b; } return a; } // Score each SAX void scoreAllSAX(int R) { int word; double score; USAX_elm_type usax; for (Map.Entry<Integer, USAX_elm_type> entry : USAX_Map.entrySet()) { word = entry.getKey(); usax = entry.getValue(); score = calcScore(usax, R); Score_List.add(new Pair<>(word, score)); } } double calcScore(USAX_elm_type usax, int R) { double score = -1; int cid, count; double[] c_in = new double[inputData.numClasses()]; // Count object inside hash bucket double[] c_out = new double[inputData.numClasses()]; // Count object outside hash bucket /// Note that if no c_in, then no c_out of that object for (Map.Entry<Integer, Integer> entry : usax.obj_count.entrySet()) { cid = (int) inputData.get(entry.getKey()).classValue(); count = entry.getValue(); c_in[cid] += (count); c_out[cid] += (R - count); } score = calcScoreFromObjCount(c_in, c_out); return score; } // Score each sax in the matrix double calcScoreFromObjCount(double[] c_in, double[] c_out) { /// multi-class double diff, sum = 0, max_val = Double.NEGATIVE_INFINITY, min_val = Double.POSITIVE_INFINITY; for (int i = 0; i < inputData.numClasses(); i++) { diff = (c_in[i] - c_out[i]); if (diff > max_val) { max_val = diff; } if (diff < min_val) { min_val = diff; } sum += Math.abs(diff); } return (sum - Math.abs(max_val) - Math.abs(min_val)) + Math.abs(max_val - min_val); } private class ScoreComparator implements Comparator<Pair<Integer, Double>>, Serializable{ @Override //if the left one is bigger put it closer to the top. public int compare(Pair<Integer, Double> t, Pair<Integer, Double> t1) { return Double.compare(t1.second, t.second); } } private class USAX_elm_type implements Serializable{ HashSet<Integer> obj_set; ArrayList<Triplet<Integer, Integer, Integer>> sax_id; HashMap<Integer, Integer> obj_count; public USAX_elm_type() { obj_set = new HashSet<>(); sax_id = new ArrayList<>(); obj_count = new HashMap<>(); } } private class Pair<A, B> implements Serializable{ public A first; public B second; Pair() { } Pair(A l, B r) { first = l; second = r; } } private class Triplet<A, B, C> implements Serializable{ public A first; public B second; public C third; Triplet() { } Triplet(A l, B r, C g) { first = l; second = r; third = g; } } }
13,093
31.735
130
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/GeneticSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import java.util.List; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import utilities.generic_storage.Pair; import weka.core.Instance; import weka.core.Instances; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author raj09hxu */ @Deprecated public class GeneticSearch extends ImprovedRandomSearch { int initialPopulationSize = 50; private int initialNumShapeletsPerSeries; private int evaluated; public GeneticSearch(ShapeletSearchOptions sop){ super(sop); } @Override public void init(Instances input){ super.init(input); initialNumShapeletsPerSeries = (int) (numShapeletsPerSeries / inputData.numInstances()); } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ShapeletSearch.ProcessCandidate checkCandidate){ evaluated = 0; double[] series = timeSeries.toDoubleArray(); List<Shapelet> population = new ArrayList<>(); //generate the random shapelets we're going to visit. for(int i=0; i<initialPopulationSize; i++){ //randomly generate values. Pair<Integer, Integer> pair = createRandomShapelet(series); Shapelet shape = checkCandidate.process(timeSeries, pair.var2, pair.var1); evaluated++; if(shape != null) population.add(shape); } // so we evaluate the initial population while(evaluated < initialNumShapeletsPerSeries){ population = evolvePopulation(timeSeries, population, checkCandidate); } return (ArrayList<Shapelet>) population; } private Pair<Integer, Integer> createRandomShapelet(double[] series){ int numLengths = maxShapeletLength - minShapeletLength; //want max value to be inclusive. int length = random.nextInt(numLengths) + minShapeletLength; //offset the index by the min value. int position = random.nextInt(series.length + 1 - length); // can only have valid start positions based on the length. (numAtts-1)-l+1 return new Pair<>(length, position); } private static final double mutationRate = 0.015; private static final int tournamentSize = 5; private static final boolean elitism = true; private List<Shapelet> evolvePopulation(Instance timeSeries, List<Shapelet> shapesIn, ShapeletSearch.ProcessCandidate checkCandidate){ List<Shapelet> newPopulation = new ArrayList<>(); List<Pair<Integer, Integer>> populationToBe = new ArrayList<>(); // Keep our best individual if (elitism) { newPopulation.add(getBestShapelet(shapesIn)); } // Crossover population int elitismOffset = elitism ? 1 : 0; // Loop over the population size and create new individuals with // crossover for (int i = elitismOffset; i < shapesIn.size(); i++) { Shapelet indiv1 = tournamentSelection(shapesIn); Shapelet indiv2 = tournamentSelection(shapesIn); Pair<Integer, Integer> crossed = crossOver(indiv1, indiv2); populationToBe.add(crossed); } double[] series = timeSeries.toDoubleArray(); // Mutate population for (Pair<Integer, Integer> populationToBe1 : populationToBe) { mutate(populationToBe1); //check it's valid. PURGE THE MUTANT! Replace with random valid replacement. if(!validMutation(populationToBe1)){ Pair<Integer, Integer> pair = createRandomShapelet(series); populationToBe1 = pair; } Shapelet sh = checkCandidate.process(timeSeries, populationToBe1.var2, populationToBe1.var1); evaluated++; if(sh != null) newPopulation.add(sh); } return newPopulation; } private Shapelet getBestShapelet(List<Shapelet> shapes){ Shapelet bsf = shapes.get(0); for(Shapelet s : shapes){ if(s.getQualityValue() > bsf.getQualityValue()) bsf = s; } return bsf; } private void mutate(Pair<Integer, Integer> shape){ //random length or position mutation. if(random.nextDouble() <= mutationRate){ //mutate length by + or - 1 shape.var1+= random.nextBoolean() ? 1 : -1; } if(random.nextDouble() <= mutationRate){ //mutate position by + or - 1 shape.var2+= random.nextBoolean() ? 1 : -1; } } private boolean validMutation(Pair<Integer, Integer> mutant){ int newLen = mutant.var1; int newPos = mutant.var2; int m = inputData.numAttributes() -1; return !(newLen < minShapeletLength || //don't allow length to be less than minShapeletLength. newLen > maxShapeletLength || //don't allow length to be more than maxShapeletLength. newPos < 0 || //don't allow position to be less than 0. newPos >= (m-newLen+1)); //don't allow position to be greater than m-l+1. } private Pair<Integer, Integer> crossOver(Shapelet shape1, Shapelet shape2){ //pair should be length, position. //take the shapelets and make them breeeeeed. int length, position; length = random.nextBoolean() ? shape1.length : shape2.length; position = random.nextBoolean() ? shape1.startPos : shape2.startPos; return new Pair<>(length, position); } private Shapelet tournamentSelection(List<Shapelet> shapes){ //create random list of shapelets and battle them off. // Create a tournament population List<Shapelet> tournament = new ArrayList<>(); // For each place in the tournament get a random individual for (int i = 0; i < tournamentSize; i++) { int randomId = (int) (Math.random() * shapes.size()); tournament.add(shapes.get(randomId)); } // Get the fittest return getBestShapelet(tournament); } }
7,206
36.931579
143
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/ImprovedRandomSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import tsml.transformers.shapelet_tools.Shapelet; import tsml.transformers.shapelet_tools.search_functions.RandomSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instance; import weka.core.Instances; /** * * @author Aaron * random search of shapelet locations with replacement seems to be the improvement. */ public class ImprovedRandomSearch extends RandomSearch { protected Map<Integer, ArrayList<CandidateSearchData>> shapeletsToFind = new HashMap<>(); int currentSeries =0; public Map<Integer, ArrayList<CandidateSearchData>> getShapeletsToFind(){ return shapeletsToFind; } public ImprovedRandomSearch(ShapeletSearchOptions ops) { super(ops); } @Override public void init(Instances input){ super.init(input); int numLengths = maxShapeletLength - minShapeletLength; //want max value to be inclusive. //generate the random shapelets we're going to visit. for(int i = 0; i< numShapeletsPerSeries; i++){ //randomly generate values. int series = random.nextInt(input.numInstances()); int length = random.nextInt(numLengths) + minShapeletLength; //offset the index by the min value. int position = random.nextInt(seriesLength - length); // can only have valid start positions based on the length. (numAtts-1)-l+1 int dimension = random.nextInt(numDimensions); //find the shapelets for that series. ArrayList<CandidateSearchData> shapeletList = shapeletsToFind.get(series); if(shapeletList == null) shapeletList = new ArrayList<>(); //add the random shapelet to the length shapeletList.add(new CandidateSearchData(position,length,dimension)); //put back the updated version. shapeletsToFind.put(series, shapeletList); } } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); ArrayList<CandidateSearchData> shapeletList = shapeletsToFind.get(currentSeries); currentSeries++; //no shapelets to consider. if(shapeletList == null){ return seriesShapelets; } //Only consider a fixed amount of shapelets. for(CandidateSearchData shapelet : shapeletList){ //position is in var2, and length is in var1 Shapelet shape = checkCandidate.process(getTimeSeries(timeSeries,shapelet.getDimension()), shapelet.getStartPosition(), shapelet.getLength(), shapelet.getDimension()); if(shape != null) seriesShapelets.add(shape); } return seriesShapelets; } }
3,867
37.29703
179
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/LocalSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instance; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author raj09hxu */ public class LocalSearch extends RandomTimedSearch{ int maxIterations; public LocalSearch(ShapeletSearchOptions ops) { super(ops); maxIterations = ops.getMaxIterations(); } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ShapeletSearch.ProcessCandidate checkCandidate){ ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); int numLengths = maxShapeletLength - minShapeletLength /*+ 1*/; //want max value to be inclusive. visited = new boolean[numLengths][]; //maxIterations is the same as K. for(int currentIterations = 0; currentIterations < maxIterations; currentIterations++){ int lengthIndex = random.nextInt(numLengths); int length = lengthIndex + minShapeletLength; //offset the index by the min value. int maxPositions = seriesLength - length ; int start = random.nextInt(maxPositions); // can only have valid start positions based on the length. //we haven't constructed the memory for this length yet. initVisitedMemory(seriesLength, length); if(!visited[lengthIndex][start]){ Shapelet shape = evaluateShapelet(timeSeries, start, length, checkCandidate); //if the shapelet is null, it means it was poor quality. so we've abandoned this branch. if(shape != null) seriesShapelets.add(shape); } } return seriesShapelets; } private static final int START_DEC = 0, START_INC = 1, LENGTH_DEC = 2, LENGTH_INC = 3; private Shapelet evaluateShapelet(Instance series, int start, int length, ShapeletSearch.ProcessCandidate checkCandidate) { //we've not eval'd this shapelet; consider and put in list. Shapelet shapelet = visitCandidate(series, start, length, checkCandidate); if(shapelet == null) return shapelet; Shapelet[] shapelets; int index; Shapelet bsf_shapelet = shapelet; do{ //need to reset directions after each loop. shapelets = new Shapelet[4]; //calculate the best four directions. int startDec = start - 1; int startInc = start + 1; int lengthDec = length - 1; int lengthInc = length + 1; //as long as our start position doesn't go below 0. if(startDec >= 0){ shapelets[START_DEC] = visitCandidate(series, startDec, length, checkCandidate); } //our start position won't make us over flow on length. the start position is in the last pos. if(startInc < seriesLength - length){ shapelets[START_INC] = visitCandidate(series, startInc, length, checkCandidate); } //don't want to be shorter than the min length && does our length reduction invalidate our start pos? if(lengthDec > minShapeletLength && start < seriesLength - lengthDec){ shapelets[LENGTH_DEC] = visitCandidate(series, start, lengthDec, checkCandidate); } //dont want to be longer than the max length && does our start position invalidate our new length. if(lengthInc < maxShapeletLength && start < seriesLength - lengthInc){ shapelets[LENGTH_INC] = visitCandidate(series, start, lengthInc, checkCandidate); } //find the best shaplet direction and record which the best direction is. if it's -1 we don't want to move. //we only want to move when the shapelet is better, or equal but longer. index = -1; for(int i=0; i < shapelets.length; i++){ Shapelet shape = shapelets[i]; //if we're greater than the quality value then we want it, or if we're the same as the quality value but we are increasing length. if(shape != null && ((shape.qualityValue > bsf_shapelet.qualityValue) || (shape.qualityValue == bsf_shapelet.qualityValue && i == LENGTH_INC))){ index = i; bsf_shapelet = shape; } } //find the direction thats best, if it's same as current but longer keep searching, if it's shorter and same stop, if it's start = bsf_shapelet.startPos; length = bsf_shapelet.length; }while(index != -1); //no directions are better. return bsf_shapelet; } }
5,877
40.394366
146
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/MagnifySearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import java.util.BitSet; import static utilities.GenericTools.randomRange; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instance; import weka.core.Instances; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author raj09hxu */ public class MagnifySearch extends ImprovedRandomSearch { int initialNumShapeletsPerSeries; //how many times do we want to make our search area smaller. int maxDepth = 3; public MagnifySearch(ShapeletSearchOptions ops) { super(ops); proportion = ops.getProportion(); } float proportion = 1.0f; BitSet seriesToConsider; @Override public void init(Instances input){ //we need to detect whether it's multivariate or univariate. //this feels like a hack. BOO. //one relational and a class att. maxDepth = 3; inputData = input; seriesLength = setSeriesLength(); float subsampleSize = (float) inputData.numInstances() * proportion; initialNumShapeletsPerSeries = (int) ((float) numShapeletsPerSeries / subsampleSize); seriesToConsider = new BitSet(inputData.numInstances()); //if we're looking at less than root(m) shapelets per series. sample to root n. if(initialNumShapeletsPerSeries < Math.sqrt(inputData.numAttributes()-1)){ //recalc prop and subsample size. proportion = ((float) Math.sqrt(inputData.numInstances()) / (float)inputData.numInstances()); subsampleSize = (float) inputData.numInstances() * proportion; initialNumShapeletsPerSeries = (int) ((float) numShapeletsPerSeries / subsampleSize); System.out.println("sampling"); } initialNumShapeletsPerSeries /= (float) maxDepth; //if proportion is 1.0 enable all series. if(proportion >= 1.0){ seriesToConsider.set(0, inputData.numInstances(), true); //enable all } else{ for(int i=0; i< subsampleSize; i++){ seriesToConsider.set(random.nextInt((int) inputData.numInstances())); } System.out.println(seriesToConsider); } if(initialNumShapeletsPerSeries < 1) System.err.println("Too Few Starting shapelets"); } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ ArrayList<Shapelet> candidateList = new ArrayList<>(); if(!seriesToConsider.get(currentSeries++)) return candidateList; //we want to iteratively shrink our search area. int minLength = minShapeletLength; int maxLength = maxShapeletLength; int minPos = 0; //if the series is m = 100. our max pos is 97, when min is 3. int maxPos = maxShapeletLength - minShapeletLength + 1; int lengthWidth = (maxLength - minLength) / 2; int posWidth = (maxPos + minPos) / 2; for(int depth = 0; depth < maxDepth; depth++){ Shapelet bsf = null; //we divide the numShapeletsPerSeries by maxDepth. for(int i = 0; i< initialNumShapeletsPerSeries; i++){ CandidateSearchData sh = createRandomShapelet(seriesLength-1, minLength, maxLength, minPos, maxPos); Shapelet shape = checkCandidate.process(timeSeries, sh.getStartPosition(), sh.getLength()); if(bsf == null) { bsf = shape; } if(shape == null || bsf == null) continue; //if we're at the bottom level we should start compiling the list. if(depth == maxDepth-1) candidateList.add(shape); if(comparator.compare(bsf, shape) > 0){ bsf = shape; } } //add each best so far. //should give us a bit of a range of improving shapelets and a really gone one. //do another trial. -- this is super unlikely. if(bsf==null) { continue; } //change the search parameters based on the new best. //divide by 2. lengthWidth >>= 1; posWidth >>= 1; minLength = bsf.length - lengthWidth; maxLength = bsf.length + lengthWidth; minPos = bsf.startPos - posWidth; maxPos = bsf.startPos + posWidth; } return candidateList; } private CandidateSearchData createRandomShapelet(int totalLength, int minLen, int maxLen, int minPos, int maxPos){ //clamp the lengths. //never let the max length go lower than 3. int maxL = Math.min(totalLength, Math.max(maxLen, minShapeletLength)); int minL = Math.max(minShapeletLength, minLen); int length = randomRange(random, minL, maxL); //calculate max and min clamp based on length. //can't have max position > m-l+1 //choose the smaller of the two. int maxP = Math.min(totalLength-length, maxPos); int minP = Math.max(0, minPos); int position = randomRange(random, minP, maxP); return new CandidateSearchData(position,length); } public static void main(String[] args){ ShapeletSearchOptions magnifyOptions = new ShapeletSearchOptions.Builder().setMin(3).setMax(100).setNumShapeletsToEvaluate(1000).setSeed(0).build(); MagnifySearch ps = new MagnifySearch(magnifyOptions); for(int i=0; i<100; i++) System.out.println(ps.createRandomShapelet(100, 3, 100, 0, 100)); } }
6,817
36.668508
156
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/RandomSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import tsml.transformers.shapelet_tools.Shapelet; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instance; import java.util.ArrayList; import java.util.Random; /** * * @author raj09hxu * * random search of shapelet locations, does not visit the same shapelet twice */ public class RandomSearch extends ShapeletSearch{ protected Random random; protected long numPerSeries; //Number of shapelets to sample per series protected boolean[][] visited; // protected RandomSearch(ShapeletSearchOptions ops) { super(ops); numPerSeries = ops.getNumShapeletsToEvaluate(); random = new Random(ops.getSeed()); } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); int numLengths = maxShapeletLength - minShapeletLength /*+ 1*/; //want max value to be inclusive. visited = new boolean[numLengths][]; //Only consider a fixed number of shapelets per series. for(int i = 0; i< numPerSeries; i++ ){ int lengthIndex = random.nextInt(numLengths); int length = lengthIndex + minShapeletLength; //offset the index by the min value. int maxPositions = seriesLength - length ; int start = random.nextInt(maxPositions); // can only have valid start positions based on the length. //we haven't constructed the memory for this length yet. initVisitedMemory(seriesLength, length); Shapelet shape = visitCandidate(timeSeries, start, length, checkCandidate); if(shape != null) seriesShapelets.add(shape); } for(int i=0; i<visited.length; i++){ if(visited[i] == null) continue; for(int j=0; j<visited[i].length; j++){ if(visited[i][j]) shapeletsVisited.add(seriesCount+","+(i+minShapeletLength)+","+j); } } seriesCount++; //keep track of the series. return seriesShapelets; } protected void initVisitedMemory(int seriesLength, int length){ int lengthIndex = getLengthIndex(length); if(visited[lengthIndex] == null){ int maxPositions = seriesLength - length; visited[lengthIndex] = new boolean[maxPositions]; } } protected int getLengthIndex(int length){ return length - minShapeletLength; } public long getNumPerSeries(){ return numPerSeries;} protected Shapelet visitCandidate(Instance series, int start, int length, ProcessCandidate checkCandidate){ initVisitedMemory(series.numAttributes(), length); int lengthIndex = getLengthIndex(length); Shapelet shape = null; if(!visited[lengthIndex][start]){ shape = checkCandidate.process(series, start, length); visited[lengthIndex][start] = true; } return shape; } }
4,121
35.803571
114
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/RandomTimedSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import java.util.Random; import tsml.transformers.shapelet_tools.search_functions.RandomSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instance; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author raj09hxu */ public class RandomTimedSearch extends RandomSearch { protected long timeLimit; public RandomTimedSearch(ShapeletSearchOptions ops) { super(ops); timeLimit = ops.getTimeLimit(); random = new Random(ops.getSeed()); } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ long currentTime =0; ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); int numLengths = maxShapeletLength - minShapeletLength /*+ 1*/; //want max value to be inclusive. visited = new boolean[numLengths][]; //you only get a 1/nth of the time. while((timeLimit/inputData.numInstances()) > currentTime){ int lengthIndex = random.nextInt(numLengths); int length = lengthIndex + minShapeletLength; //offset the index by the min value. int maxPositions = seriesLength - length ; int start = random.nextInt(maxPositions); // can only have valid start positions based on the length. //we haven't constructed the memory for this length yet. initVisitedMemory(seriesLength, length); Shapelet shape = visitCandidate(timeSeries, start, length, checkCandidate); if(shape != null) seriesShapelets.add(shape); //we add time, even if we've visited it, this is just incase we end up stuck in some // improbable recursive loop. currentTime += calculateTimeToRun(inputData.numInstances(), seriesLength-1, length); //n,m,l } for(int i=0; i<visited.length; i++){ if(visited[i] == null) continue; for(int j=0; j<visited[i].length; j++){ if(visited[i][j]) shapeletsVisited.add(seriesCount+","+(i+minShapeletLength)+","+j); } } seriesCount++; //keep track of the series. return seriesShapelets; } protected long calculateTimeToRun(int n, int m, int length){ long time = (m - length + 1) * length; //number of subsequeneces in the seuquenece, and we do euclidean comparison length times for each. return time * (n-1); //we calculate this for n-1 series. } }
3,592
36.041237
145
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/RefinedRandomSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import tsml.transformers.shapelet_tools.ShapeletTransformTimingUtilities; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instances; /** * * @author raj09hxu * * Tony adds, 25/11/19: refined in interesting ways no doubt, but I have no idea how. */ public class RefinedRandomSearch extends ImprovedRandomSearch { float shapeletToSeriesRatio; public RefinedRandomSearch(ShapeletSearchOptions ops) { super(ops); shapeletToSeriesRatio = ops.getProportion(); } @Override public void init(Instances input){ super.init(input); int numInstances = input.numInstances(); int numAttributes = seriesLength - 1; float currentRatio; do{ long totalShapelets = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(--numInstances, numAttributes, minShapeletLength, maxShapeletLength); currentRatio = (float) numShapeletsPerSeries / (float) totalShapelets; if(numInstances == 25) break; // any less than 25 and we've sampled too far (Subject to change and discussion). }while(currentRatio < shapeletToSeriesRatio); inputData = input; int numLengths = maxShapeletLength - minShapeletLength; //want max value to be inclusive. //generate the random shapelets we're going to visit. for(int i = 0; i< numShapeletsPerSeries; i++){ //randomly generate values. int series = random.nextInt(numInstances); int length = random.nextInt(numLengths) + minShapeletLength; //offset the index by the min value. int position = random.nextInt(numAttributes - length + 1); // can only have valid start positions based on the length. the upper bound is exclusive. int dimension = random.nextInt(numDimensions); //so for the m-m+1 case it always resolves to 0. //find the shapelets for that series. ArrayList<CandidateSearchData> shapeletList = shapeletsToFind.get(series); if(shapeletList == null) shapeletList = new ArrayList<>(); //add the random shapelet to the length shapeletList.add(new CandidateSearchData(position,length,dimension)); //put back the updated version. shapeletsToFind.put(series, shapeletList); } } }
3,383
39.771084
163
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/SkewedRandomSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import java.util.Random; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instances; /** * * @author Aaron */ public class SkewedRandomSearch extends ImprovedRandomSearch { int[] lengthDistribution; int[] cumulativeDistribution; public SkewedRandomSearch(ShapeletSearchOptions sops){ super(sops); lengthDistribution = sops.getLengthDistribution(); } @Override public void init(Instances input){ super.init(input); cumulativeDistribution = findCumulativeCounts(lengthDistribution); //generate the random shapelets we're going to visit. for(int i = 0; i< numShapeletsPerSeries; i++){ //randomly generate values. int series = random.nextInt(input.numInstances()); //this gives an index, we assume the length dsitribution is from min-max. so a value of 0 is == minShapeletLength int length = sampleCounts(cumulativeDistribution, random) + minShapeletLength; //select the random length from the distribution of lengths. int position = random.nextInt(seriesLength - length); // can only have valid start positions based on the length. (numAtts-1)-l+1 int dimension = random.nextInt(numDimensions); //find the shapelets for that series. ArrayList<CandidateSearchData> shapeletList = shapeletsToFind.get(series); if(shapeletList == null) shapeletList = new ArrayList<>(); //add the random shapelet to the length shapeletList.add(new CandidateSearchData(position,length,dimension)); //put back the updated version. shapeletsToFind.put(series, shapeletList); } } /** * * @param counts count of number of items at each level i * @return cumulative count of items at level <=i */ public static int[] findCumulativeCounts(int[] counts){ int[] c=new int[counts.length]; c[0]=counts[0]; int i=1; while(i<counts.length){ c[i]=c[i-1]+counts[i]; i++; } return c; } /** * * @param cumulativeCounts: cumulativeCounts[i] is the number of items <=i * as found by findCumulativeCounts * cumulativeCounts[length-1] is the total number of objects * @param rand * @return a randomly selected level i based on sample of cumulativeCounts */ public static int sampleCounts(int[] cumulativeCounts, Random rand){ int c=rand.nextInt(cumulativeCounts[cumulativeCounts.length-1]); int pos=0; while(cumulativeCounts[pos]<= c) pos++; return pos; } public static void main(String[] args) { int[] histogram = {4,4,0,1}; int[] cum = findCumulativeCounts(histogram); Random rand = new Random(0); //i histogrammed this for a bunch of different distributions. for (int i = 0; i < 1000; i++) { //System.out.print(sampleCounts(cum, rand) + ","); } } }
4,030
34.052174
151
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/SkippingSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearch; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instance; import weka.core.Instances; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author Aaron * * Skipping search. Assume it just jumps through a range of */ public class SkippingSearch extends ShapeletSearch { int[] positions; int[] lengths; public SkippingSearch(ShapeletSearchOptions sops){ super(sops); } @Override public void init(Instances input){ super.init(input); //create array of classValues. positions = new int[input.numClasses()]; lengths = new int[input.numClasses()]; } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ //we want to store a startLength and startPos for each class and cycle them when we're skipping. int index = (int)timeSeries.classValue(); int start = positions[index]; int length = lengths[index] + minShapeletLength; ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); for (; length <= maxShapeletLength; length+=lengthIncrement) { //for all possible starting positions of that length. -1 to remove classValue for (; start <= seriesLength - length - 1; start+=positionIncrement) { Shapelet shapelet = checkCandidate.process(timeSeries, start, length); if (shapelet != null) { seriesShapelets.add(shapelet); } } } //IE if we're skipping 2positions. we want to cycle between starting a series at 0,1 positions[index] = ++positions[index] % positionIncrement; lengths[index] = ++lengths[index] % lengthIncrement; return seriesShapelets; } }
2,835
35.358974
112
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/SubsampleRandomSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instances; /** * * @author Aaron */ public class SubsampleRandomSearch extends ImprovedRandomSearch { float shapeletToSeriesRatio; public SubsampleRandomSearch(ShapeletSearchOptions ops) { super(ops); shapeletToSeriesRatio = ops.getProportion(); } @Override public void init(Instances input){ super.init(input); int numInstances = (int) (input.numInstances() * shapeletToSeriesRatio) ; int numAttributes = seriesLength - 1; inputData = input; int numLengths = maxShapeletLength - minShapeletLength; //want max value to be inclusive. //generate the random shapelets we're going to visit. for(int i = 0; i< numShapeletsPerSeries; i++){ //randomly generate values. int series = random.nextInt(numInstances); int length = random.nextInt(numLengths) + minShapeletLength; //offset the index by the min value. int position = random.nextInt(numAttributes - length + 1); // can only have valid start positions based on the length. the upper bound is exclusive. int dimension = random.nextInt(numDimensions); //find the shapelets for that series. ArrayList<CandidateSearchData> shapeletList = shapeletsToFind.get(series); if(shapeletList == null) shapeletList = new ArrayList<>(); //add the random shapelet to the length shapeletList.add(new CandidateSearchData(position,length,dimension)); //put back the updated version. shapeletsToFind.put(series, shapeletList); } } }
2,689
37.428571
162
java
tsml-java
tsml-java-master/src/main/java/tsml/transformers/shapelet_tools/search_functions/aaron_search/TabuSearch.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package tsml.transformers.shapelet_tools.search_functions.aaron_search; import java.util.ArrayList; import java.util.BitSet; import java.util.LinkedList; import java.util.Queue; import tsml.transformers.shapelet_tools.search_functions.ShapeletSearchOptions; import weka.core.Instance; import weka.core.Instances; import tsml.transformers.shapelet_tools.Shapelet; /** * * @author raj09hxu */ public class TabuSearch extends ImprovedRandomSearch { int neighbourhoodWidth = 3; //3x3 int maxTabuSize = 50; int initialNumShapeletsPerSeries; Shapelet bsf_shapelet; BitSet seriesToConsider; float proportion = 1.0f; public TabuSearch(ShapeletSearchOptions ops) { super(ops); proportion = ops.getProportion(); } @Override public void init(Instances input){ super.init(input); float subsampleSize = (float) inputData.numInstances() * proportion; initialNumShapeletsPerSeries = (int) ((float) numShapeletsPerSeries / subsampleSize); seriesToConsider = new BitSet(inputData.numInstances()); System.out.println(initialNumShapeletsPerSeries); //if we're looking at less than root(m) shapelets per series. sample to root n. if(initialNumShapeletsPerSeries < Math.sqrt(inputData.numAttributes()-1)){ //recalc prop and subsample size. proportion = ((float) Math.sqrt(inputData.numInstances()) / (float)inputData.numInstances()); subsampleSize = (float) inputData.numInstances() * proportion; initialNumShapeletsPerSeries = (int) ((float) numShapeletsPerSeries / subsampleSize); System.out.println("subsampleSize " + (int)subsampleSize); } if(proportion >= 1.0){ seriesToConsider.set(0, inputData.numInstances(), true); //enable all } else{ //randomly select % of the series. for(int i=0; i< subsampleSize; i++){ seriesToConsider.set(random.nextInt((int) inputData.numInstances())); } System.out.println(seriesToConsider); } System.out.println(initialNumShapeletsPerSeries); // we might need to reduce the number of series. could do 10% subsampling. if(initialNumShapeletsPerSeries < 1) System.err.println("Too Few Starting shapelets"); } @Override public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); if(!seriesToConsider.get(currentSeries++)) return seriesShapelets; Queue<CandidateSearchData> tabuList = new LinkedList<>(); CandidateSearchData shapelet; int numShapeletsEvaluated = 0; //Only consider a fixed amount of shapelets. while(initialNumShapeletsPerSeries > numShapeletsEvaluated){ //create the random shapelet. //if it's the first iteration and we've got a previous best shapelet. if(numShapeletsEvaluated == 0 && bsf_shapelet != null){ shapelet = new CandidateSearchData(bsf_shapelet.startPos,bsf_shapelet.length) ; bsf_shapelet = null; //reset the best one for this series. }else{ shapelet = createRandomShapelet(timeSeries); } ArrayList<CandidateSearchData> candidateList = new ArrayList<>(); candidateList.add(shapelet); candidateList.addAll(createNeighbourhood(shapelet, timeSeries.numAttributes())); boolean inList = false; for(CandidateSearchData neighbour : candidateList){ //i think if we collide with the tabuList we should abandon the neighbourhood. if(tabuList.contains(neighbour)){ inList = true; break; } } //if inList is true we want to abandon this whole search area. if(inList){ continue; } //find the best local candidate CandidateSearchData bestLocal = null; Shapelet local_bsf_shapelet = null; for(CandidateSearchData shape : candidateList ){ Shapelet sh = checkCandidate.process(timeSeries, shape.getStartPosition(), shape.getLength()); numShapeletsEvaluated++; //we've abandoned this shapelet, and therefore it is null. if(sh == null) continue; if(local_bsf_shapelet == null){ bestLocal = shape; local_bsf_shapelet = sh; } //if the comparator says it's better. if(comparator.compare(local_bsf_shapelet, sh) > 0){ bestLocal = shape; local_bsf_shapelet = sh; } } if(local_bsf_shapelet == null) continue; if(bsf_shapelet == null){ bsf_shapelet = local_bsf_shapelet; seriesShapelets.add(local_bsf_shapelet); //stick the local best ones in the list. } //update bsf shapelet if the local one is better. if(comparator.compare(bsf_shapelet, local_bsf_shapelet) > 0){ bsf_shapelet = local_bsf_shapelet; seriesShapelets.add(local_bsf_shapelet); //stick the local best ones in the list. } //add the best local to the TabuList tabuList.add(bestLocal); if(tabuList.size() > maxTabuSize){ tabuList.remove(); } } return seriesShapelets; } ArrayList<CandidateSearchData> createNeighbourhood(CandidateSearchData shapelet){ return createNeighbourhood(shapelet, inputData.numAttributes()-1); } ArrayList<CandidateSearchData> createNeighbourhood(CandidateSearchData shapelet, int m){ ArrayList<CandidateSearchData> neighbourhood = new ArrayList<>(); neighbourhood.add(shapelet); //add the shapelet to the neighbourhood. int halfWidth = (int)((double)neighbourhoodWidth / 2.0); for(int pos= -halfWidth; pos <= halfWidth; pos++){ for(int len= -halfWidth; len <= halfWidth; len++){ if(len == 0 && pos == 0) continue; //need to prune impossible shapelets. int newLen = shapelet.getLength() + len; int newPos = shapelet.getStartPosition() + pos; if(newLen < minShapeletLength || //don't allow length to be less than minShapeletLength. newLen > maxShapeletLength || //don't allow length to be more than maxShapeletLength. newPos < 0 || //don't allow position to be less than 0. newPos >= (m-newLen)) //don't allow position to be greater than m-l+1. continue; neighbourhood.add(new CandidateSearchData(newPos,newLen)); } } return neighbourhood; } private CandidateSearchData createRandomShapelet(Instance series){ int numLengths = maxShapeletLength - minShapeletLength; //want max value to be inclusive. int length = random.nextInt(numLengths) + minShapeletLength; //offset the index by the min value. int position = random.nextInt(series.numAttributes() - length); // can only have valid start positions based on the length. (numAtts-1)-l+1 return new CandidateSearchData(position,length); } public static void main(String[] args){ //3 -> 100 series. 100 shapelets. //will aim to make a searchFactory so you dont hand build a searchFunction. ShapeletSearchOptions tabuOptions = new ShapeletSearchOptions.Builder().setMin(3).setMax(100).setNumShapeletsToEvaluate(1000).setSeed(0).build(); TabuSearch tb = new TabuSearch(tabuOptions); //edge case neighbour hood testing //length of m, and for (int len = 3; len < 100; len++) { for(int pos=0; pos< 100-len+1; pos++){ ArrayList<CandidateSearchData> createNeighbourhood = tb.createNeighbourhood(new CandidateSearchData(pos,len), 100); System.out.println(createNeighbourhood); } } } }
9,554
39.487288
153
java
tsml-java
tsml-java-master/src/main/java/utilities/ArrayUtilities.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; public class ArrayUtilities { private ArrayUtilities() {} public static String toString(double[][] array) { return toString(array, ",", System.lineSeparator()); } public static String toString(int[][] array) { return toString(array, ",", System.lineSeparator()); } public static double[][] transposeMatrix(double [][] m){ double[][] temp = new double[m[0].length][m.length]; for (int i = 0; i < m.length; i++) for (int j = 0; j < m[0].length; j++) temp[j][i] = m[i][j]; return temp; } public static double[] intToDouble(int[] input) { double[] output = new double[input.length]; for(int i = 0; i < output.length; i++) { output[i] = input[i]; } return output; } public static double[][] intToDouble(int[][] input) { double[][] output = new double[input.length][]; for(int i = 0; i < output.length; i++) { output[i] = intToDouble(input[i]); } return output; } public static double[] oneHot(int length, int index) { final double[] array = new double[length]; array[index] = 1; return array; } public static double[][] oneHot(int length, int[] indicies) { final double[][] array = new double[indicies.length][length]; for (int i = 0; i < indicies.length; i++){ array[i][indicies[i]] = 1; } return array; } public static double[][] oneHot(int length, double[] indicies) { final double[][] array = new double[indicies.length][length]; for (int i = 0; i < indicies.length; i++){ array[i][(int) indicies[i]] = 1; } return array; } public static void add(double[] src, double[] addend) { if(src.length < addend.length) { throw new IllegalArgumentException(); } for(int i = 0; i < addend.length; i++) { src[i] += addend[i]; } } public static double[] subtract(double[] a, double[] b) { int length = Math.min(a.length, b.length); for(int i = 0; i < length; i++) { a[i] -= b[i]; } return a; } public static double[] subtract(double[] a, double amount) { int length = a.length; for(int i = 0; i < length; i++) { a[i] -= amount; } return a; } public static double[] abs(double[] array) { for(int i = 0; i < array.length; i++) { array[i] = Math.abs(array[i]); } return array; } public static boolean[] mask(double[] array, Predicate<Double> condition) { final boolean[] result = new boolean[array.length]; for(int i = 0; i < array.length; i++) { result[i] = condition.test(array[i]); } return result; } public static int count(boolean[] array) { int sum = 0; for(final boolean b : array) { if(b) { sum++; } } return sum; } public static double[] pow(double[] array, double degree) { for(int i = 0; i < array.length; i++) { array[i] = Math.pow(array[i], degree); } return array; } public static double sum(double[] array) { double sum = 0; for(int i = 0; i < array.length; i++) { sum += array[i]; } return sum; } public static double sumPow2(double[] array) { double sum = 0; for(int i = 0; i < array.length; i++) { sum += Math.pow(array[i], 2); } return sum; } public static double[] cumsum(double[] array) { double[] sum = new double[array.length]; sum[0] = array[0]; for(int i = 1; i < array.length; i++) { sum[i] = sum[i - 1] + array[i]; } return sum; } public static double[] cumsumPow2(double[] array) { double[] sum = new double[array.length]; sum[0] = Math.pow(array[0], 2); for(int i = 1; i < array.length; i++) { sum[i] = sum[i - 1] + Math.pow(array[i], 2);; } return sum; } public static double[] normalise(double[] array, boolean ignoreZeroSum) { double sum = sum(array); if(sum == 0) { if(ignoreZeroSum) { return uniformDistribution(array.length); } throw new IllegalArgumentException("sum of zero"); } for(int i = 0; i < array.length; i++) { array[i] /= sum; } return array; } public static double[] copy(double[] input) { double[] output = new double[input.length]; System.arraycopy(input, 0, output, 0, input.length); return output; } public static double[] normalise(double[] array) { return normalise(array, true); } public static double[] normalise(int[] array) { return normalise(array, true); } public static double[] normalise(int[] array, boolean ignoreZeroSum) { double sum = sum(array); double[] result = new double[array.length]; if(sum == 0 && !ignoreZeroSum) { throw new IllegalArgumentException("sum of zero"); } for(int i = 0; i < array.length; i++) { result[i] = (double) array[i] / sum; } return result; } public static <A> List<A> drain(Iterable<A> iterable) { return drain(iterable.iterator()); } public static <A> List<A> drain(Iterator<A> iterator) { List<A> list = new ArrayList<>(); while(iterator.hasNext()) { list.add(iterator.next()); } return list; } public static double sum(List<Double> list) { return list.stream().reduce(0d, Double::sum); } public static List<Double> normalise(List<Double> list) { double sum = sum(list); if(sum == 0) { sum = 1; } final double finalSum = sum; return list.stream().map(element -> element / finalSum).collect(Collectors.toList()); } public static List<Double> normalise(Iterable<Double> iterable) { List<Double> list = drain(iterable); return normalise(list); } public static void multiply(double[] array, double multiplier) { for(int i = 0; i < array.length; i++) { array[i] *= multiplier; } } public static double mean(double[] array) { return sum(array) / array.length; } public static double std(double[] array){ double mean = mean(array); double squareSum = 0; for (double v : array) { double temp = v - mean; squareSum += temp * temp; } return Math.sqrt(squareSum/(array.length-1)); } public static double std(double[] array, double mean){ double squareSum = 0; for (double v : array) { double temp = v - mean; squareSum += temp * temp; } return Math.sqrt(squareSum/(array.length-1)); } public static void divide(int[] array, int divisor) { for(int i = 0; i < array.length; i++) { array[i] /= divisor; } } public static List<Object> asList(Object[] array) { return Arrays.asList(array); } public static List<Integer> asList(int[] array) { return Arrays.asList(box(array)); } public static List<Double> asList(double[] array) { return Arrays.asList(box(array)); } public static List<Float> asList(float[] array) { return Arrays.asList(box(array)); } public static List<Long> asList(long[] array) { return Arrays.asList(box(array)); } public static List<Short> asList(short[] array) { return Arrays.asList(box(array)); } public static List<Byte> asList(byte[] array) { return Arrays.asList(box(array)); } public static List<Boolean> asList(boolean[] array) { return Arrays.asList(box(array)); } public static List<Character> asList(char[] array) { return Arrays.asList(box(array)); } public static double[] unbox(List<Double> list) { double[] array = new double[list.size()]; for(int i = 0; i < array.length; i++) { array[i] = list.get(i); } return array; } public static int[] range(int min, int max, int size) { int[] output = new int[size]; output[0] = min; output[size - 1] = max; for(int i = 1; i < size - 1; i++) { output[i] = (int) Math.round(((double) (max - min)) / (size - 1) * i); } return output; } public static double[] range(double min, double max, int size) { double[] output = new double[size]; output[0] = min; output[size - 1] = max; for(int i = 1; i < size - 1; i++) { output[i] = (max - min) / (size - 1) * i + min; } return output; } public static <A extends Comparable<A>> List<A> unique(Collection<A> values) { return unique(new ArrayList<>(values), Comparator.naturalOrder()); } public static <A extends Comparable<A>> List<A> unique(List<A> values) { return unique(values, Comparator.naturalOrder()); } public static List<Double> unique(double[] values) { return unique(new ArrayList<>(asList(values))); } public static List<Integer> unique(int[] values) { return unique(new ArrayList<>(asList(values))); } public static <A> List<A> unique(List<A> values, Comparator<A> comparator) { Set<A> set = new TreeSet<>(comparator); // must be treeset to maintain ordering set.addAll(values); values.clear(); values.addAll(set); return values; } public static List<Integer> fromPermutation(int permutation, List<Integer> binSizes) { int maxCombination = numPermutations(binSizes) - 1; if(permutation > maxCombination || binSizes.size() == 0 || permutation < 0) { throw new IndexOutOfBoundsException(); } List<Integer> result = new ArrayList<>(); for(int index = 0; index < binSizes.size(); index++) { int binSize = binSizes.get(index); if(binSize > 1) { result.add(permutation % binSize); permutation /= binSize; } else { if(binSize < 0) { throw new IllegalArgumentException(); } result.add(binSize - 1); } } return result; } public static int toPermutation(List<Integer> values, List<Integer> binSizes) { if(values.size() != binSizes.size()) { throw new IllegalArgumentException("incorrect number of args"); } int permutation = 0; for(int i = binSizes.size() - 1; i >= 0; i--) { int binSize = binSizes.get(i); if(binSize > 1) { int value = values.get(i); permutation *= binSize; permutation += value; } else if(binSize < 0){ throw new IllegalArgumentException(); } } return permutation; } public static int numPermutations(List<Integer> binSizes) { if(binSizes.isEmpty()) { return 0; } List<Integer> maxValues = new ArrayList<>(); for(int i = 0; i < binSizes.size(); i++) { int size = binSizes.get(i) - 1; if(size < 0) { size = 0; } maxValues.add(size); } return toPermutation(maxValues, binSizes) + 1; } /** * produce a list of ints from 0 to limit - 1 (inclusively) * @param j the limit * @return */ public static <A extends List<Integer>> A sequence(int j, A list) { for(int i = 0; i < j; i++) { list.add(i); } return list; } public static List<Integer> sequence(int j) { return sequence(j, new ArrayList<>(j)); } public static Integer[] box(int[] array) { Integer[] boxed = new Integer[array.length]; for(int i = 0; i < array.length; i++) { boxed[i] = array[i]; } return boxed; } public static Long[] box(long[] array) { Long[] boxed = new Long[array.length]; for(int i = 0; i < array.length; i++) { boxed[i] = array[i]; } return boxed; } public static Double[] box(double[] array) { Double[] boxed = new Double[array.length]; for(int i = 0; i < array.length; i++) { boxed[i] = array[i]; } return boxed; } public static Float[] box(float[] array) { Float[] boxed = new Float[array.length]; for(int i = 0; i < array.length; i++) { boxed[i] = array[i]; } return boxed; } public static Short[] box(short[] array) { Short[] boxed = new Short[array.length]; for(int i = 0; i < array.length; i++) { boxed[i] = array[i]; } return boxed; } public static Boolean[] box(boolean[] array) { Boolean[] boxed = new Boolean[array.length]; for(int i = 0; i < array.length; i++) { boxed[i] = array[i]; } return boxed; } public static Byte[] box(byte[] array) { Byte[] boxed = new Byte[array.length]; for(int i = 0; i < array.length; i++) { boxed[i] = array[i]; } return boxed; } public static Character[] box(char[] array) { Character[] boxed = new Character[array.length]; for(int i = 0; i < array.length; i++) { boxed[i] = array[i]; } return boxed; } public static String toString(double[][] matrix, String horizontalSeparator, String verticalSeparator) { StringBuilder builder = new StringBuilder(); for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { // builder.append(new BigDecimal(matrix[i][j]).setScale(2, RoundingMode.HALF_UP).doubleValue()); builder.append(matrix[i][j]); if(j != matrix[i].length - 1) { builder.append(horizontalSeparator); } } if(i != matrix.length - 1) { builder.append(verticalSeparator); } } builder.append(System.lineSeparator()); return builder.toString(); } public static String toString(int[][] matrix, String horizontalSeparator, String verticalSeparator) { StringBuilder builder = new StringBuilder(); for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { // builder.append(new BigDecimal(matrix[i][j]).setScale(2, RoundingMode.HALF_UP).doubleValue()); builder.append(matrix[i][j]); if(j != matrix[i].length - 1) { builder.append(horizontalSeparator); } } if(i != matrix.length - 1) { builder.append(verticalSeparator); } } builder.append(System.lineSeparator()); return builder.toString(); } public static int sum(final int... nums) { int sum = 0; for(int num : nums) { sum += num; } return sum; } public static int sum(Iterator<Integer> iterator) { int sum = 0; while(iterator.hasNext()) { sum += iterator.next(); } return sum; } public static int sum(Iterable<Integer> iterable) { return sum(iterable.iterator()); } public static double[] uniformDistribution(final int limit) { double[] result = new double[limit]; double amount = 1d / limit; for(int i = 0; i < limit; i++) { result[i] = amount; } return result; } }
17,145
29.67263
127
java
tsml-java
tsml-java-master/src/main/java/utilities/ClassifierTools.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; /* * Created on Dec 4, 2005 */ import java.util.ArrayList; import java.util.Random; import evaluation.evaluators.SingleTestSetEvaluator; import evaluation.storage.ClassifierResults; import experiments.data.DatasetLoading; import fileIO.OutFile; import machine_learning.classifiers.kNN; import statistics.distributions.NormalDistribution; import tsml.classifiers.TSClassifier; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import weka.classifiers.Classifier; import weka.classifiers.bayes.NaiveBayes; import java.util.logging.Level; import tsml.classifiers.EnhancedAbstractClassifier; import tsml.classifiers.distance_based.utils.classifiers.contracting.TimedTest; import tsml.classifiers.distance_based.utils.classifiers.results.ResultUtils; import tsml.classifiers.distance_based.utils.system.logging.Loggable; import tsml.classifiers.distance_based.utils.system.memory.MemoryWatcher; import tsml.classifiers.distance_based.utils.system.timing.StopWatch; import weka.classifiers.evaluation.EvaluationUtils; import weka.classifiers.evaluation.NominalPrediction; import weka.classifiers.functions.SMO; import weka.classifiers.functions.supportVector.PolyKernel; import weka.classifiers.lazy.IBk; import weka.classifiers.meta.RotationForest; import weka.classifiers.trees.J48; import weka.classifiers.trees.RandomForest; import weka.core.*; import weka.filters.supervised.attribute.NominalToBinary; import weka.filters.unsupervised.attribute.ReplaceMissingValues; /** * @author ajb * *Methods to perform Classification tasks with Weka which I cant seem to *do in Weka */ public class ClassifierTools { /** * Simple util to find the accuracy of a trained classifier on a test set. Probably is a built in method for this! * @param test * @param c * @return accuracy of classifier c on Instances test */ public static double accuracy(Instances test, Classifier c){ double a=0; int size=test.numInstances(); Instance d; double predictedClass,trueClass; for(int i=0;i<size;i++) { d=test.instance(i); try{ predictedClass=c.classifyInstance(d); trueClass=d.classValue(); if(trueClass==predictedClass) a++; // System.out.println("True = "+trueClass+" Predicted = "+predictedClass); }catch(Exception e){ System.out.println(" Error with instance "+i+" with Classifier "+c.getClass().getName()+" Exception ="+e); e.printStackTrace(); System.exit(0); } } return a/size; } public static double accuracy(TimeSeriesInstances test, TSClassifier c){ double a=0; int size=test.numInstances(); TimeSeriesInstance d; double predictedClass,trueClass; for(int i=0;i<size;i++) { d=test.get(i); try{ predictedClass=c.classifyInstance(d); trueClass=d.getLabelIndex(); if(trueClass==predictedClass) a++; // System.out.println("True = "+trueClass+" Predicted = "+predictedClass); }catch(Exception e){ System.out.println(" Error with instance "+i+" with Classifier "+c.getClass().getName()+" Exception ="+e); e.printStackTrace(); System.exit(0); } } return a/size; } public static Classifier[] setDefaultSingleClassifiers(ArrayList<String> names){ ArrayList<Classifier> sc2=new ArrayList<>(); sc2.add(new kNN(1)); names.add("NN"); Classifier c; sc2.add(new NaiveBayes()); names.add("NB"); sc2.add(new J48()); names.add("C45"); c=new SMO(); PolyKernel kernel = new PolyKernel(); kernel.setExponent(1); ((SMO)c).setKernel(kernel); sc2.add(c); names.add("SVML"); c=new SMO(); kernel = new PolyKernel(); kernel.setExponent(2); ((SMO)c).setKernel(kernel); sc2.add(c); names.add("SVMQ"); c=new RandomForest(); ((RandomForest)c).setNumTrees(100); sc2.add(c); names.add("RandF100"); c=new RotationForest(); sc2.add(c); names.add("RotF30"); Classifier[] sc=new Classifier[sc2.size()]; for(int i=0;i<sc.length;i++) sc[i]=sc2.get(i); return sc; } /** * This method returns the data in the same order it was given, and returns probability distributions for each test data * Assume data is randomised already * @param trainData * @param testData * @param c * @return distributionForInstance for each Instance in testData */ public static double[][] predict(Instances trainData,Instances testData, Classifier c){ double[][] results=new double[testData.numInstances()][]; try{ c.buildClassifier(trainData); for(int i=0;i<testData.numInstances();i++) results[i]=c.distributionForInstance(testData.instance(i)); }catch(Exception e){ System.out.println(" Error in manual cross val"); } return results; } /** * This method does a cross validation using the EvaluationUtils and stores the predicted and actual values. * I implemented this because I saw no way of using the built in cross vals to get the actual predictions, * useful for e.g McNemar's test (and cv variance). Note that the use of FastVector has been depreciated * @param c * @param allData * @param m * @return */ @SuppressWarnings({ "deprecation", "rawtypes" }) public static double[][] crossValidation(Classifier c, Instances allData, int m){ EvaluationUtils evalU; double[][] preds=new double[2][allData.numInstances()]; Object[] p; FastVector f; NominalPrediction nom; try{ evalU=new EvaluationUtils(); evalU.setSeed(10); f=evalU.getCVPredictions(c,allData,m); p=f.toArray(); for(int i=0;i<p.length;i++) { nom=((NominalPrediction)p[i]); preds[1][i]=nom.predicted(); preds[0][i]=nom.actual(); } }catch(Exception e){ System.out.println(" Error ="+e+" in method Cross Validate Experiment"); e.printStackTrace(); System.out.println(allData.relationName()); System.exit(0); } return preds; } /** * This method does a cross validation using the EvaluationUtils and stores t * he predicted and actual values. * Accuracy is stored in preds[0][0], StdDev of accuracy between folds SHOULD BE * stored in preds[1][0]. * TO IMPLEMENT! * Could do with some testing, there is some uncertainty over the last fold. * @param allData * @param m * @return */ @SuppressWarnings({ "deprecation", "rawtypes" }) public static double[][] crossValidationWithStats(Classifier c, Instances allData, int m) { EvaluationUtils evalU; double[][] preds=new double[2][allData.numInstances()+1]; int foldSize=allData.numInstances()/m; //Last fold may have fewer cases than this FastVector f; Object[] p; NominalPrediction nom; double acc=0,sum=0,sumsq=0; try{ evalU=new EvaluationUtils(); // evalU.setSeed(10); f=evalU.getCVPredictions(c,allData,m); p=f.toArray(); for(int i=0;i<p.length;i++) { nom=((NominalPrediction)p[i]); preds[1][i+1]=nom.predicted(); preds[0][i+1]=nom.actual(); // System.out.println(" pred = "+preds[i+1]); if(preds[0][i+1]==preds[1][i+1]){ preds[0][0]++; acc++; } if((i>0 && i%foldSize==0)){ //Sum Squares sumsq+=(acc/foldSize)*(acc/foldSize); //Sum sum+=(acc/foldSize); acc=0; } } //Accuracy stored in preds[0][0] preds[0][0]=preds[0][0]/p.length; preds[1][0]=(sumsq-sum*sum/m)/m; preds[1][0]=Math.sqrt(preds[1][0]); }catch(Exception e) { System.out.println(" Error ="+e+" in method Cross Validate Experiment"); e.printStackTrace(); System.out.println(allData.relationName()); System.exit(0); } return preds; } public static double stratifiedCrossValidation(Instances data, Classifier c, int folds, int seed) throws Exception{ Random rand = new Random(seed); // create seeded number generator Instances randData = new Instances(data); // create copy of original data randData.randomize(rand); // randomize data with number generator randData.stratify(folds); int correct=0; int total=data.numInstances(); for (int n = 0; n < folds; n++) { Instances train = randData.trainCV(folds, n); Instances test = randData.testCV(folds, n); c.buildClassifier(train); for(Instance ins:test){ int pred=(int)c.classifyInstance(ins); if(pred==ins.classValue()) correct++; } // System.out.println("Finished fold "+n+" acc ="+((double)correct/((n+1)*test.numInstances()))); } return ((double)correct)/total; } /** * This does a manual cross validation (i.e. without EvalUtils) and rather confusingly returns * the distribution for each Instance (as opposed to the predicted/actual in method performCrossValidation * @param data * @param c * @param numFolds * @return distribution for each Instance */ public static double[][] performManualCrossValidation(Instances data, Classifier c, int numFolds) { double[][] results=new double[data.numInstances()][data.numClasses()]; Instances train; Instances test; int interval = data.numInstances()/numFolds; int start=0; int end=interval; int testCount=0; try{ for(int f=0;f<numFolds;f++){ //Split Data train=new Instances(data,0); test=new Instances(data,0); for(int i=0;i<data.numInstances();i++){ if(i>=start && i<end) test.add(data.instance(i)); else train.add(data.instance(i)); } //Classify on training c.buildClassifier(data); //Predict for(int i=0;i<interval;i++){ results[testCount]=c.distributionForInstance(test.instance(i)); testCount++; } //Increment start=end; end=end+interval; } }catch(Exception e){ System.out.println(" Error in manual cross val"); } return results; } /** * Writes the predictions vs actual of a pre trained classifier to a file * @param model * @param data * @param path */ public static void makePredictions(Classifier model,Instances data, String path){ OutFile f1 = new OutFile(path+".csv"); double actual,pred; Instance t; try{ for(int i=0;i<data.numInstances();i++){ t=data.instance(i); actual=t.classValue(); pred=model.classifyInstance(t); f1.writeLine(i+","+actual+","+pred); } }catch(Exception e){ System.out.println("Exception in makePredictions"+e); } } public static Classifier[] setSingleClassifiers(ArrayList<String> names){ ArrayList<Classifier> sc2=new ArrayList<Classifier>(); IBk k=new IBk(50); k.setCrossValidate(true); sc2.add(k); names.add("kNN"); Classifier c; sc2.add(new NaiveBayes()); names.add("NB"); sc2.add(new J48()); names.add("C45"); c=new SMO(); PolyKernel kernel = new PolyKernel(); kernel.setExponent(1); ((SMO)c).setKernel(kernel); sc2.add(c); names.add("SVML"); c=new SMO(); kernel = new PolyKernel(); kernel.setExponent(2); ((SMO)c).setKernel(kernel); sc2.add(c); names.add("SVMQ"); c=new RandomForest(); ((RandomForest)c).setNumTrees(100); sc2.add(c); names.add("RandF100"); c=new RotationForest(); sc2.add(c); names.add("RotF30"); Classifier[] sc=new Classifier[sc2.size()]; for(int i=0;i<sc.length;i++) sc[i]=sc2.get(i); return sc; } public static double singleTrainTestSplitAccuracy(Classifier c, Instances train, Instances test){ //Perform a simple experiment, double acc=0; try{ c.buildClassifier(train); int correct=0; for(Instance ins:test){ int pred=(int)c.classifyInstance(ins); // System.out.println((int)ins.classValue()+","+pred); if(pred==(int)ins.classValue()) correct++; } acc=correct/(double)test.numInstances(); }catch(Exception e) { System.out.println(" Error ="+e+" in method singleTrainTestSplitAccuracy"+e); e.printStackTrace(); System.exit(0); } return acc; } /* Returns probability distribution for each instance with no randomisation */ public static double[][] crossValidate(Classifier c,Instances data, int numFolds) { double[][] results=new double[data.numInstances()][data.numClasses()]; Instances train; Instances test; int interval = data.numInstances()/numFolds; int start=0; int end=interval; int testCount=0; try{ for(int f=0;f<numFolds;f++){ if(f==numFolds-1) end=data.numInstances(); //Split Data train=new Instances(data,0); test=new Instances(data,0); for(int i=0;i<data.numInstances();i++){ if(i>=start && i<end) test.add(data.instance(i)); else train.add(data.instance(i)); } //Classify on training c.buildClassifier(train); //Predict for(int i=0;i<test.numInstances();i++){ results[testCount]=c.distributionForInstance(test.instance(i)); testCount++; } //Increment start=end; end=end+interval; } }catch(Exception e){ System.out.println(" Error in manual cross val"); } return results; } public static ClassifierResults constructClassifierResults(Classifier classifier, Instances test) throws Exception{ //jamesl: no usages reported 19/02/2019, but this function header left in and refactored to //use up to date method in case external usages exist return new SingleTestSetEvaluator().evaluate(classifier, test); } /** * Conducts a full run of a classifier on some train and test data with a set seed, printing off the stats / results. This is intended for reducing boilerplate main method code in each classifier. * @param classifier * @param trainAndTestData * @param seed * @throws Exception */ public static void trainTestPrint(Classifier classifier, Instances[] trainAndTestData, int seed) throws Exception { if(classifier instanceof Randomizable) { ((Randomizable) classifier).setSeed(seed); } Random random = new Random(seed); MemoryWatcher overallMemoryWatcher = new MemoryWatcher(); StopWatch overallTimer = new StopWatch(); overallMemoryWatcher.resetAndStart(); overallTimer.resetAndStart(); MemoryWatcher memoryWatcher = new MemoryWatcher(); StopWatch timer = new StopWatch(); if(classifier instanceof Loggable) { ((Loggable) classifier).setLogLevel(Level.ALL); } final Instances trainData = trainAndTestData[0]; final Instances testData = trainAndTestData[1]; timer.resetAndStart(); memoryWatcher.resetAndStart(); classifier.buildClassifier(trainData); timer.stop(); memoryWatcher.stop(); System.out.println(); System.out.println("train time: " + timer.elapsedTime()); System.out.println("train mem: " + memoryWatcher.getMaxMemoryUsage()); System.out.println(); // GcFinalization.awaitFullGc(); if(classifier instanceof EnhancedAbstractClassifier) { if(((EnhancedAbstractClassifier) classifier).getEstimateOwnPerformance()) { ClassifierResults trainResults = ((EnhancedAbstractClassifier) classifier).getTrainResults(); ResultUtils.setInfo(trainResults, classifier, trainData); System.out.println("train results:"); System.out.println(trainResults.writeFullResultsToString()); System.out.println("train acc: " + trainResults.getAcc()); System.out.println(); } } timer.resetAndStart(); memoryWatcher.resetAndStart(); ClassifierResults testResults = new ClassifierResults(); for(Instance instance : testData) { addPrediction(classifier, instance, testResults, random); } memoryWatcher.stop(); timer.stop(); ResultUtils.setInfo(testResults, classifier, trainData); System.out.println("test time: " + timer.elapsedTime()); System.out.println("test mem: " + memoryWatcher.getMaxMemoryUsage()); System.out.println("test results:"); System.out.println(testResults.writeFullResultsToString()); System.out.println("test acc: " + testResults.getAcc()); overallMemoryWatcher.stop(); overallTimer.stop(); System.out.println(); System.out.println("overall time: " + overallTimer.elapsedTime()); System.out.println("overall mem: " + overallMemoryWatcher.getMaxMemoryUsage()); } /** * Add the prediction of several test cases to a results object. * @param classifier * @param testData * @param results * @param random * @throws Exception */ public static void addPredictions(Classifier classifier, Instances testData, ClassifierResults results, Random random) throws Exception { for(Instance test : testData) { addPrediction(classifier, test, results, random); } } public static void addPredictions(TSClassifier classifier, TimeSeriesInstances testData, ClassifierResults results, Random random) throws Exception { for(TimeSeriesInstance test : testData) { addPrediction(classifier, test, results, random); } } /** * Add a prediction of a single test case to a results obj. * @param classifier * @param test * @param results * @param random * @throws Exception */ public static void addPrediction(Classifier classifier, Instance test, ClassifierResults results, Random random) throws Exception { final double classValue = test.classValue(); test.setClassMissing(); long timestamp = System.nanoTime(); final double[] distribution = classifier.distributionForInstance(test); long testTime = System.nanoTime() - timestamp; if(classifier instanceof TimedTest) { testTime = ((TimedTest) classifier).getTestTime(); } final double prediction = Utilities.argMax(distribution, random); results.addPrediction(classValue, distribution, prediction, testTime, null); test.setClassValue(classValue); } public static void addPrediction(TSClassifier classifier, TimeSeriesInstance test, ClassifierResults results, Random random) throws Exception { final double classValue = test.getLabelIndex(); test = new TimeSeriesInstance(test, -1); long timestamp = System.nanoTime(); final double[] distribution = classifier.distributionForInstance(test); long testTime = System.nanoTime() - timestamp; if(classifier instanceof TimedTest) { testTime = ((TimedTest) classifier).getTestTime(); } final double prediction = Utilities.argMax(distribution, random); results.addPrediction(classValue, distribution, prediction, testTime, null); } public static class ResultsStats{ public double accuracy; public double sd; public double min; public double max; public ResultsStats(){ accuracy=0; sd=0; } public ResultsStats(double[][] preds, int folds){ findCVMeanSD(preds,folds); } public static ResultsStats find(double[][] preds, int folds){ ResultsStats f=new ResultsStats(); f.findCVMeanSD(preds,folds); return f; } public void findCVMeanSD(double[][] preds, int folds){ double[] acc= new double[folds]; //System.out.println("No. of folds = "+acc.length); // Test output int count=0; // Changed from 1 int window=(preds[0].length-1)/folds; //Put any excess in the last fold window=(preds[0].length)/folds; //Changed from length-1 //System.out.println("Window = "+window+" readings; excess goes in last fold"); // Test output for(int i=0;i<folds-1;i++){ acc[i]=0; for(int j=0;j<window;j++){ if(preds[0][count]==preds[1][count]) acc[i]++; count++; } } //Last fold is the remainder int lastSize=preds[0].length-count; //System.out.println("Last fold has " + lastSize + " instances.");//Test output for(int j=count;j<preds[0].length;j++){ if(preds[0][count]==preds[1][count]) acc[folds-1]++; count++; } //System.out.println("Final fold has accuracy = " + acc[folds-1]);//Test outputs //Find mean, min and max accuracy=acc[0]; //System.out.println("First fold accuracy = "+accuracy);//Test output //min=1.0; // Should be acc[0]; min=acc[0]; max=0; for(int i=1;i<folds;i++){ accuracy+=acc[i]; //System.out.println("Sum of accuracies = " + accuracy);//Test output if(acc[i]<min) min=acc[i]; if(acc[i]>max) max=acc[i]; } //System.out.println(accuracy+"/"+(preds[0].length));//Test output accuracy/=preds[0].length;//Changed from length -1. //System.out.println(accuracy);//Test output //Find SD sd=0; for(int i=0;i<folds-1;i++)// Changed from int i=1 { sd+=(acc[i]/window-accuracy)*(acc[i]/window-accuracy); //System.out.println("Accuracy used here = " +acc[i]); //Test output, added braces. } sd+=(acc[folds-1]/lastSize-accuracy)*(acc[folds-1]/lastSize-accuracy);//Last fold sd/=folds; sd=Math.sqrt(sd); } public String toString(){ return "Accuracy = "+accuracy+" SD = "+sd+" Min = "+min+" Max = "+max; //Added some spaces } } // public static void main(String[] args) // Test harness. // { // // double[][] preds = { // {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0}, // {1.0, 5.0, 3.0,4.0,5.0,6.0,3.0,8.0,9.0} // }; // // double[][] preds2 = { // {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0}, // {1.4, 5.0, 3.0,4.0,5.0,6.0,3.0,8.0,9.0} // }; // int folds = 3; // // //folds = preds[0].length; // // //System.out.println(folds); //// //// // // System.out.println("preds"); // ResultsStats rs = new ResultsStats(preds,folds); // // System.out.println(rs); // // System.out.println("preds2"); // rs = new ResultsStats(preds2,folds); // // System.out.println(rs); // // } /********** Some other random methods *****************/ //If the folds is 1, do a simple test/train split. Otherwise, do a cross validation by first combining the sets public static ResultsStats[] evalClassifiers(Instances test, Instances train, int folds,Classifier[] sc) throws Exception{ int nosClassifiers=sc.length; double[][] preds; ResultsStats[] mean=new ResultsStats[nosClassifiers]; int seed=100; for(int i=0;i<nosClassifiers;i++){ // String[] settings=sc[i].getOptions(); // for(String s:settings) // System.out.print(","+s); // System.out.print("\t folds ="+folds); if(folds>1){ // Combine the two files Instances full=new Instances(train);//Instances.mergeInstances(train, test); for(int j=0;j<test.numInstances();j++) full.add(test.instance(j)); Random rand = new Random(seed); // System.out.print("\t cases ="+full.numInstances()); full.randomize(rand); preds=crossValidation(sc[i],full,folds); mean[i]= ResultsStats.find(preds,full.numInstances()); // System.out.println("\t : "+mean[i].accuracy); } else{ sc[i].buildClassifier(train); mean[i]=new ResultsStats(); mean[i].accuracy=accuracy(test,sc[i]); // System.out.println("\t : "+mean[i].accuracy); } } return mean; } public static Instances estimateMissing(Instances data){ ReplaceMissingValues nb = new ReplaceMissingValues(); Instances nd=null; try{ nb.setInputFormat(data); Instance temp; int n = data.numInstances(); for(int i=0;i<n;i++) nb.input(data.instance(i)); System.out.println(" Instances input"); System.out.println(" Output format retrieved"); // nd=Filter.useFilter(data,nb); // System.out.println(" Filtered? num atts = "+nd.numAttributes()+" num inst = "+nd.numInstances()+" filter = "+nb); if(nb.batchFinished()) System.out.println(" batch finished "); nd=nb.getOutputFormat(); for(int i=0;i<n;i++) { temp=nb.output(); // System.out.println(temp); nd.add(temp); } }catch(Exception e) { System.out.println("Error in estimateMissing = "+e.toString()); nd=data; System.exit(0); } return nd; } /** * Converts all the categorical variables to binary * * NOTE dummy created for all values, so the matrix is not full rank * If a regression formulation required (e.g. 6 binarys for 7 attribute values) * call makeBinaryFullRank * @param data */ public static Instances makeBinary(Instances data){ NominalToBinary nb = new NominalToBinary(); Instances nd; try{ Instance temp; nb.setInputFormat(data); int n = data.numInstances(); for(int i=0;i<n;i++) nb.input(data.instance(i)); nd=nb.getOutputFormat(); for(int i=0;i<n;i++) { temp=nb.output(); // System.out.println(temp); nd.add(temp); } }catch(Exception e) { System.out.println("Error in NominalToBinary = "+e.toString()); nd=data; System.exit(0); } return nd; } /** * generates white noise attributes and random classes * @param numAtts * @param numCases * @param numClasses * @return */ public static Instances generateRandomProblem(int numAtts,int numCases, int numClasses){ String name="Random"+numAtts+"_"+numCases+"_"+numClasses; ArrayList<Attribute> atts=new ArrayList<>(numAtts); for(int i=0;i<numAtts;i++){ Attribute at=new Attribute("Rand"+i);//Assume defaults to numeric? atts.add(at); } //Add class value ArrayList<String> vals=new ArrayList<>(numClasses); for(int i=0;i<numClasses;i++) vals.add(i+""); atts.add(new Attribute("Response",vals)); //Add instances NormalDistribution norm=new NormalDistribution(0,1); Random rng=new Random(); Instances data=new Instances(name,atts,numCases); data.setClassIndex(numAtts); for(int i=0;i<numCases;i++){ Instance in= new DenseInstance(data.numAttributes()); for(int j=0;j<numAtts;j++){ double v=norm.simulate(); in.setValue(j, v); } //Class value double classV=rng.nextInt(numClasses); in.setValue(numAtts,classV); data.add(in); } return data; } /** * Simple utility method to evaluate the given classifier on the ItalyPowerDemand dataset (fold 0) * and return the results. */ public static ClassifierResults testUtils_evalOnIPD(Classifier c) throws Exception { int seed = 0; Instances[] data = DatasetLoading.sampleItalyPowerDemand(seed); SingleTestSetEvaluator eval = new SingleTestSetEvaluator(seed, true, true); return eval.evaluate(c, data[0], data[1]); } /** * Simple utility method to evaluate the classifier on the ItalyPowerDemand dataset (fold 0), * in order to get the expected accuracy in the first place. It is up to the human * that the value returned is in fact 'correct' to the best of their knowledge, * tests of this nature will only confirm reproducability, but the classifier * could e.g. be consistently WRONG. */ public static double testUtils_getIPDAcc(Classifier c) throws Exception { return testUtils_evalOnIPD(c).getAcc(); } /** * Simple utility method to evaluate the classifier on the ItalyPowerDemand dataset (fold 0), * and compare the test accuracy to a given expected value (defined by prior * experimentation/confirmation by human). */ public static boolean testUtils_confirmIPDReproduction(Classifier c, double expectedTestAccuracy, String dateOfExpectedAcc) throws Exception { ClassifierResults res = testUtils_evalOnIPD(c); System.out.println("Expected accuracy generated " + dateOfExpectedAcc); System.out.println("Expected accuracy: " + expectedTestAccuracy + " Actual accuracy: " + res.getAcc()); return res.getAcc() == expectedTestAccuracy; } }
32,992
36.364666
200
java
tsml-java
tsml-java-master/src/main/java/utilities/ClusteringUtilities.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import evaluation.storage.ClustererResults; import tsml.clusterers.EnhancedAbstractClusterer; import weka.core.DistanceFunction; import weka.core.Instance; import weka.core.Instances; import static utilities.ArrayUtilities.oneHot; public class ClusteringUtilities { public static double randIndex(double[] predicted, double[] actual){ double A = 0, B = 0, C = 0, D = 0; for (int i = 0; i < predicted.length; i++){ for (int n = 0; n < actual.length; n++){ if (i == n) continue; if (predicted[i] == predicted[n] && actual[i] == actual[n]){ A++; } else if (predicted[i] != predicted[n] && actual[i] != actual[n]){ B++; } else if (predicted[i] == predicted[n] && actual[i] != actual[n]){ C++; } else{ D++; } } } return (A + B)/(A + B + C + D); } public static double randIndex(double[] predicted, Instances inst){ double[] actual = inst.attributeToDoubleArray(inst.classIndex()); double A = 0, B = 0, C = 0, D = 0; for (int i = 0; i < predicted.length; i++){ for (int n = 0; n < actual.length; n++){ if (i == n) continue; if (predicted[i] == predicted[n] && actual[i] == actual[n]){ A++; } else if (predicted[i] != predicted[n] && actual[i] != actual[n]){ B++; } else if (predicted[i] == predicted[n] && actual[i] != actual[n]){ C++; } else{ D++; } } } return (A + B)/(A + B + C + D); } public static void zNormalise(Instances data) { for (Instance inst: data){ zNormalise(inst); } } public static void zNormalise(Instance inst){ double meanSum = 0; int length = inst.numAttributes(); if (length < 2) return; for (int i = 0; i < length; i++){ meanSum += inst.value(i); } double mean = meanSum / length; double squareSum = 0; for (int i = 0; i < length; i++){ double temp = inst.value(i) - mean; squareSum += temp * temp; } double stdev = Math.sqrt(squareSum/(length-1)); if (stdev == 0){ stdev = 1; } for (int i = 0; i < length; i++){ inst.setValue(i, (inst.value(i) - mean) / stdev); } } public static void zNormalise(double[] inst){ double meanSum = 0; for (int i = 0; i < inst.length; i++){ meanSum += inst[i]; } double mean = meanSum / inst.length; double squareSum = 0; for (int i = 0; i < inst.length; i++){ double temp = inst[i] - mean; squareSum += temp * temp; } double stdev = Math.sqrt(squareSum/(inst.length-1)); if (stdev == 0){ stdev = 1; } for (int i = 0; i < inst.length; i++){ inst[i] = (inst[i] - mean) / stdev; } } public static void zNormaliseWithClass(Instances data) { for (Instance inst: data){ zNormaliseWithClass(inst); } } public static void zNormaliseWithClass(Instance inst){ double meanSum = 0; int length = inst.numAttributes()-1; for (int i = 0; i < inst.numAttributes(); i++){ if (inst.classIndex() != i) { meanSum += inst.value(i); } } double mean = meanSum / length; double squareSum = 0; for (int i = 0; i < inst.numAttributes(); i++){ if (inst.classIndex() != i) { double temp = inst.value(i) - mean; squareSum += temp * temp; } } double stdev = Math.sqrt(squareSum/(length-1)); if (stdev == 0){ stdev = 1; } for (int i = 0; i < inst.numAttributes(); i++){ if (inst.classIndex() != i) { inst.setValue(i, (inst.value(i) - mean) / stdev); } } } //Create lower half distance matrix. public static double[][] createDistanceMatrix(Instances data, DistanceFunction distFunc){ double[][] distMatrix = new double[data.numInstances()][]; distFunc.setInstances(data); for (int i = 0; i < data.numInstances(); i++){ distMatrix[i] = new double[i+1]; Instance first = data.get(i); for (int n = 0; n < i; n++){ distMatrix[i][n] = distFunc.distance(first, data.get(n)); } } return distMatrix; } //Create full distance matrix. public static double[][] createFullDistanceMatrix(Instances data, DistanceFunction distFunc){ double[][] distMatrix = new double[data.numInstances()][]; distFunc.setInstances(data); for (int i = 0; i < data.numInstances(); i++){ distMatrix[i] = new double[data.numInstances()]; Instance first = data.get(i); for (int n = 0; n < data.numInstances(); n++){ distMatrix[i][n] = distFunc.distance(first, data.get(n)); } } return distMatrix; } public static ClustererResults getClusteringResults(EnhancedAbstractClusterer clusterer, Instances inst) throws Exception { ClustererResults cr = new ClustererResults(inst.numClasses(), inst.attributeToDoubleArray(inst.classIndex()), clusterer.getAssignments(), oneHot(clusterer.numberOfClusters(), clusterer.getAssignments()), new long[inst.numInstances()], null); return cr; } }
6,791
28.789474
117
java
tsml-java
tsml-java-master/src/main/java/utilities/DebugPrinting.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.util.function.Consumer; /** * Just saves some time/copied code when making new classes * * And in general the codebase needed a bit more hacky-ness to it * * @author James Large */ public interface DebugPrinting { final static Consumer<String> printer = (s) -> System.out.print(s); final static Consumer<String> printlner = (s) -> System.out.println(s); final static Consumer<String> nothing_placeholder = (s) -> { }; //defaults to printing nothing static Consumer[] printers = new Consumer[] { nothing_placeholder, nothing_placeholder }; default void setDebugPrinting(boolean b) { if (b) { printers[0] = printer; printers[1] = printlner; } else { printers[0] = nothing_placeholder; printers[1] = nothing_placeholder; } } default boolean getDebugPrinting() { return printers[0] == nothing_placeholder; } default void printDebug(String str) { printers[0].accept(str); } default void printlnDebug(String str) { printers[1].accept(str); } }
1,930
30.655738
93
java
tsml-java
tsml-java-master/src/main/java/utilities/ErrorReport.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; /** * Noddy little class for situations where multiple exceptions may be thrown during some * action and you want to collect/report them all instead of just the first to help with debugging * * @author James Large (james.large@uea.ac.uk) */ public class ErrorReport { private boolean anyErrors; private String errorLog; public ErrorReport(String msgHeader) { errorLog = msgHeader; } public void log(String errorMsg) { anyErrors = true; errorLog += errorMsg; } public void throwIfErrors() throws Exception { if (anyErrors) throw new Exception(errorLog); } public boolean isEmpty() { return !anyErrors; }; public String getLog() { return errorLog; }; public void setLog(String newLog) { errorLog = newLog; }; }
1,591
32.87234
98
java
tsml-java
tsml-java-master/src/main/java/utilities/FileHandlingTools.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /** * * @author James Large (james.large@uea.ac.uk) */ public class FileHandlingTools { public static void recursiveDelete(String directory) throws IOException { recursiveDelete(new File(directory)); } public static void recursiveDelete(File directory) throws IOException { if (directory.isDirectory()) { for (File subDirectory : directory.listFiles()) recursiveDelete(subDirectory); } Files.delete(directory.toPath()); // if (!directory.delete()) // throw new FileNotFoundException("Failed to delete file: " + directory); } /** * List the directories contained in the directory given */ public static File[] listDirectories(String baseDirectory) { return (new File(baseDirectory)).listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); } /** * List the directories contained in the directory given */ public static String[] listDirectoryNames(String baseDirectory) { return (new File(baseDirectory)).list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return dir.isDirectory(); } }); } /** * List the files contained in the directory given */ public static File[] listFiles(String baseDirectory) { return (new File(baseDirectory)).listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile(); } }); } /** * List the files contained in the directory given */ public static String[] listFileNames(String baseDirectory) { return (new File(baseDirectory)).list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return dir.isFile(); } }); } /** * List the files contained in the directory given, that end with the given suffix (file extension, generally) */ public static File[] listFilesEndingWith(String baseDirectory, String suffix) { return (new File(baseDirectory)).listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().endsWith(suffix); } }); } /** * List the files contained in the directory given, that match the given regex */ public static File[] listFilesMatchingRegex(String baseDirectory, String regex) { return (new File(baseDirectory)).listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().matches(regex); } }); } /** * List the files contained in the directory given, that contain the given term */ public static File[] listFilesContaining(String baseDirectory, String term) { return (new File(baseDirectory)).listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().contains(term); } }); } /** * List the files contained in the directory given, that end with the given suffix (file extension, generally) */ public static String[] listFileNamesEndingWith(String baseDirectory, String suffix) { return (new File(baseDirectory)).list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return dir.isFile() && name.endsWith(suffix); } }); } }
4,896
33.006944
114
java
tsml-java
tsml-java-master/src/main/java/utilities/FileUtils.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; public class FileUtils { public static boolean isEmptyDir(String path) { final File file = new File(path); if(file.exists() && file.isDirectory()) { final File[] files = file.listFiles(); return files == null || files.length == 0; } return true; } public static void writeToFile(String str, String path) throws IOException { makeParentDir(path); BufferedWriter writer = new BufferedWriter(new FileWriter(path)); writer.write(str); writer.close(); } public static void writeToFile(String str, File file) throws IOException { writeToFile(str, file.getPath()); } public static String readFromFile(String path) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(path)); String line; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line); builder.append(System.lineSeparator()); } reader.close(); return builder.toString(); } public static String readFromFile(File path) throws IOException { return readFromFile(path.getPath()); } public static void copy(String src, String dest) throws IOException { copy(Paths.get(src), Paths.get(dest)); } public static void copy(Path src, Path dest) throws IOException { try (Stream<Path> stream = Files.walk(src)) { stream.forEach(source -> { try { Files.copy(source, dest.resolve(src.relativize(source)), REPLACE_EXISTING); } catch(IOException e) { throw new IllegalStateException(e); } }); } } public static void delete(String src) throws IOException { delete(Paths.get(src)); } public static void delete(Path src) throws IOException { if(!Files.exists(src)) { return; } List<Path> paths = Files.walk(src).collect(Collectors.toList()); Collections.reverse(paths); try (Stream<Path> stream = paths.stream()) { stream.forEach(source -> { try { Files.delete(source); } catch(IOException e) { throw new IllegalStateException(e); } }); } } public static void makeDir(String filePath) { makeParentDir(new File(filePath)); } public static void makeDir(File file) { makeParentDir(file); file.mkdirs(); } public static void makeParentDir(String filePath) { makeParentDir(new File(filePath)); } public static void makeParentDir(File file) { File parent = file.getParentFile(); if(parent != null) { parent.mkdirs(); } } public static boolean rename(final String src, final String dest) { makeParentDir(dest); return new File(src).renameTo(new File(dest)); } public static class FileLock implements AutoCloseable { public static class LockException extends RuntimeException { public LockException(String s) { super(s); } } private Thread thread; private File file; private File lockFile; private static final long interval = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES); private static final long expiredInterval = interval + TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES); private final AtomicBoolean unlocked = new AtomicBoolean(true); private int lockCount = 0; public int getLockCount() { return lockCount; } public File getFile() { return file; } public File getLockFile() { return lockFile; } public FileLock(String path, boolean lock) { this(new File(path), lock); } public FileLock(File file, boolean lock) { this.file = file; this.lockFile = new File(file.getPath() + ".lock"); if(lock) { lock(); } } public FileLock(File file) { // assume we want to lock the file asap this(file, true); } public FileLock(String path) { this(new File(path)); } public FileLock lock() { if(isUnlocked()) { makeParentDir(lockFile); boolean stop = false; while(!stop) { boolean created = false; try { created = lockFile.createNewFile(); } catch(IOException ignored) {} if(created) { lockFile.deleteOnExit(); unlocked.set(false); thread = new Thread(this::watch); thread.setDaemon(true); thread.start(); lockCount++; return this; } else { long lastModified = lockFile.lastModified(); if(lastModified <= 0 || lastModified + expiredInterval < System.currentTimeMillis()) { stop = !lockFile.delete(); } else { stop = true; } } } throw new LockException("failed to lock file: " + file.getPath()); } lockCount++; return this; } private void watch() { do { boolean setLastModified = lockFile.setLastModified(System.currentTimeMillis()); if(!setLastModified) { unlocked.set(true); } if(!unlocked.get()) { try { Thread.sleep(interval); } catch (InterruptedException e) { unlocked.set(true); } } } while (!unlocked.get()); lockFile.delete(); } public FileLock unlock() { lockCount--; if(lockCount == 0) { unlocked.set(true); if(thread != null) { thread.interrupt(); do { try { thread.join(); } catch(InterruptedException ignored) { } } while(thread.isAlive()); thread = null; } } else if(lockCount < 0) { throw new LockException(file.getPath() + " already unlocked"); } return this; } public boolean isUnlocked() { return unlocked.get(); } public boolean isLocked() { return !isUnlocked(); } @Override public void close() throws Exception { unlock(); } } }
8,632
31.092937
114
java
tsml-java
tsml-java-master/src/main/java/utilities/FileUtilsTest.java
package utilities; import org.junit.Assert; import org.junit.Test; import java.io.File; public class FileUtilsTest { @Test public void testFileLock() { final File file = new File("hello.txt"); final FileUtils.FileLock lock = new FileUtils.FileLock(file); Assert.assertEquals(file.getPath() + ".lock", lock.getLockFile().getPath()); Assert.assertTrue(lock.getLockFile().exists()); Assert.assertEquals(1, lock.getLockCount()); lock.unlock(); Assert.assertFalse(lock.getLockFile().exists()); Assert.assertEquals(0, lock.getLockCount()); lock.lock(); Assert.assertTrue(lock.getLockFile().exists()); Assert.assertEquals(1, lock.getLockCount()); lock.lock(); Assert.assertTrue(lock.getLockFile().exists()); Assert.assertEquals(2, lock.getLockCount()); lock.unlock(); Assert.assertTrue(lock.getLockFile().exists()); Assert.assertEquals(1, lock.getLockCount()); lock.unlock(); Assert.assertFalse(lock.getLockFile().exists()); Assert.assertEquals(0, lock.getLockCount()); } }
1,147
32.764706
84
java
tsml-java
tsml-java-master/src/main/java/utilities/FoldCreator.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import utilities.InstanceTools; import weka.core.Instances; /** * Base class to create folds from a dataset in a reproducable way. * This class can be subtyped to allow for dataset specific cross validation. * Examples include leave one person out (e.g. EpilepsyX) or leave one bottle out * (e.g. EthanolLevel) * * @author ajb */ public class FoldCreator { double prop=0.3; protected boolean deleteFirstAttribute=false;//Remove an index public void deleteFirstAtt(boolean b){ deleteFirstAttribute=b; } public FoldCreator(){ } public FoldCreator(double p){ prop=p; } public void setProp(double p){ prop=p; } public Instances[] createSplit(Instances data, int fold) throws Exception{ Instances[] split= InstanceTools.resampleInstances(data, fold, prop); if(deleteFirstAttribute){ split[0].deleteAttributeAt(0); split[1].deleteAttributeAt(0); } return split; } }
1,795
31.071429
81
java
tsml-java
tsml-java-master/src/main/java/utilities/GenericTools.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.io.File; import java.io.FileNotFoundException; import java.text.DecimalFormat; import java.util.*; /** * * @author raj09hxu */ public class GenericTools { public static final DecimalFormat RESULTS_DECIMAL_FORMAT = new DecimalFormat("#.######"); public static List<String> readFileLineByLineAsList(String filename) throws FileNotFoundException { Scanner filein = new Scanner(new File(filename)); List<String> dsets = new ArrayList<>(); while (filein.hasNextLine()) dsets.add(filein.nextLine()); return dsets; } public static String[] readFileLineByLineAsArray(String filename) throws FileNotFoundException { return readFileLineByLineAsList(filename).toArray(new String[] { }); } public static double indexOfMin(double[] dist) { double min = dist[0]; int minInd = 0; for (int i = 1; i < dist.length; ++i) { if (dist[i] < min) { min = dist[i]; minInd = i; } } return minInd; } public static int indexOfMin(int[] dist) { int min = dist[0]; int minInd = 0; for (int i = 1; i < dist.length; ++i) { if (dist[i] < min) { min = dist[i]; minInd = i; } } return minInd; } public static double min(double[] array) { return array[(int)indexOfMin(array)]; } public static int min(int[] array) { return array[indexOfMin(array)]; } public static double indexOfMax(double[] dist) { double max = dist[0]; int maxInd = 0; for (int i = 1; i < dist.length; ++i) { if (dist[i] > max) { max = dist[i]; maxInd = i; } } return maxInd; } public static double max(double[] array) { return array[(int)indexOfMax(array)]; } public static double indexOf(double[] array, double val){ for(int i=0; i<array.length; i++) if(array[i] == val) return i; return -1; } public static <E> ArrayList<E> cloneArrayList(ArrayList<E> list){ ArrayList<E> temp = new ArrayList<>(); for (E el : list) { temp.add(el); } return temp; } public static <E> ArrayList<E> twoDArrayToList(E[][] twoDArray) { ArrayList<E> list = new ArrayList<>(); for (E[] array : twoDArray){ if(array == null) continue; for(E elm : array){ if(elm == null) continue; list.add(elm); } } return list; } //this is inclusive of the top value. public static int randomRange(Random rand, int min, int max){ return rand.nextInt((max - min) + 1) + min; } public static String sprintf(String format, Object... strings){ StringBuilder sb = new StringBuilder(); String out; try (Formatter ft = new Formatter(sb, Locale.UK)) { ft.format(format, strings); out = ft.toString(); } return out; } /** * assumes it's a square matrix basically. uneven inner array lengths will mess up */ public static double[][] cloneAndTranspose(double[][] in) { double[][] out = new double[in[0].length][in.length]; for (int i = 0; i < in.length; i++) for (int j = 0; j < in[0].length; j++) out[j][i] = in[i][j]; return out; } public static class SortIndexDescending implements Comparator<Integer> { private double[] values; public SortIndexDescending(double[] values){ this.values = values; } public Integer[] getIndicies(){ Integer[] indicies = new Integer[values.length]; for (int i = 0; i < values.length; i++) { indicies[i] = i; } return indicies; } @Override public int compare(Integer index1, Integer index2) { if (values[index2] < values[index1]){ return -1; } else if (values[index2] > values[index1]){ return 1; } else{ return 0; } } } public static class SortIndexAscending implements Comparator<Integer>{ private double[] values; public SortIndexAscending(double[] values){ this.values = values; } public Integer[] getIndicies(){ Integer[] indicies = new Integer[values.length]; for (int i = 0; i < values.length; i++) { indicies[i] = i; } return indicies; } @Override public int compare(Integer index1, Integer index2) { if (values[index1] < values[index2]){ return -1; } else if (values[index1] > values[index2]){ return 1; } else{ return 0; } } } public static double[] linSpace(int numValues, double min, double max){ double[] d = new double[numValues]; double step = (max-min)/(numValues-1); for (int i = 0; i < numValues; i++){ d[i] = min + i * step; } return d; } public static int[] linSpace(int numValues, int min, int max){ int[] d = new int[numValues]; double step = (max-min)/(numValues-1.0); for (int i = 0; i < numValues; i++){ d[i] = (int)(min + i * step); } return d; } }
6,635
27.603448
103
java
tsml-java
tsml-java-master/src/main/java/utilities/InstanceTools.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.io.File; import java.io.FileWriter; import java.util.*; //import scala.tools.nsc.Global; import utilities.class_counts.ClassCounts; import utilities.class_counts.TreeSetClassCounts; import utilities.generic_storage.Pair; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.DistanceFunction; import weka.core.Instance; import weka.core.Instances; /** * * @author Aaron */ public class InstanceTools { public static double[] countClasses(Instances data) { return countClasses(data, data.numClasses()); } public static double[] countClasses(List<? extends Instance> data, int numClasses) { double[] distribution = new double[numClasses]; for(Instance instance : data) { final int classValue = (int) instance.classValue(); distribution[classValue] += instance.weight(); } return distribution; } public static Map<Instance, Integer> indexInstances(Instances instances) { Map<Instance, Integer> instanceIntegerMap = new HashMap<>(instances.size(), 1); for(int i = 0; i < instances.size(); i++) { instanceIntegerMap.put(instances.get(i), i); } return instanceIntegerMap; } public static void setClassMissing(Instances data) { for(Instance instance : data) { instance.setClassMissing(); } } public static Pair<Instance, Double> findMinDistance(Instances data, Instance inst, DistanceFunction dist){ double min = dist.distance(data.get(0), inst); Instance minI = data.get(0); for (int i = 1; i < data.numInstances(); i++) { double temp = dist.distance(data.get(i), inst); if(temp < min){ min = temp; minI = data.get(i); } } return new Pair(minI, min); } public static int[] deleteClassValues(Instances d){ int[] classVals=new int[d.numInstances()]; for(int i=0;i<d.numInstances();i++){ classVals[i]=(int)d.instance(i).classValue(); d.instance(i).setMissing(d.instance(i).classIndex()); } return classVals; } /** * By Aaron: * Public method to calculate the class distributions of a dataset. Main * purpose is for computing shapelet qualities. * * @param data the input data set that the class distributions are to be * derived from * @return a TreeMap<Double, Integer> in the form of <Class Value, * Frequency> */ public static Map<Double, Integer> createClassDistributions(Instances data) { Map<Double, Integer> classDistribution = new TreeMap<>(); ListIterator<Instance> it = data.listIterator(); double classValue; while (it.hasNext()) { classValue = it.next().classValue(); Integer val = classDistribution.get(classValue); val = (val != null) ? val + 1 : 1; classDistribution.put(classValue, val); } return classDistribution; } /** * by Tony * Public method to calculate the class distributions of a dataset. */ public static double[] findClassDistributions(Instances data) { double[] dist=new double[data.numClasses()]; for(Instance d:data) dist[(int)d.classValue()]++; for(int i=0;i<dist.length;i++) dist[i]/=data.numInstances(); return dist; } /** * by James... * Public method to calculate the class distributions given a list of class labels and the number of classes. * Mostly to use with the data classifierresults/results analysis tools keep */ public static double[] findClassDistributions(ArrayList<Double> classLabels, int numClasses) { double[] dist=new double[numClasses]; for(double d:classLabels) dist[(int)d]++; for(int i=0;i<dist.length;i++) dist[i]/=classLabels.size(); return dist; } public static Map<Double, Instances> createClassInstancesMap(Instances data) { Map<Double, Instances> instancesMap = new TreeMap<>(); ListIterator<Instance> it = data.listIterator(); double classValue; while (it.hasNext()) { Instance inst = it.next(); classValue = inst.classValue(); Instances val = instancesMap.get(classValue); if(val == null) val = new Instances(data, 0); val.add(inst); instancesMap.put(classValue, val); } return instancesMap; } /** * Modified from Aaron's shapelet resampling code in development.ReasamplingExperiments. Used to resample * train and test instances while maintaining original train/test class distributions * * @param train Input training instances * @param test Input test instances * @param seed Used to create reproducible folds by using a consistent seed value * @return Instances[] with two elements; [0] is the output training instances, [1] output test instances */ public static Instances[] resampleTrainAndTestInstances(Instances train, Instances test, long seed){ if(seed==0){ //For consistency, I have made this clone the data. Its not necessary generally, but not doing it // introduced a bug in diagnostics elsewhere Instances newTrain = new Instances(train); Instances newTest = new Instances(test); return new Instances[]{newTrain,newTest}; } Instances all = new Instances(train); all.addAll(test); ClassCounts trainDistribution = new TreeSetClassCounts(train); Map<Double, Instances> classBins = createClassInstancesMap(all); Random r = new Random(seed); //empty instances. Instances outputTrain = new Instances(all, 0); Instances outputTest = new Instances(all, 0); Iterator<Double> keys = classBins.keySet().iterator(); while(keys.hasNext()){ double classVal = keys.next(); int occurences = trainDistribution.get(classVal); Instances bin = classBins.get(classVal); bin.randomize(r); //randomise the bin. outputTrain.addAll(bin.subList(0,occurences));//copy the first portion of the bin into the train set outputTest.addAll(bin.subList(occurences, bin.size()));//copy the remaining portion of the bin into the test set. } return new Instances[]{outputTrain,outputTest}; } /** * * @param all full data set * @param seed random seed so that the split can be exactly duplicated * @param propInTrain proportion of data for training * @return */ public static Instances[] resampleInstances(Instances all, long seed, double propInTrain){ ClassCounts classDist = new TreeSetClassCounts(all); Map<Double, Instances> classBins = createClassInstancesMap(all); Random r = new Random(seed); //empty instances. Instances outputTrain = new Instances(all, 0); Instances outputTest = new Instances(all, 0); Iterator<Double> keys = classBins.keySet().iterator(); while(keys.hasNext()){ //For each class value double classVal = keys.next(); //Get the number of this class to put in train and test int classCount = classDist.get(classVal); int occurences=(int)(classCount*propInTrain); Instances bin = classBins.get(classVal); bin.randomize(r); //randomise the instances in this class. outputTrain.addAll(bin.subList(0,occurences));//copy the first portion of the bin into the train set outputTest.addAll(bin.subList(occurences, bin.size()));//copy the remaining portion of the bin into the test set. } return new Instances[]{outputTrain,outputTest}; } public static Instances resample(Instances series, double trainProportion, Random random) { int newSize = (int)(series.numInstances()*trainProportion); Instances newData = new Instances(series, newSize); Instances temp = new Instances(series); while (newData.numInstances() < newSize) { newData.add(temp.remove(random.nextInt(temp.numInstances()))); } return newData; } //converts a 2d array into a weka Instances. public static Instances toWekaInstances(double[][] data) { Instances wekaInstances = null; if (data.length <= 0) { return wekaInstances; } int dimRows = data.length; int dimColumns = data[0].length; // create a list of attributes features + label ArrayList<Attribute> attributes = new ArrayList<>(dimColumns); for (int i = 0; i < dimColumns; i++) { attributes.add(new Attribute("attr" + String.valueOf(i + 1))); } // add the attributes wekaInstances = new Instances("", attributes, dimRows); // add the values for (int i = 0; i < dimRows; i++) { double[] instanceValues = new double[dimColumns]; for (int j = 0; j < dimColumns; j++) { instanceValues[j] = data[i][j]; } wekaInstances.add(new DenseInstance(1.0, instanceValues)); } return wekaInstances; } //converts a 2d array into a weka Instances, setting the last attribute to be the class value. public static Instances toWekaInstancesWithClass(double[][] data) { Instances wekaInstances = toWekaInstances(data); wekaInstances.setClassIndex(wekaInstances.numAttributes()-1); return wekaInstances; } //converts a 2d array into a weka Instances, appending the ith classlabel onto the ith row of data for each instance public static Instances toWekaInstances(double[][] data, double[] classLabels) { //todo error checking if really wanted. all utils need it at some point double[][] newData = new double[data.length][]; for (int i = 0; i < data.length; i++) { newData[i] = new double[data[i].length + 1]; int j = 0; for ( ; j < data[i].length; j++) newData[i][j] = data[i][j]; newData[i][j] = classLabels[i]; } return toWekaInstancesWithClass(newData); } //converts a weka Instances into a 2d array - removing class val at the end. public static double[][] fromWekaInstancesArray(Instances ds, boolean removeLastVal) { int numFeatures = ds.numAttributes() - (removeLastVal ? 1 : 0); int numInstances = ds.numInstances(); double[][] data = new double[numInstances][numFeatures]; for (int i = 0; i < numInstances; i++) { for (int j = 0; j < numFeatures; j++) { data[i][j] = ds.get(i).value(j); } } return data; } //converts a weka Instances into a 2d array. public static ArrayList<ArrayList<Double>> fromWekaInstancesList(Instances ds) { int numFeatures = ds.numAttributes()-1; //no classValue int numInstances = ds.numInstances(); //Logging.println("Converting " + numInstances + " instances and " + numFeatures + " features.", LogLevel.DEBUGGING_LOG); ArrayList<ArrayList<Double>> data = new ArrayList<>(numInstances); ArrayList<Double> temp; for (int i = 0; i < numInstances; i++) { temp = new ArrayList<>(numFeatures); for (int j = 0; j < numFeatures; j++) { temp.add(ds.get(i).value(j)); } data.add(temp); } return data; } //this is for Grabockas train/test set combo matrix. removes the need for appending. public static double[][] create2DMatrixFromInstances(Instances train, Instances test) { double [][] data = new double[train.numInstances() + test.numInstances()][train.numAttributes()]; for(int i=0; i<train.numInstances(); i++) { for(int j=0; j<train.numAttributes(); j++) { data[i][j] = train.get(i).value(j); } } int index=0; for(int i=train.numInstances(); i<train.numInstances()+test.numInstances(); i++) { for(int j=0; j<test.numAttributes(); j++) { data[i][j] = test.get(index).value(j); } ++index; } return data; } // utility method for creating ARFF from UCR file without writing output, just returns Instances public static Instances convertFromUCRtoARFF(String inputFilePath) throws Exception{ return convertFromUCRtoARFF(inputFilePath, null, null); } // writes output and returns Instances too public static Instances convertFromUCRtoARFF(String inputFilePath, String outputRelationName, String fullOutputPath) throws Exception{ File input = new File(inputFilePath); if(!input.exists()){ throw new Exception("Error converting to ARFF - input file not found: "+input.getAbsolutePath()); } // get instance length Scanner scan = new Scanner(input); scan.useDelimiter("\n"); String firstIns = scan.next(); int numAtts = firstIns.split(",").length; // create attribute list ArrayList<Attribute> attList = new ArrayList<>(); for(int i = 0; i < numAtts-1; i++){ attList.add(new Attribute("att"+i)); } attList.add(new Attribute("classVal")); // create Instances object Instances output; if(outputRelationName==null){ output = new Instances("temp", attList, numAtts); }else{ output = new Instances(outputRelationName, attList, numAtts); } output.setClassIndex(numAtts-1); // populate Instances String[] nextIns; DenseInstance d; scan = new Scanner(input); scan.useDelimiter("\n"); while(scan.hasNext()){ nextIns = scan.next().split(","); d = new DenseInstance(numAtts); for(int a = 0; a < numAtts-1; a++){ d.setValue(a, Double.parseDouble(nextIns[a+1])); } d.setValue(numAtts-1, Double.parseDouble(nextIns[0])); output.add(d); } // if null, don't write. Else, write output ARFF here if(fullOutputPath!=null){ System.out.println(fullOutputPath.substring(fullOutputPath.length()-5, fullOutputPath.length())); if(!fullOutputPath.substring(fullOutputPath.length()-5, fullOutputPath.length()).equalsIgnoreCase(".ARFF")){ fullOutputPath += ".ARFF"; } new File(fullOutputPath).getParentFile().mkdirs(); FileWriter out = new FileWriter(fullOutputPath); out.append(output.toString()); out.close(); } return output; } public static void removeConstantTrainAttributes(Instances train, Instances test){ int i=0; while(i<train.numAttributes()-1){ //Dont test class // Test if constant int j=1; while(j<train.numInstances() && train.instance(j-1).value(i)==train.instance(j).value(i)) j++; if(j==train.numInstances()){ // Remove from train train.deleteAttributeAt(i); test.deleteAttributeAt(i); // Remove from test }else{ i++; } } } /** * * @param ins Instances object * @return true if there are any missing values (including class value) */ public static boolean hasMissing(Instances ins){ for(Instance in:ins) if(in.hasMissingValue()) return true; return false; } /** * Deletes the attributes by *shifted* index, i.e. the positions are *not* the * original positions in the data * @param test * @param features */ public static void removeConstantAttributes(Instances test, int[] features){ for(int del:features) test.deleteAttributeAt(del); } //Returns the *shifted* indexes, so just deleting them should work public static int[] removeConstantTrainAttributes(Instances train){ int i=0; LinkedList<Integer> list= new LinkedList<>(); int count=0; while(i<train.numAttributes()-1){ //Dont test class // Test if constant int j=1; while(j<train.numInstances() && train.instance(j-1).value(i)==train.instance(j).value(i)) j++; if(j==train.numInstances()){ // Remove from train train.deleteAttributeAt(i); list.add(i); // Remove from test }else{ i++; } count++; } int[] del=new int[list.size()]; count=0; for(Integer in:list){ del[count++]=in; } return del; } /** * Removes attributes deemed redundant. These are either * 1. All one value (i.e. constant) * 2. Some odd test to count the number different to the one before. * I think this is meant to count the number of different values? * It would be good to delete attributes that are identical to other attributes. * @param train instances from which to remove redundant attributes * @return array of indexes of attributes remove */ //Returns the *shifted* indexes, so just deleting them should work //Removes all constant attributes or attributes with just a single value public static int[] removeRedundantTrainAttributes(Instances train){ int i=0; int minNumDifferent=2; boolean remove=false; LinkedList<Integer> list= new LinkedList<>(); int count=0; while(i<train.numAttributes()-1){ //Dont test class remove=false; // Test if constant int j=1; if(train.instance(j-1).value(i)==train.instance(j).value(i)) while(j<train.numInstances() && train.instance(j-1).value(i)==train.instance(j).value(i)) j++; if(j==train.numInstances()) remove=true; else{ //Test pairwise similarity? //I think this is meant to test how many different values there are. If so, it should be //done with a HashSet of doubles. This counts how many values are identical to their predecessor count =0; for(j=1;j<train.numInstances();j++){ if(train.instance(j-1).value(i)==train.instance(j).value(i)) count++; } if(train.numInstances()-count<minNumDifferent+1) remove=true; } if(remove){ // Remove from data train.deleteAttributeAt(i); list.add(i); }else{ i++; } // count++; } int[] del=new int[list.size()]; count=0; for(Integer in:list){ del[count++]=in; } return del; } //be careful using this function. //this wants to create a proportional sub sample //but if you're sampling size is too small you could create a dodgy dataset. public static Instances subSample(Instances data, int amount, int seed){ if(amount < data.numClasses()) System.out.println("Error: too few instances compared to classes."); Map<Double, Instances> classBins = createClassInstancesMap(data); ClassCounts trainDistribution = new TreeSetClassCounts(data); Random r = new Random(seed); //empty instances. Instances output = new Instances(data, 0); Iterator<Double> keys = classBins.keySet().iterator(); while(keys.hasNext()){ double classVal = keys.next(); int occurences = trainDistribution.get(classVal); float proportion = (float) occurences / (float) data.numInstances(); int numInstances = (int) (proportion * amount); Instances bin = classBins.get(classVal); bin.randomize(r); //randomise the bin. output.addAll(bin.subList(0,numInstances));//copy the first portion of the bin into the train set } return output; } public static Instances subSampleFixedProportion(Instances data, double proportion, long seed){ Map<Double, Instances> classBins = createClassInstancesMap(data); ClassCounts trainDistribution = new TreeSetClassCounts(data); Random r = new Random(seed); //empty instances. Instances output = new Instances(data, 0); Iterator<Double> keys = trainDistribution.keySet().iterator(); while(keys.hasNext()){ double classVal = keys.next(); int occurences = trainDistribution.get(classVal); int numInstances = (int) (proportion * occurences); Instances bin = classBins.get(classVal); bin.randomize(r); //randomise the bin. output.addAll(bin.subList(0,numInstances));//copy the first portion of the bin into the train set } return output; } //use in conjunction with subSampleFixedProportion. //Instances subSample = InstanceTools.subSampleFixedProportion(train, proportion, fold); public static double calculateSubSampleProportion(Instances train, int min){ int small_sf = InstanceTools.findSmallestClassAmount(train); double proportion = 1; if (small_sf>min){ proportion = (double)min/(double)small_sf; if (proportion < 0.1) proportion = 0.1; } return proportion; } public static int findSmallestClassAmount(Instances data){ ClassCounts trainDistribution = new TreeSetClassCounts(data); //find the smallest represented class. Iterator<Double> keys = trainDistribution.keySet().iterator(); int small_sf = Integer.MAX_VALUE; int occurences; double key; while(keys.hasNext()){ key = keys.next(); occurences = trainDistribution.get(key); if(occurences < small_sf) small_sf = occurences; } return small_sf; } public static int indexOf(Instances dataset, Instance find){ int index = -1; for(int i=0; i<dataset.numInstances(); i++){ Instance in = dataset.get(i); boolean match = true; for(int j=0; j<in.numAttributes();j++){ if(in.value(j) != find.value(j)) match = false; } if(match){ index = i; break; } } return index; } public static int indexOf2(Instances dataset, Instance find){ int index = -1; for(int i=0; i< dataset.numInstances(); i++){ if(dataset.instance(i).toString(0).contains(find.toString(0))){ index = i; break; } } return index; } //similar to concatinate, but interweaves the attributes. //all of att_0 in each instance, then att_1 etc. public static Instances mergeInstances(String dataset, Instances[] inst, String[] dimChars){ ArrayList<Attribute> atts = new ArrayList<>(); String name; Instances firstInst = inst[0]; int dimensions = inst.length; int length = (firstInst.numAttributes()-1)*dimensions; for (int i = 0; i < length; i++) { name = dataset + "_" + dimChars[i%dimensions] + "_" + (i/dimensions); atts.add(new Attribute(name)); } //clone the class values over. //Could be from x,y,z doesn't matter. Attribute target = firstInst.attribute(firstInst.classIndex()); ArrayList<String> vals = new ArrayList<>(target.numValues()); for (int i = 0; i < target.numValues(); i++) { vals.add(target.value(i)); } atts.add(new Attribute(firstInst.attribute(firstInst.classIndex()).name(), vals)); //same number of xInstances Instances result = new Instances(dataset + "_merged", atts, firstInst.numInstances()); int size = result.numAttributes()-1; for(int i=0; i< firstInst.numInstances(); i++){ result.add(new DenseInstance(size+1)); for(int j=0; j<size;){ for(int k=0; k< dimensions; k++){ result.instance(i).setValue(j,inst[k].get(i).value(j/dimensions)); j++; } } } for (int j = 0; j < result.numInstances(); j++) { //we always want to write the true ClassValue here. Irrelevant of binarised or not. result.instance(j).setValue(size, firstInst.get(j).classValue()); } return result; } public static void deleteClassAttribute(Instances data){ if (data.classIndex() >= 0){ int clsIndex = data.classIndex(); data.setClassIndex(-1); data.deleteAttributeAt(clsIndex); } } public static List<Instances> instancesByClass(Instances instances) { List<Instances> instancesByClass = new ArrayList<>(); int numClasses = instances.get(0).numClasses(); for(int i = 0; i < numClasses; i++) { instancesByClass.add(new Instances(instances,0)); } for(Instance instance : instances) { instancesByClass.get((int) instance.classValue()).add(instance); } return instancesByClass; } public static List<List<Integer>> indexByClass(Instances instances) { List<List<Integer>> instancesByClass = new ArrayList<>(); int numClasses = instances.get(0).numClasses(); for(int i = 0; i < numClasses; i++) { instancesByClass.add(new ArrayList()); } for(int i = 0; i < instances.size(); i++) { instancesByClass.get((int) instances.get(i).classValue()).add(i); } return instancesByClass; } public static double[] classCounts(Instances instances) { double[] counts = new double[instances.numClasses()]; for(Instance instance : instances) { counts[(int) instance.classValue()]++; } return counts; } public static double[] classDistribution(Instances instances) { double[] distribution = new double[instances.numClasses()]; for(Instance instance : instances) { distribution[(int) instance.classValue()]++; } ArrayUtilities.normalise(distribution); return distribution; } /** * Concatenate features into a new Instances. Check is made that the class * values are the same * @param a * @param b * @return */ public static Instances concatenateInstances(Instances a, Instances b){ if(a.numInstances()!=b.numInstances()) throw new RuntimeException(" ERROR in concatenate Instances, number of cases unequal"); for(int i=0;i<a.numInstances();i++){ if(a.instance(i).classValue()!=b.instance(i).classValue()) throw new RuntimeException(" ERROR in concatenate Instances, class labels not alligned in case "+i+" class in a ="+a.instance(i).classValue()+" and in b equals "+b.instance(i).classValue()); } //4. Merge them all together Instances combo=new Instances(a); combo.setClassIndex(-1); combo.deleteAttributeAt(combo.numAttributes()-1); combo=Instances.mergeInstances(combo,b); combo.setClassIndex(combo.numAttributes()-1); return combo; } public static Map<Double, Instances> byClass(Instances instances) { Map<Double, Instances> map = new HashMap<>(); for(Instance instance : instances) { map.computeIfAbsent(instance.classValue(), k -> new Instances(instances, 0)).add(instance); } return map; } public static Instance reverseSeries(Instance inst){ Instance newInst = new DenseInstance(inst); for (int i = 0; i < inst.numAttributes()-1; i++){ newInst.setValue(i, inst.value(inst.numAttributes()-i-2)); } return newInst; } public static Instance shiftSeries(Instance inst, int shift){ Instance newInst = new DenseInstance(inst); if (shift < 0){ shift = Math.abs(shift); for (int i = 0; i < inst.numAttributes()-shift-1; i++){ newInst.setValue(i, inst.value(i+shift)); } for (int i = inst.numAttributes()-shift-1; i < inst.numAttributes()-1; i++){ newInst.setValue(i, 0); } } else if (shift > 0){ for (int i = 0; i < shift; i++){ newInst.setValue(i, 0); } for (int i = shift; i < inst.numAttributes()-1; i++){ newInst.setValue(i, inst.value(i-shift)); } } return newInst; } public static Instance randomlyAddToSeriesValues(Instance inst, Random rand, int minAdd, int maxAdd, int maxValue){ Instance newInst = new DenseInstance(inst); for (int i = 0; i < inst.numAttributes()-1; i++){ int n = rand.nextInt(maxAdd+1-minAdd)+minAdd; double newVal = inst.value(i)+n; if (newVal > maxValue) newVal = maxValue; newInst.setValue(i, newVal); } return newInst; } public static Instance randomlySubtractFromSeriesValues(Instance inst, Random rand, int minSubtract, int maxSubtract, int minValue){ Instance newInst = new DenseInstance(inst); for (int i = 0; i < inst.numAttributes()-1; i++){ int n = rand.nextInt(maxSubtract+1-maxSubtract)+maxSubtract; double newVal = inst.value(i)-n; if (newVal < minValue) newVal = minValue; newInst.setValue(i, newVal); } return newInst; } public static Instance randomlyAlterSeries(Instance inst, Random rand){ Instance newInst = new DenseInstance(inst); if (rand.nextBoolean()){ newInst = reverseSeries(newInst); } int shift = rand.nextInt(240)-120; newInst = shiftSeries(newInst, shift); if (rand.nextBoolean()){ newInst = randomlyAddToSeriesValues(newInst, rand, 0, 5, Integer.MAX_VALUE); } else{ newInst = randomlySubtractFromSeriesValues(newInst, rand, 0, 5, 0); } return newInst; } public static Instances shortenInstances(Instances data, double proportionRemaining, boolean normalise){ if (proportionRemaining > 1 || proportionRemaining <= 0){ throw new RuntimeException("Remaining series length propotion must be greater than 0 and less than or equal to 1"); } else if (data.classIndex() != data.numAttributes()-1){ throw new RuntimeException("Dataset class attribute must be the final attribute"); } Instances shortenedData = new Instances(data); if (proportionRemaining == 1) return shortenedData; int newSize = (int)Math.round((data.numAttributes()-1) * proportionRemaining); if (newSize == 0) newSize = 1; if (normalise) { Instances tempData = truncateInstances(data, data.numAttributes()-1, newSize); tempData = zNormaliseWithClass(tempData); for (int i = 0; i < data.numInstances(); i++){ for (int n = 0; n < tempData.numAttributes()-1; n++){ shortenedData.get(i).setValue(n, tempData.get(i).value(n)); } } } for (int i = 0; i < data.numInstances(); i++){ for (int n = data.numAttributes()-2; n >= newSize; n--){ //shortenedData.get(i).setMissing(n); shortenedData.get(i).setValue(n, 0); } } return shortenedData; } public static Instances truncateInstances(Instances data, int fullLength, int newLength){ Instances newData = new Instances(data); for (int i = 0; i < fullLength - newLength; i++){ newData.deleteAttributeAt(newLength); } return newData; } public static Instances truncateInstances(Instances data, double proportionRemaining){ if (proportionRemaining == 1) return data; int newSize = (int)Math.round((data.numAttributes()-1) * proportionRemaining); if (newSize == 0) newSize = 1; return truncateInstances(data, data.numAttributes()-1, newSize); } public static Instance truncateInstance(Instance inst, int fullLength, int newLength){ Instance newInst = new DenseInstance(inst); for (int i = 0; i < fullLength - newLength; i++){ newInst.deleteAttributeAt(newLength); } return newInst; } public static Instances zNormaliseWithClass(Instances data) { Instances newData = new Instances(data, 0); for (int i = 0; i < data.numInstances(); i++){ newData.add(zNormaliseWithClass(data.get(i))); } return newData; } public static Instance zNormaliseWithClass(Instance inst){ Instance newInst = new DenseInstance(inst); newInst.setDataset(inst.dataset()); double meanSum = 0; int length = newInst.numAttributes()-1; if (length < 2) return newInst; for (int i = 0; i < length; i++){ meanSum += newInst.value(i); } double mean = meanSum / length; double squareSum = 0; for (int i = 0; i < length; i++){ double temp = newInst.value(i) - mean; squareSum += temp * temp; } double stdev = Math.sqrt(squareSum/(length-1)); if (stdev == 0){ stdev = 1; } for (int i = 0; i < length; i++){ newInst.setValue(i, (newInst.value(i) - mean) / stdev); } return newInst; } /* Surprised these don't exist */ public static double sum(Instance inst){ double sumSq = 0; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal()) {// Ignore all nominal atts double x = inst.value(j); sumSq += x; } } return sumSq; } public static double sumSq(Instance inst){ double sumSq = 0; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal()) {// Ignore all nominal atts double x = inst.value(j); sumSq += x * x; } } return sumSq; } public static int argmax(Instance inst){ double max = -99999999; int arg = -1; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal()) {// Ignore all nominal atts{ double x = inst.value(j); if (x > max){ max = x; arg = j; } } } return arg; } public static double max(Instance inst){ return inst.value(argmax(inst)); } public static int argmin(Instance inst){ double min = Double.MAX_VALUE; int arg =-1; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal()) {// Ignore all nominal atts{ double x = inst.value(j); if (x < min){ min = x; arg = j; } } } return arg; } public static double min(Instance inst){ return inst.value(argmin(inst)); } public static double mean(Instance inst){ double mean = 0; int k = 0; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal() && !inst.isMissing(j)){// Ignore all nominal atts{ double x = inst.value(j); mean +=x; } else k++; } return mean / (double)(inst.numAttributes() - 1 - k); } public static double variance(Instance inst, double mean){ double var = 0; int k = 0; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal()) {// Ignore all nominal atts{ double x = inst.value(j); var += Math.pow(x-mean, 2); } else k++; } return var / (double)(inst.numAttributes() - 1 - k); } public static double kurtosis(Instance inst, double mean, double std){ double kurt = 0; int k = 0; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal()) {// Ignore all nominal atts{ double x = inst.value(j); kurt += Math.pow(x-mean, 4); } else k++; } kurt /= Math.pow(std, 4); return kurt / (double)(inst.numAttributes() - 1 - k); } public static double skew(Instance inst, double mean, double std){ double skew = 0; int k = 0; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal()) {// Ignore all nominal atts{ double x = inst.value(j); skew += Math.pow(x-mean, 3); } else k++; } skew /= Math.pow(std, 3); return skew / (double)(inst.numAttributes() - 1 - k); } public static double slope(Instance inst, double sum, double sumXX){ double sumXY= 0; int k =0; for (int j = 0; j < inst.numAttributes(); j++) { if (j != inst.classIndex() && !inst.attribute(j).isNominal()) {// Ignore all nominal atts{ sumXY += inst.value(j) * j; } else k++; } double length = (double)(inst.numAttributes() - k); double sqsum = sum*sum; //slope double slope = sumXY-sqsum/length; double denom=sumXX-sqsum/length; if(denom!=0) slope/=denom; else slope=0; //if(standardDeviation == 0) //slope=0; return slope; } public static double[] ConvertInstanceToArrayRemovingClassValue(Instance inst, int c) { double[] d = inst.toDoubleArray(); double[] temp; if (c >= 0) { temp = new double[d.length - 1]; System.arraycopy(d, 0, temp, 0, c); d = temp; } return d; } public static double[] ConvertInstanceToArrayRemovingClassValue(Instance inst) { return ConvertInstanceToArrayRemovingClassValue(inst, inst.classIndex()); } }
40,864
33.514358
206
java
tsml-java
tsml-java-master/src/main/java/utilities/NumUtils.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; public class NumUtils { public static boolean isPercentage(double value) { return value >= 0 && value <= 1; } public static boolean isNearlyEqual(double a, double b, double eps){ return Math.abs(a - b) < eps; } public static boolean isNearlyEqual(double a, double b){ return isNearlyEqual(a,b, 1e-6); } }
1,132
30.472222
76
java
tsml-java
tsml-java-master/src/main/java/utilities/StatisticalUtilities.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import tsml.data_containers.TimeSeries; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import weka.core.Instance; import weka.core.Instances; import java.math.BigDecimal; import java.math.MathContext; import java.util.*; import static java.math.BigDecimal.ROUND_HALF_UP; /** * A class offering statistical utility functions like the average and the * standard deviations * * @author aaron */ public class StatisticalUtilities { // the mean of a list of values public static double mean(double[] values, boolean classVal) { double sum = 0; int offset = classVal ? 1 : 0; for (int i = 0; i < values.length - offset; i++) { sum += values[i]; } return sum / (double) (values.length - offset); } public static double pStdDev(TimeSeriesInstances insts) { double sumx = 0; double sumx2 = 0; int n = 0; for(int i = 0; i < insts.numInstances(); i++){ final TimeSeriesInstance inst = insts.get(i); for(int j = 0; j < inst.getNumDimensions(); j++){ final TimeSeries dim = inst.get(j); for(int k = 0; k < inst.getMaxLength(); k++) { final Double value = dim.get(k); sumx+= value; sumx2+= value * value; n++; } } } double mean = sumx/n; return Math.sqrt(sumx2/(n)-mean*mean); } public static double pStdDev(Instances input){ if(input.classIndex() != input.numAttributes() - 1) { throw new IllegalArgumentException("class value must be at the end"); } double sumx = 0; double sumx2 = 0; double[] ins2array; for(int i = 0; i < input.numInstances(); i++){ final Instance instance = input.instance(i); for(int j = 0; j < instance.numAttributes()-1; j++){//-1 to avoid classVal final double value = instance.value(j); sumx+= value; sumx2+= value * value; } } int n = input.numInstances()*(input.numAttributes()-1); double mean = sumx/n; return Math.sqrt(sumx2/(n)-mean*mean); } // jamesl // the median of a list of values, just sorts (a copy, original remains unsorted) and takes middle for now // can make O(n) if wanted later public static double median(double[] values) { return median(values, true); } public static double median(double[] values, boolean copyArr) { double[] copy; if (copyArr) copy = Arrays.copyOf(values, values.length); else copy = values; Arrays.sort(copy); if (copy.length % 2 == 1) return copy[copy.length/2]; else return (copy[copy.length/2 - 1] + copy[copy.length/2]) / 2; } public static double median(ArrayList<Double> values) { return median(values, true); } public static double median(ArrayList<Double> values, boolean copyArr) { ArrayList<Double> copy; if (copyArr) copy = new ArrayList<>(values); else copy = values; Collections.sort(copy); if (copy.size() % 2 == 1) return copy.get(copy.size()/2); else return (copy.get(copy.size()/2 - 1) + copy.get(copy.size()/2)) / 2; } public static double standardDeviation(double[] values, boolean classVal) { double mean = mean(values, classVal); double sumSquaresDiffs = 0; int offset = classVal ? 1 : 0; for (int i = 0; i < values.length - offset; i++) { double diff = values[i] - mean; sumSquaresDiffs += diff * diff; } return Math.sqrt(sumSquaresDiffs / (values.length - 1 - offset)); } public static double standardDeviation(double[] values, boolean classVal, double mean) { // double mean = mean(values, classVal); double sumSquaresDiffs = 0; int offset = classVal ? 1 : 0; for (int i = 0; i < values.length - offset; i++) { double diff = values[i] - mean; sumSquaresDiffs += diff * diff; } return Math.sqrt(sumSquaresDiffs / (values.length - 1 - offset)); } // normalize the vector to mean 0 and std 1 public static double[] normalize(double[] vector, boolean classVal) { double mean = mean(vector, classVal); double std = standardDeviation(vector, classVal, mean); double[] normalizedVector = new double[vector.length]; for (int i = 0; i < vector.length; i++) { normalizedVector[i] = !NumUtils.isNearlyEqual(std, 0.0) ? (vector[i] - mean) / std : 0; } return normalizedVector; } public static double[] normalize(double[] vector) { return StatisticalUtilities.normalize(vector, false); } //Aaron: I'm not confident in the others...I may have written those too... lol public static double[] norm(double[] patt){ double mean =0,sum =0 ,sumSq =0,var = 0; for(int i=0; i< patt.length; ++i){ sum = patt[i]; sumSq = patt[i]*patt[i]; } double size= patt.length; var = (sumSq - sum * sum / size) / size; mean = sum / size; double[] out = new double[patt.length]; if(NumUtils.isNearlyEqual(var, 0.0)){ for(int i=0; i<patt.length; ++i) out[i] = 0.0; } else{ double stdv = Math.sqrt(var); for(int i=0; i<patt.length; ++i) out[i] = (patt[i] - mean) / stdv; } return out; } public static void normInPlace(double[] r){ double sum=0,sumSq=0,mean=0,stdev=0; for(int i=0;i<r.length;i++){ sum+=r[i]; sumSq+=r[i]*r[i]; } stdev=(sumSq-sum*sum/r.length)/r.length; mean=sum/r.length; if(stdev==0){ for (int j = 0; j < r.length; ++j) r[j] = 0; } else{ stdev=Math.sqrt(stdev); for(int i=0;i<r.length;i++) r[i]=(r[i]-mean)/stdev; } } public static void normalize2D(double[][] data, boolean classVal) { int offset = classVal ? 1 : 0; //normalise each series. for (double[] series : data) { //TODO: could make mean and STD better. double mean = mean(series, classVal); double std = standardDeviation(series, classVal,mean); //class value at the end of the series. for (int j = 0; j < series.length - offset; j++) { if (std != 0) { series[j] = (series[j] - mean) / std; } } } } public static double exp(double val) { final long tmp = (long) (1512775 * val + 1072632447); return Double.longBitsToDouble(tmp << 32); } public static double sumOfSquares(double[] v1, double[] v2) { double ss = 0; int N = v1.length; double err = 0; for (int i = 0; i < N; i++) { err = v1[i] - v2[i]; ss += err * err; } return ss; } public static double calculateSigmoid(double x) { return 1.0 / (1.0 + Math.exp(-x)); } private static final BigDecimal TWO = BigDecimal.valueOf(2L); //calculates the square root of a bigdecimal. Give a mathcontext to specify precision. public static BigDecimal sqrt(BigDecimal x, MathContext mc) { BigDecimal g = x.divide(TWO, mc); boolean done = false; final int maxIterations = mc.getPrecision() + 1; for (int i = 0; !done && i < maxIterations; i++) { // r = (x/g + g) / 2 BigDecimal r = x.divide(g, mc); r = r.add(g); r = r.divide(TWO, mc); done = r.equals(g); g = r; } return g; } /** * * @param counts count of number of items at each level i * @return cumulative count of items at level <=i */ public static int[] findCumulativeCounts(int[] counts){ int[] c=new int[counts.length]; c[0]=counts[0]; int i=1; while(i<counts.length){ c[i]=c[i-1]+counts[i]; i++; } return c; } /** * * @param cumulativeCounts: cumulativeCounts[i] is the number of items <=i * as found by findCumulativeCounts * cumulativeCounts[length-1] is the total number of objects * @return a randomly selected level i based on sample of cumulativeCounts */ public static int sampleCounts(int[] cumulativeCounts, Random rand){ int c=rand.nextInt(cumulativeCounts[cumulativeCounts.length-1]); int pos=0; while(cumulativeCounts[pos]<c) pos++; return pos; } public static double[][][][] averageFinalDimension(double[][][][][] results) { double[][][][] res = new double[results.length][results[0].length][results[0][0].length][results[0][0][0].length]; for (int i = 0; i < results.length; i++) for (int j = 0; j < results[0].length; j++) for (int k = 0; k < results[0][0].length; k++) for (int l = 0; l < results[0][0][0].length; l++) res[i][j][k][l] = StatisticalUtilities.mean(results[i][j][k][l], false); return res; } public static double[][][] averageFinalDimension(double[][][][] results) { double[][][] res = new double[results.length][results[0].length][results[0][0].length]; for (int i = 0; i < results.length; i++) for (int j = 0; j < results[0].length; j++) for (int k = 0; k < results[0][0].length; k++) res[i][j][k] = StatisticalUtilities.mean(results[i][j][k], false); return res; } public static double[][] averageFinalDimension(double[][][] results) { double[][] res = new double[results.length][results[0].length]; for (int i = 0; i < results.length; i++) for (int j = 0; j < results[0].length; j++) res[i][j] = StatisticalUtilities.mean(results[i][j], false); return res; } public static double[] averageFinalDimension(double[][] results) { double[] res = new double[results.length]; for (int i = 0; i < results.length; i++) res[i] = StatisticalUtilities.mean(results[i], false); return res; } public static double averageFinalDimension(double[] results) { return StatisticalUtilities.mean(results, false); } public static BigDecimal sqrt(BigDecimal decimal) { int scale = MathContext.DECIMAL128.getPrecision(); BigDecimal x0 = new BigDecimal("0"); BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(decimal.doubleValue())); while (!x0.equals(x1)) { x0 = x1; x1 = decimal.divide(x0, scale, ROUND_HALF_UP); x1 = x1.add(x0); x1 = x1.divide(TWO, scale, ROUND_HALF_UP); } return x1; } public static double dot(double[] inst1, double[] inst2){ double sum = 0; for (int i = 0; i < inst1.length; i++) sum += inst1[i] * inst2[i]; return sum; } public static int dot(int[] inst1, int[] inst2){ int sum = 0; for (int i = 0; i < inst1.length; i++) sum += inst1[i] * inst2[i]; return sum; } }
12,538
32.348404
123
java
tsml-java
tsml-java-master/src/main/java/utilities/ThreadingUtilities.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Some utility methods for threading, currently assumes that all threaded jobs * are independent etc. * * @author James Large (james.large@uea.ac.uk) */ public class ThreadingUtilities { public static ExecutorService buildExecutorService(int numThreads) { //todo look into queues etc return Executors.newFixedThreadPool(numThreads); } public static void shutdownExecutor(ExecutorService executor) { //todo maybe add timer to while, for general expected usecase in this codebase //this should be fine though executor.shutdown(); while (!executor.isTerminated()) { } } /** * Submits all given jobs that each return an object to the executor, waits for them * all to finish and returns all the results. The returned list of results is * in the same order as the jobs, i.e. results.get(0) is the results for jobs.get(0), * etc. */ public static <T> List<T> computeAll(ExecutorService executor, List<Callable<T>> jobs, boolean shutdownExecutorOnCompletion) throws InterruptedException, ExecutionException { List<T> results = gatherAll(submitAll(executor, jobs)); if (shutdownExecutorOnCompletion) shutdownExecutor(executor); return results; } /** * Submits all given jobs that do NOT return an object to the executor, wait for them all to * finish and returns any Exceptions thrown in a list parallel with the jobs. This can be inspected * for failed executions if desired. If there was no exception and the job completed successfully, * the Exception will be null */ public static List<Exception> runAll(ExecutorService executor, List<Runnable> jobs, boolean shutdownExecutorOnCompletion) throws InterruptedException, ExecutionException { List<Future<Exception>> futureResults = new ArrayList<>(); for (Runnable job : jobs) { Callable<Exception> wrappedJob = () -> { try { job.run(); return null; } catch (Exception e) { return e; } }; futureResults.add(executor.submit(wrappedJob)); } List<Exception> results = gatherAll(futureResults); if (shutdownExecutorOnCompletion) shutdownExecutor(executor); return results; } public static <T> List<Future<T>> submitAll(ExecutorService executor, List<Callable<T>> jobs) throws InterruptedException, ExecutionException { List<Future<T>> futureResults = new ArrayList<>(); for (Callable<T> job : jobs) futureResults.add(executor.submit(job)); return futureResults; } public static <T> List<T> gatherAll(List<Future<T>> futures) throws InterruptedException, ExecutionException { List<T> results = new ArrayList<>(); for (Future<T> future : futures) results.add(future.get()); return results; } }
4,209
36.927928
178
java
tsml-java
tsml-java-master/src/main/java/utilities/Timer.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; /** * * @author xmw13bzu */ public class Timer { public static boolean PRINT = false; public static double SECS = 1000.0; long startTime; String name; public Timer(String name) { this(name, true); } public Timer() { this("", true); } public Timer(String name, boolean auto_start){ this.name = name; if(auto_start) start(); } public void start() { startTime = System.currentTimeMillis(); } public long restart() { long t = timeSoFar(); startTime = System.currentTimeMillis(); return t; } public long timeSoFar() { return System.currentTimeMillis() - startTime; } @Override public String toString() { return "("+name+") TIMER timeSoFar (secs): " + (timeSoFar() / SECS); } public void printlnTimeSoFar() { if (PRINT) System.out.println(toString()); } public static void main(String[] args) { //use case Timer.PRINT = true; //globally should timers be printed, similar idea to ndebug Timer looptimer = new Timer("looptimer"); for (int i = 0; i < 1000000; i++) { } looptimer.printlnTimeSoFar(); } }
2,133
24.404762
87
java
tsml-java
tsml-java-master/src/main/java/utilities/TriFunction.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.util.Objects; import java.util.function.Function; public interface TriFunction<A,B,C,R> { R apply(A a, B b, C c); default <V> TriFunction<A, B, C, V> andThen( Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (A a, B b, C c) -> after.apply(apply(a, b, c)); } }
1,149
33.848485
76
java
tsml-java
tsml-java-master/src/main/java/utilities/Utilities.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import com.beust.jcommander.internal.Lists; import java.math.BigDecimal; import java.math.RoundingMode; import org.junit.Assert; import tsml.classifiers.distance_based.utils.strings.StrUtils; import tsml.classifiers.distance_based.utils.collections.views.IntListView; import weka.core.Instance; import weka.core.Instances; import weka.core.SerializedObject; import java.io.Serializable; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; public class Utilities { public static void busyWait(long nanos) { final long timeStamp = System.nanoTime(); while(System.nanoTime() - timeStamp < nanos) { // busy wait } } public static <A, B, C extends Collection<B>> C apply(Collection<A> src, Function<A, B> func, C dest) { for(A item : src) { dest.add(func.apply(item)); } return dest; } public static <A, B> ArrayList<B> apply(Collection<A> src, Function<A, B> func) { return apply(src, func, new ArrayList<>(src.size())); } public static <A> int sum(Iterator<A> iterator, Function<A, Integer> func) { int sum = 0; while(iterator.hasNext()) { A next = iterator.next(); Integer integer = func.apply(next); sum += integer; } return sum; } public static <A, B> List<B> convert(Iterable<A> source, Function<A, B> converter) { // todo stream version return convert(source.iterator(), converter); } public static <A, B> List<B> convert(Iterator<A> source, Function<A, B> converter) { return convert(source, converter, ArrayList::new); } public static <A, B, C extends Collection<B>> C convert(Iterator<A> source, Function<A, B> converter, Supplier<C> supplier) { C destination = supplier.get(); while(source.hasNext()) { A item = source.next(); B convertedItem = converter.apply(item); destination.add(convertedItem); } return destination; } public static <A, B, C extends Collection<B>> C convert(Iterable<A> source, Function<A, B> converter, Supplier<C> supplier) { return convert(source.iterator(), converter, supplier); } /** * 6/2/19: bug fixed so it properly ignores the class value, only place its used * is in measures.DistanceMeasure * @param instance * @return array of doubles with the class value removed */ public static final double[] extractTimeSeries(Instance instance) { if(instance.classIndex() < 0) { return instance.toDoubleArray(); } else { double[] timeSeries = new double[instance.numAttributes() - 1]; for(int i = 0; i < instance.numAttributes(); i++) { if(i < instance.classIndex()) { timeSeries[i] = instance.value(i); } else if (i != instance.classIndex()){ timeSeries[i - 1] = instance.value(i); } } return timeSeries; } } public static final int maxIndex(double[] array) { int maxIndex = 0; for (int i = 1; i < array.length; i++) { if(array[maxIndex] < array[i]) { maxIndex = i; } } return maxIndex; } public static final int minIndex(double[] array) { int minIndex = 0; for (int i = 1; i < array.length; i++) { if(array[i] < array[minIndex]) { minIndex = i; } } return minIndex; } public static double log(double value, double base) { // beware, this is inaccurate due to floating point error! if(value == 0) { return 0; } return Math.log(value) / Math.log(base); } /** * get the instances by class. This returns a map of class value to indices of instances in that class. * @param instances * @return */ public static Map<Double, List<Integer>> instancesByClass(Instances instances) { Map<Double, List<Integer>> map = new LinkedHashMap<>(instances.size(), 1); for(int i = 0; i < instances.size(); i++) { final Instance instance = instances.get(i); map.computeIfAbsent(instance.classValue(), k -> new ArrayList<>()).add(i); } return map; } public static <A, B> boolean isUnique(final Iterator<A> iterator, Function<A, B> func) { if(!iterator.hasNext()) { return true; } B value = func.apply(iterator.next()); while(iterator.hasNext()) { B nextValue = func.apply(iterator.next()); if(value == null) { if(nextValue != null) { return false; } } else if(!value.equals(nextValue)) { return false; } } return true; } public static <A> boolean isUnique(final Iterator<A> iterator) { return isUnique(iterator, i -> i); } public static <A> boolean isUnique(Iterable<A> iterable) { return isUnique(iterable.iterator()); } public static <A, B> boolean isUnique(Iterable<A> iterable, Function<A, B> func) { return isUnique(iterable.iterator(), func); } public static boolean isHomogeneous(List<Instance> data) { return isUnique(data, Instance::classValue); } public static int[] argMax(double[] array) { List<Integer> indices = new ArrayList<>(); double max = array[0]; indices.add(0); for(int i = 1; i < array.length; i++) { if(array[i] >= max) { if(array[i] > max) { max = array[i]; indices.clear(); } indices.add(i); } } int[] indicesCopy = new int[indices.size()]; for(int i = 0; i < indicesCopy.length; i++) { indicesCopy[i] = indices.get(i); } return indicesCopy; } public static int argMax(double[] array, Random random) { int[] indices = argMax(array); if(indices.length == 1) { return indices[0]; } return indices[random.nextInt(indices.length)]; } public static boolean stringIsDouble(String input){ /*********Aarons Nasty Regex From https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String **********/ final String Digits = "(\\p{Digit}+)"; final String HexDigits = "(\\p{XDigit}+)"; // an exponent is 'e' or 'E' followed by an optionally // signed decimal integer. final String Exp = "[eE][+-]?"+Digits; final String fpRegex = ("[\\x00-\\x20]*"+ // Optional leading "whitespace" "[+-]?(" + // Optional sign character "NaN|" + // "NaN" string "Infinity|" + // "Infinity" string // A decimal floating-point string representing a finite positive // number without a leading sign has at most five basic pieces: // Digits . Digits ExponentPart FloatTypeSuffix // // Since this method allows integer-only strings as input // in addition to strings of floating-point literals, the // two sub-patterns below are simplifications of the grammar // productions from section 3.10.2 of // The Java Language Specification. // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+ // . Digits ExponentPart_opt FloatTypeSuffix_opt "(\\.("+Digits+")("+Exp+")?)|"+ // Hexadecimal strings "((" + // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "(\\.)?)|" + // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*");// Optional trailing "whitespace" return Pattern.matches(fpRegex, input); } }
9,199
34.384615
143
java
tsml-java
tsml-java-master/src/main/java/utilities/WritableTestResults.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities; import java.io.File; import java.io.FileWriter; import weka.classifiers.Classifier; import weka.core.Instances; /** * * @author Jason Lines (j.lines@uea.ac.uk) */ public interface WritableTestResults extends Classifier{ default void writeTestResultsToFile(Instances testData, String datasetName, String classifierName, String paramLine, String outputFilePathAndName) throws Exception{ new File(outputFilePathAndName).getParentFile().mkdirs(); FileWriter out = new FileWriter(outputFilePathAndName); out.close(); if(new File(outputFilePathAndName).exists()==false){ throw new Exception("Error: could not create file "+outputFilePathAndName); } int correct = 0; double actual, pred; double[] dists; double bsfClass; double bsfWeight; StringBuilder lineBuilder; StringBuilder outBuilder = new StringBuilder(); for(int i = 0; i < testData.numInstances(); i++){ actual = testData.instance(i).classValue(); dists = this.distributionForInstance(testData.instance(i)); lineBuilder = new StringBuilder(); bsfClass = -1; bsfWeight = -1; for(int c = 0; c < dists.length; c++){ if(dists[c] > bsfWeight){ bsfWeight = dists[c]; bsfClass = c; } lineBuilder.append(",").append(dists[c]); } if(bsfClass==actual){ correct++; } outBuilder.append(actual).append(",").append(bsfClass).append(",").append(lineBuilder.toString()).append("\n"); } out = new FileWriter(outputFilePathAndName); out.append(datasetName+","+classifierName+",test\n"); out.append(paramLine+"\n"); out.append(((double)correct/testData.numInstances())+"\n"); out.append(outBuilder.toString()); out.close(); } }
2,816
35.584416
168
java
tsml-java
tsml-java-master/src/main/java/utilities/class_counts/ClassCounts.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities.class_counts; import java.io.Serializable; import java.util.Collection; import java.util.Set; /** * This is used by Aarons shapelet code and is down for depreciation * @author raj09hxu */ public abstract class ClassCounts implements Serializable { public abstract int get(double classValue); public abstract int get(int accessValue); public abstract void put(double classValue, int value); public abstract int size(); public abstract Set<Double> keySet(); public abstract Collection<Integer> values(); public abstract void addTo(double classValue, int val); }
1,374
36.162162
76
java
tsml-java
tsml-java-master/src/main/java/utilities/class_counts/SimpleClassCounts.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities.class_counts; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.TreeSet; import weka.core.Instance; import weka.core.Instances; /** * This is used by Aarons shapelet code and may be depreciated with new light * weight shapelets * @author raj09hxu */ public class SimpleClassCounts extends ClassCounts { private final Integer[] classDistribution; private final Set<Double> keySet; public SimpleClassCounts(Instances data) { classDistribution = new Integer[data.numClasses()]; Arrays.fill(classDistribution, 0); keySet = new TreeSet<>(); for (Instance data1 : data) { int thisClassVal = (int) data1.classValue(); keySet.add(data1.classValue()); classDistribution[thisClassVal]++; } } //clones the object public SimpleClassCounts(ClassCounts in){ //copy over the data. classDistribution = new Integer[in.size()]; for(int i=0; i<in.size(); i++) { classDistribution[i] = in.get(i); } keySet = in.keySet(); } //creates an empty distribution of specified size. public SimpleClassCounts(int size) { classDistribution = new Integer[size]; Arrays.fill(classDistribution, 0); keySet = new TreeSet<>(); } @Override public int get(double classValue) { return classDistribution[(int)classValue]; } //Use this with caution. @Override public void put(double classValue, int value) { classDistribution[(int)classValue] = value; keySet.add(classValue); } @Override public int size() { return classDistribution.length; } @Override public int get(int accessValue) { return classDistribution[accessValue]; } @Override public String toString(){ String temp = ""; for(int i=0; i<classDistribution.length; i++){ temp+="["+i+" "+classDistribution[i]+"] "; } return temp; } @Override public void addTo(double classValue, int value) { classDistribution[(int)classValue]+= value; } @Override public Set<Double> keySet() { return keySet; } @Override public Collection<Integer> values() { return new ArrayList<>(Arrays.asList(classDistribution)); } }
3,315
25.741935
78
java
tsml-java
tsml-java-master/src/main/java/utilities/class_counts/TreeSetClassCounts.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities.class_counts; import java.util.Collection; import java.util.ListIterator; import java.util.Set; import java.util.TreeMap; import tsml.data_containers.TimeSeriesInstance; import tsml.data_containers.TimeSeriesInstances; import weka.core.Instance; import weka.core.Instances; /** * This is used by Aarons shapelet code and is down for depreciation * @author raj09hxu */ public class TreeSetClassCounts extends ClassCounts{ TreeMap<Double,Integer> classDistribution; public TreeSetClassCounts(Instances data) { classDistribution = new TreeMap<>(); ListIterator<Instance> it = data.listIterator(); double classValue; while (it.hasNext()) { classValue = it.next().classValue(); Integer val = classDistribution.get(classValue); val = (val != null) ? val + 1 : 1; classDistribution.put(classValue, val); } } public TreeSetClassCounts(TimeSeriesInstances data) { classDistribution = new TreeMap<>(); for(TimeSeriesInstance inst : data){ classDistribution.merge((double)inst.getLabelIndex(), 1, Integer::sum); } } public TreeSetClassCounts() { classDistribution = new TreeMap<>(); } public TreeSetClassCounts(ClassCounts in){ //copy over the data. classDistribution = new TreeMap<>(); for(double val : in.keySet()) { classDistribution.put(val, in.get(val)); } } @Override public int get(double classValue) { return classDistribution.getOrDefault(classValue, 0); } @Override public void put(double classValue, int value) { classDistribution.put(classValue, value); } @Override public int size() { return classDistribution.size(); } @Override public int get(int accessValue) { return classDistribution.getOrDefault((double) accessValue, 0); } @Override public void addTo(double classVal, int value) { put(classVal, get(classVal)+value); } @Override public Set<Double> keySet() { return classDistribution.keySet(); } @Override public Collection<Integer> values() { return classDistribution.values(); } }
3,129
25.982759
83
java
tsml-java
tsml-java-master/src/main/java/utilities/generic_storage/ComparableKeyPair.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities.generic_storage; import java.util.Objects; public class ComparableKeyPair<T1 extends Comparable<T1>, T2 extends Comparable<T2> > implements Comparable<ComparableKeyPair<T1, T2>>{ public final T1 var1; public final T2 var2; public ComparableKeyPair(T1 t1, T2 t2){ var1 = t1; var2 = t2; } @Override public String toString(){ return var1 + " " + var2; } @Override public int compareTo(ComparableKeyPair<T1, T2> other) { return var1.compareTo(other.var1); } @Override public boolean equals(Object other) { if (other instanceof ComparableKeyPair<?,?>) return var1.equals(((ComparableKeyPair<?,?>)other).var1); return false; } @Override public int hashCode() { return Objects.hash(var1); } }
1,619
28.454545
85
java
tsml-java
tsml-java-master/src/main/java/utilities/generic_storage/ComparablePair.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities.generic_storage; import java.util.Objects; public class ComparablePair <T1 extends Comparable<T1>, T2 extends Comparable<T2> > implements Comparable<ComparablePair<T1, T2> >{ public final T1 var1; public final T2 var2; public ComparablePair(T1 t1, T2 t2){ var1 = t1; var2 = t2; } @Override public String toString(){ return var1 + " " + var2; } @Override public int compareTo(ComparablePair<T1, T2> other) { int c1 = var1.compareTo(other.var1); if (c1 != 0) return c1; else return var2.compareTo(other.var2); } @Override public boolean equals(Object other) { if (other instanceof ComparablePair<?,?>) return var1.equals(((ComparablePair<?,?>)other).var1) && var2.equals(((ComparablePair<?,?>)other).var2) ; return false; } @Override public int hashCode() { return Objects.hash(var1, var2); } }
1,792
28.883333
83
java
tsml-java
tsml-java-master/src/main/java/utilities/generic_storage/Pair.java
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The UEA TSML toolbox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ package utilities.generic_storage; /** * * @author raj09hxu * @param <T1> * @param <T2> * Generic Tuple class. */ public class Pair <T1, T2>{ public T1 var1; public T2 var2; public Pair(T1 t1, T2 t2){ var1 = t1; var2 = t2; } @Override public String toString(){ return var1 + " " + var2; } @Override public boolean equals(/*Pair<T1,T2>*/Object ot){ if (!(ot instanceof Pair)) return false; Pair<T1, T2> other = (Pair<T1,T2>) ot; return var1.equals(other.var1) && var2.equals(other.var2); } }
1,382
26.66
76
java