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/classifiers/distance_based/distances/dtw/spaces/DTWDistanceFullWindowSpace.java | package tsml.classifiers.distance_based.distances.dtw.spaces;
import tsml.classifiers.distance_based.distances.dtw.DTWDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.distances.DistanceMeasure.DISTANCE_MEASURE_FLAG;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class DTWDistanceFullWindowSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DISTANCE_MEASURE_FLAG, newArrayList(new DTWDistance()), new DTWDistanceFullWindowParams().build(data)));
}
}
| 908 | 49.5 | 153 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/dtw/spaces/DTWDistanceParams.java | package tsml.classifiers.distance_based.distances.dtw.spaces;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import java.util.stream.IntStream;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
public class DTWDistanceParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap()
.add(WINDOW_FLAG, IntStream.range(0, 100).mapToDouble(i -> (double) i / 100d).toArray()));
}
}
| 761 | 41.333333 | 113 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/dtw/spaces/DTWDistanceRestrictedContinuousParams.java | package tsml.classifiers.distance_based.distances.dtw.spaces;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
public class DTWDistanceRestrictedContinuousParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
final ParamMap subSpace = new ParamMap();
subSpace.add(WINDOW_FLAG, new UniformDoubleDistribution(0d, 0.25d));
return new ParamSpace(subSpace);
}
}
| 871 | 47.444444 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/dtw/spaces/DTWDistanceRestrictedContinuousSpace.java | package tsml.classifiers.distance_based.distances.dtw.spaces;
import tsml.classifiers.distance_based.distances.dtw.DTWDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.distances.DistanceMeasure.DISTANCE_MEASURE_FLAG;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class DTWDistanceRestrictedContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DISTANCE_MEASURE_FLAG, newArrayList(new DTWDistance()), new DTWDistanceRestrictedContinuousParams().build(data)));
}
}
| 928 | 50.611111 | 163 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/dtw/spaces/DTWDistanceSpace.java | package tsml.classifiers.distance_based.distances.dtw.spaces;
import tsml.classifiers.distance_based.distances.dtw.DTWDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.distances.DistanceMeasure.DISTANCE_MEASURE_FLAG;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class DTWDistanceSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DISTANCE_MEASURE_FLAG, newArrayList(new DTWDistance()), new DTWDistanceParams().build(data)));
}
}
| 891 | 48.555556 | 146 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/ed/EDistance.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.classifiers.distance_based.distances.ed;
import tsml.classifiers.distance_based.distances.BaseDistanceMeasure;
import tsml.classifiers.distance_based.distances.MatrixBasedDistanceMeasure;
import tsml.classifiers.distance_based.distances.dtw.DTWDistance;
import tsml.data_containers.TimeSeriesInstance;
public class EDistance extends BaseDistanceMeasure {
public double distance(final TimeSeriesInstance a, TimeSeriesInstance b, final double limit) {
double sum = 0;
final int aLength = a.getMaxLength();
final int bLength = b.getMaxLength();
for(int i = 0; i < aLength; i++) {
sum += DTWDistance.cost(a, i, b, i);
if(sum > limit) {
return Double.POSITIVE_INFINITY;
}
}
return sum;
}
}
| 1,578 | 35.72093 | 98 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/ed/EDistanceTest.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.classifiers.distance_based.distances.ed;
import static tsml.classifiers.distance_based.distances.dtw.DTWDistanceTest.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import tsml.classifiers.distance_based.distances.dtw.DTWDistance;
import weka.core.Instances;
public class EDistanceTest {
@Test
public void matchesDtwZeroWindow() {
DTWDistance dtw = new DTWDistance();
dtw.setWindow(0);
final Instances instances = buildInstances();
dtw.buildDistanceMeasure(instances);
final double d1 = df.distance(instances.get(0), instances.get(1));
final double d2 = dtw.distance(instances.get(0), instances.get(1));
Assert.assertEquals(d1, d2, 0d);
}
private Instances instances;
private EDistance df;
@Before
public void before() {
instances = buildInstances();
df = new EDistance();
df.buildDistanceMeasure(instances);
}
}
| 1,735 | 32.384615 | 78 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/ed/spaces/EDistanceParams.java | package tsml.classifiers.distance_based.distances.ed.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.ed.EDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class EDistanceParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace();
}
}
| 742 | 42.705882 | 93 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/ed/spaces/EDistanceSpace.java | package tsml.classifiers.distance_based.distances.ed.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.ed.EDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class EDistanceSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new EDistance())));
}
}
| 829 | 47.823529 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/erp/ERPDistance.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.classifiers.distance_based.distances.erp;
import tsml.classifiers.distance_based.distances.MatrixBasedDistanceMeasure;
import tsml.classifiers.distance_based.distances.dtw.DTW;
import tsml.classifiers.distance_based.utils.collections.checks.Checks;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import utilities.Utilities;
import java.util.Arrays;
/**
* ERP distance measure.
* <p>
* Contributors: goastler
*/
public class ERPDistance extends MatrixBasedDistanceMeasure {
public static final String WINDOW_FLAG = DTW.WINDOW_FLAG;
public static final String G_FLAG = "g";
private double g = 0.01;
private double window = 1;
public double getG() {
return g;
}
public void setG(double g) {
this.g = g;
}
public double cost(final TimeSeriesInstance a, final int aIndex) {
double sum = 0;
for(int i = 0; i < a.getNumDimensions(); i++) {
final TimeSeries aDim = a.get(i);
final double aValue = aDim.get(aIndex);
final double sqDiff = StrictMath.pow(aValue - g, 2);
sum += sqDiff;
}
return sum;
}
public double cost(TimeSeriesInstance a, int aIndex, TimeSeriesInstance b, int bIndex) {
double sum = 0;
for(int i = 0; i < a.getNumDimensions(); i++) {
final TimeSeries aDim = a.get(i);
final TimeSeries bDim = b.get(i);
final double aValue = aDim.get(aIndex);
final double bValue = bDim.get(bIndex);
final double sqDiff = StrictMath.pow(aValue - bValue, 2);
sum += sqDiff;
}
return sum;
}
@Override
public double distance(TimeSeriesInstance a, TimeSeriesInstance b, final double limit) {
// make a the longest time series
if(a.getMaxLength() < b.getMaxLength()) {
TimeSeriesInstance tmp = a;
a = b;
b = tmp;
}
final int aLength = a.getMaxLength();
final int bLength = b.getMaxLength();
setup(aLength, bLength, true);
// step is the increment of the mid point for each row
final double step = (double) (bLength - 1) / (aLength - 1);
final double windowSize = this.window * bLength;
// row index
int i = 0;
// start and end of window
int start = 0;
double mid = 0;
int end = Math.min(bLength - 1, (int) Math.floor(windowSize));
int prevEnd; // store end of window from previous row to fill in shifted space with inf
double[] row = getRow(i);
double[] prevRow;
// col index
int j = start;
// process top left sqaure of mat
double min = row[j++] = 0; // top left cell is always zero
// compute the first row
for(; j <= end; j++) {
row[j] = row[j - 1] + cost(b, j);
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
i++;
// process remaining rows
for(; i < aLength; i++) {
// reset min for the row
min = Double.POSITIVE_INFINITY;
// change rows
prevRow = row;
row = getRow(i);
// start, end and mid of window
prevEnd = end;
mid = i * step;
// if using variable length time series and window size is fractional then the window may part cover an
// element. Any part covered element is truncated from the window. I.e. mid point of 5.5 with window of 2.3
// would produce a start point of 2.2. The window would start from index 3 as it does not fully cover index
// 2. The same thing happens at the end, 5.5 + 2.3 = 7.8, so the end index is 7 as it does not fully cover 8
start = Math.max(0, (int) Math.ceil(mid - windowSize));
end = Math.min(bLength - 1, (int) Math.floor(mid + windowSize));
j = start;
// set the values above the current row and outside of previous window to inf
Arrays.fill(prevRow, prevEnd + 1, end + 1, Double.POSITIVE_INFINITY);
// set the value left of the window to inf
if(j > 0) row[j - 1] = Double.POSITIVE_INFINITY;
// if assessing the left most column then only mapping option is top - not left or topleft
if(j == 0) {
row[j] = prevRow[j] + cost(a, i);
min = Math.min(min, row[j++]);
}
// compute the distance for each cell in the row
for(; j <= end; j++) {
final double topLeft = prevRow[j - 1] + cost(a, i, b, j);
final double left = row[j - 1] + cost(b, j);
final double top = prevRow[j] + cost(a, i);
if(topLeft > left && left < top) {
// del
row[j] = left;
} else if(topLeft > top && top < left) {
// ins
row[j] = top;
} else {
// match
row[j] = topLeft;
}
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
}
// last value in the current row is the distance
final double distance = row[bLength - 1];
teardown();
return distance;
}
@Override
public ParamSet getParams() {
return super.getParams().add(DTW.WINDOW_FLAG, window).add(G_FLAG, g);
}
@Override
public void setParams(final ParamSet param) throws Exception {
super.setParams(param);
setG(param.get(G_FLAG, getG()));
setWindow(param.get(WINDOW_FLAG, getWindow()));
}
public double getWindow() {
return window;
}
public void setWindow(final double window) {
this.window = Checks.requireUnitInterval(window);
}
}
| 6,970 | 35.307292 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/erp/ERPDistanceTest.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.classifiers.distance_based.distances.erp;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.dtw.DTW;
import tsml.classifiers.distance_based.distances.dtw.DTWDistance;
import tsml.classifiers.distance_based.distances.dtw.DTWDistanceTest;
import tsml.classifiers.distance_based.distances.transformed.TransformDistanceMeasure;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import weka.core.Instances;
import static tsml.classifiers.distance_based.distances.dtw.spaces.DDTWDistanceSpace.newDDTWDistance;
public class ERPDistanceTest {
private Instances instances;
private ERPDistance df;
@Before
public void before() {
instances = DTWDistanceTest.buildInstances();
df = new ERPDistance();
df.buildDistanceMeasure(instances);
}
@Test
public void testFullWarpA() {
df.setWindow(1);
df.setG(1.5);
double distance = df.distance(instances.get(0), instances.get(1));
Assert.assertEquals(distance, 182, 0);
}
@Test
public void testFullWarpB() {
df.setWindow(1);
df.setG(2);
double distance = df.distance(instances.get(0), instances.get(1));
Assert.assertEquals(distance, 175, 0);
}
@Test
public void testConstrainedWarpA() {
df.setWindow(0.2);
df.setG(1.5);
double distance = df.distance(instances.get(0), instances.get(1));
Assert.assertEquals(distance, 189.5, 0);
}
@Test
public void testConstrainedWarpB() {
df.setWindow(1);
df.setG(2);
double distance = df.distance(instances.get(0), instances.get(1));
Assert.assertEquals(distance, 175, 0);
}
}
| 2,609 | 32.896104 | 101 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/erp/spaces/ERPDistanceContinuousParams.java | package tsml.classifiers.distance_based.distances.erp.spaces;
import tsml.classifiers.distance_based.distances.erp.ERPDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import tsml.data_containers.TimeSeriesInstances;
import utilities.StatisticalUtilities;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
public class ERPDistanceContinuousParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
final double std = StatisticalUtilities.pStdDev(data);
final ParamMap subSpace = new ParamMap();
subSpace.add(ERPDistance.G_FLAG, new UniformDoubleDistribution(0.02 * std, std));
subSpace.add(WINDOW_FLAG, new UniformDoubleDistribution(0d, 1d));
return new ParamSpace(subSpace);
}
}
| 1,116 | 49.772727 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/erp/spaces/ERPDistanceContinuousSpace.java | package tsml.classifiers.distance_based.distances.erp.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.erp.ERPDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class ERPDistanceContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new ERPDistance()),
new ERPDistanceContinuousParams().build(data)));
}
}
| 910 | 49.611111 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/erp/spaces/ERPDistanceParams.java | package tsml.classifiers.distance_based.distances.erp.spaces;
import tsml.classifiers.distance_based.distances.erp.ERPDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import utilities.StatisticalUtilities;
import java.util.List;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
import static utilities.ArrayUtilities.range;
import static utilities.ArrayUtilities.unique;
public class ERPDistanceParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
double std = StatisticalUtilities.pStdDev(data);
double stdFloor = std * 0.2;
double[] bandSizeValues = range(0d, 0.25, 10);
double[] penaltyValues = range(stdFloor, std, 10);
List<Double> penaltyValuesUnique = unique(penaltyValues);
List<Double> bandSizeValuesUnique = unique(bandSizeValues);
ParamMap params = new ParamMap();
params.add(WINDOW_FLAG, bandSizeValuesUnique);
params.add(ERPDistance.G_FLAG, penaltyValuesUnique);
return new ParamSpace(params);
}
}
| 1,328 | 41.870968 | 82 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/erp/spaces/ERPDistanceRestrictedContinuousParams.java | package tsml.classifiers.distance_based.distances.erp.spaces;
import tsml.classifiers.distance_based.distances.erp.ERPDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import tsml.data_containers.TimeSeriesInstances;
import utilities.StatisticalUtilities;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
public class ERPDistanceRestrictedContinuousParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
final double std = StatisticalUtilities.pStdDev(data);
final ParamMap subSpace = new ParamMap();
subSpace.add(ERPDistance.G_FLAG, new UniformDoubleDistribution(0.2 * std, std));
subSpace.add(WINDOW_FLAG, new UniformDoubleDistribution(0d, 0.25));
return new ParamSpace(subSpace);
}
}
| 1,127 | 50.272727 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/erp/spaces/ERPDistanceRestrictedContinuousSpace.java | package tsml.classifiers.distance_based.distances.erp.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.erp.ERPDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class ERPDistanceRestrictedContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new ERPDistance()),
new ERPDistanceRestrictedContinuousParams().build(data)));
}
}
| 930 | 50.722222 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/erp/spaces/ERPDistanceSpace.java | package tsml.classifiers.distance_based.distances.erp.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.erp.ERPDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class ERPDistanceSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new ERPDistance()),
new ERPDistanceParams().build(data)));
}
}
| 890 | 48.5 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/lcss/LCSSDistance.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.classifiers.distance_based.distances.lcss;
import tsml.classifiers.distance_based.distances.MatrixBasedDistanceMeasure;
import tsml.classifiers.distance_based.distances.dtw.DTW;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
/**
* LCSS distance measure.
* <p>
* Contributors: goastler
*/
public class LCSSDistance extends MatrixBasedDistanceMeasure {
// delta === warp
// epsilon === diff between two values before they're considered the same AKA tolerance
private double epsilon = 0.01;
private double window = 1;
public static final String EPSILON_FLAG = "e";
public static final String WINDOW_FLAG = DTW.WINDOW_FLAG;
public double getEpsilon() {
return epsilon;
}
public void setEpsilon(double epsilon) {
this.epsilon = epsilon;
}
private boolean approxEqual(TimeSeriesInstance a, int aIndex, TimeSeriesInstance b, int bIndex) {
double sum = 0;
for(int i = 0; i < a.getNumDimensions(); i++) {
final TimeSeries aDim = a.get(i);
final TimeSeries bDim = b.get(i);
final Double aValue = aDim.get(aIndex);
final Double bValue = bDim.get(bIndex);
if(Math.abs(aValue - bValue) > epsilon) {
return false;
}
}
return true;
}
@Override
public double distance(TimeSeriesInstance a, TimeSeriesInstance b, double limit) {
// make a the longest time series
if(a.getMaxLength() < b.getMaxLength()) {
TimeSeriesInstance tmp = a;
a = b;
b = tmp;
}
final int aLength = a.getMaxLength();
final int bLength = b.getMaxLength();
setup(aLength, bLength, true);
// 22/10/19 goastler - limit LCSS such that if any value in the current window is larger than the limit then we can stop here, no point in doing the extra work
if(limit != Double.POSITIVE_INFINITY) { // check if there's a limit set
// if so then reverse engineer the max LCSS distance and replace the limit
// this is just the inverse of the return value integer rounded to an LCSS distance
limit = (1 - limit) * Math.min(aLength, bLength);
// is potentially slightly too low, causing *early* early abandon
}
// step is the increment of the mid point for each row
final double step = (double) (bLength - 1) / (aLength - 1);
final double windowSize = this.window * bLength;
// row index
int i = 0;
// start and end of window
int start = 0;
double mid = 0;
int end = Math.min(bLength - 1, (int) Math.floor(windowSize));
int prevEnd; // store end of window from previous row to fill in shifted space with inf
double[] row = getRow(i);
double[] prevRow;
// col index
int j = start;
// process top left sqaure of mat
double min = row[j] = approxEqual(a, i, b, j) ? 1 : 0;
j++;
// compute the first row
for(; j <= end; j++) {
if(approxEqual(a, i, b, j)) {
row[j] = 1;
} else {
row[j] = row[j - 1];
}
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
i++;
// process remaining rows
for(; i < aLength; i++) {
// reset min for the row
min = Double.POSITIVE_INFINITY;
// change rows
prevRow = row;
row = getRow(i);
// start, end and mid of window
prevEnd = end;
mid = i * step;
// if using variable length time series and window size is fractional then the window may part cover an
// element. Any part covered element is truncated from the window. I.e. mid point of 5.5 with window of 2.3
// would produce a start point of 2.2. The window would start from index 3 as it does not fully cover index
// 2. The same thing happens at the end, 5.5 + 2.3 = 7.8, so the end index is 7 as it does not fully cover 8
start = Math.max(0, (int) Math.ceil(mid - windowSize));
end = Math.min(bLength - 1, (int) Math.floor(mid + windowSize));
j = start;
// set the values above the current row and outside of previous window to inf
Arrays.fill(prevRow, prevEnd + 1, end + 1, Double.NEGATIVE_INFINITY);
// set the value left of the window to inf
if(j > 0) row[j - 1] = Double.NEGATIVE_INFINITY;
// if assessing the left most column then only mapping option is top - not left or topleft
if(j == 0) {
if(approxEqual(a, i, b, j)) {
row[j] = 1;
} else {
row[j] = prevRow[start];
}
min = Math.min(min, row[j++]);
}
// compute the distance for each cell in the row
for(; j <= end; j++) {
if(approxEqual(a, i, b, j)) {
row[j] = prevRow[j - 1] + 1;
} else {
// note that the below is an edge case fix. LCSS algorithmically doesn't consider the topLeft cell
// when computing the max sequence. However, when a harsh enough window is applied the top and left
// cell become neg inf, causing issues as the max of neg inf and neg inf is neg inf. Therefore, we
// include topLeft in the max sequence candidates. In the case of a harsh window, this finds the
// value in the topLeft cell as max rather than neg inf in left or top. In non-harsh window cases,
// the topLeft value is always the same as left or topLeft (because they were not approx equal) or
// -1 less (because they were approx equal, hence a +1 occurred. As it's always equal to or less, it
// has no effect upon the max operation under non-harsh window circumstances.
row[j] = Math.max(row[j - 1], Math.max(prevRow[j], prevRow[j - 1]));
}
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
}
// last value in the current row is the distance
final double distance = 1d - row[row.length - 1] / Math.min(aLength, bLength);
teardown();
return distance;
}
@Override protected double getFillerValue() {
return Double.NEGATIVE_INFINITY; // LCSS maximises the subsequence count, so fill cost matrix with neg inf to begin with
}
@Override
public ParamSet getParams() {
return super.getParams().add(WINDOW_FLAG, window).add(EPSILON_FLAG, epsilon);
}
@Override
public void setParams(final ParamSet param) throws Exception {
super.setParams(param);
setEpsilon(param.get(EPSILON_FLAG, getEpsilon()));
setWindow(param.get(WINDOW_FLAG, getWindow()));
}
public double getWindow() {
return window;
}
public void setWindow(final double window) {
this.window = window;
}
}
| 8,320 | 39.590244 | 167 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/lcss/spaces/LCSSDistanceContinuousParams.java | package tsml.classifiers.distance_based.distances.lcss.spaces;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import tsml.data_containers.TimeSeriesInstances;
import utilities.StatisticalUtilities;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
public class LCSSDistanceContinuousParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
final double std = StatisticalUtilities.pStdDev(data);
final ParamMap subSpace = new ParamMap();
subSpace.add(LCSSDistance.EPSILON_FLAG, new UniformDoubleDistribution(0.2 * std, std));
subSpace.add(WINDOW_FLAG, new UniformDoubleDistribution(0d, 1d));
return new ParamSpace(subSpace);
}
}
| 1,126 | 50.227273 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/lcss/spaces/LCSSDistanceContinuousSpace.java | package tsml.classifiers.distance_based.distances.lcss.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class LCSSDistanceContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new LCSSDistance()), new LCSSDistanceContinuousParams().build(data)));
}
}
| 900 | 52 | 171 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/lcss/spaces/LCSSDistanceParams.java | package tsml.classifiers.distance_based.distances.lcss.spaces;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import utilities.StatisticalUtilities;
import java.util.List;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
import static utilities.ArrayUtilities.range;
import static utilities.ArrayUtilities.unique;
public class LCSSDistanceParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
double std = StatisticalUtilities.pStdDev(data);
double stdFloor = std * 0.2;
double[] epsilonValues = range(stdFloor, std, 10);
double[] deltaValues = range(0d, 0.25, 10);
List<Double> epsilonValuesUnique = unique(epsilonValues);
List<Double> deltaValuesUnique = unique(deltaValues);
ParamMap params = new ParamMap();
params.add(LCSSDistance.EPSILON_FLAG, epsilonValuesUnique);
params.add(WINDOW_FLAG, deltaValuesUnique);
return new ParamSpace(params);
}
}
| 1,326 | 43.233333 | 82 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/lcss/spaces/LCSSDistanceRestrictedContinuousParams.java | package tsml.classifiers.distance_based.distances.lcss.spaces;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import tsml.data_containers.TimeSeriesInstances;
import utilities.StatisticalUtilities;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
public class LCSSDistanceRestrictedContinuousParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
final double std = StatisticalUtilities.pStdDev(data);
final ParamMap subSpace = new ParamMap();
subSpace.add(LCSSDistance.EPSILON_FLAG, new UniformDoubleDistribution(0.2 * std, std));
subSpace.add(WINDOW_FLAG, new UniformDoubleDistribution(0d, 0.25));
return new ParamSpace(subSpace);
}
}
| 1,138 | 50.772727 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/lcss/spaces/LCSSDistanceRestrictedContinuousSpace.java | package tsml.classifiers.distance_based.distances.lcss.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class LCSSDistanceRestrictedContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new LCSSDistance()), new LCSSDistanceRestrictedContinuousParams().build(data)));
}
}
| 920 | 53.176471 | 181 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/lcss/spaces/LCSSDistanceSpace.java | package tsml.classifiers.distance_based.distances.lcss.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class LCSSDistanceSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new LCSSDistance()), new LCSSDistanceParams().build(data)));
}
}
| 880 | 50.823529 | 161 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/msm/MSMDistance.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.classifiers.distance_based.distances.msm;
import tsml.classifiers.distance_based.distances.MatrixBasedDistanceMeasure;
import tsml.classifiers.distance_based.utils.collections.params.ParamHandlerUtils;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
/**
* MSM distance measure.
* <p>
* Contributors: goastler
*/
public class MSMDistance extends MatrixBasedDistanceMeasure {
private double c = 1;
public MSMDistance() {
}
public static final String C_FLAG = "c";
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
/**
* Find the cost for doing a move / split / merge for the univariate case.
* @param newPoint
* @param x
* @param y
* @return
*/
private double findCost(double newPoint, double x, double y) {
double dist = 0;
if(((x <= newPoint) && (newPoint <= y)) ||
((y <= newPoint) && (newPoint <= x))) {
dist = c;
} else {
dist = c + Math.min(Math.abs(newPoint - x), Math.abs(newPoint - y));
}
return dist;
}
/**
* Find the cost for doing a move / split / merge on the multivariate case.
* @param a
* @param aIndex
* @param b
* @param bIndex
* @param c
* @param cIndex
* @return
*/
private double cost(final TimeSeriesInstance a, final int aIndex, final TimeSeriesInstance b, final int bIndex, final TimeSeriesInstance c, final int cIndex) {
double sum = 0;
for(int i = 0; i < a.getNumDimensions(); i++) {
final TimeSeries aDim = a.get(i);
final TimeSeries bDim = b.get(i);
final TimeSeries cDim = c.get(i);
final Double aValue = aDim.get(aIndex);
final Double bValue = bDim.get(bIndex);
final Double cValue = cDim.get(cIndex);
sum += findCost(aValue, bValue, cValue);
}
return sum;
}
/**
* Find the cost for a individual cell. This is used when there's no alignment change and values are mapping directly to another.
* @param a
* @param aIndex
* @param b
* @param bIndex
* @return
*/
private double directCost(final TimeSeriesInstance a, final int aIndex, final TimeSeriesInstance b, final int bIndex) {
double sum = 0;
for(int i = 0; i < a.getNumDimensions(); i++) {
final TimeSeries aDim = a.get(i);
final TimeSeries bDim = b.get(i);
final Double aValue = aDim.get(aIndex);
final Double bValue = bDim.get(bIndex);
sum += Math.abs(aValue - bValue);
}
return sum;
}
@Override
public double distance(TimeSeriesInstance a, TimeSeriesInstance b, final double limit) {
// make a the longest time series
if(a.getMaxLength() < b.getMaxLength()) {
TimeSeriesInstance tmp = a;
a = b;
b = tmp;
}
final int aLength = a.getMaxLength();
final int bLength = b.getMaxLength();
setup(aLength, bLength, true);
// step is the increment of the mid point for each row
final double step = (double) (bLength - 1) / (aLength - 1);
final double windowSize = 1d * bLength;
// row index
int i = 0;
// start and end of window
int start = 0;
double mid = 0;
int end = Math.min(bLength - 1, (int) Math.floor(windowSize));
int prevEnd; // store end of window from previous row to fill in shifted space with inf
double[] row = getRow(i);
double[] prevRow;
// col index
int j = start;
// process top left sqaure of mat
double min = row[j] = directCost(a, i, b, j);
j++;
// compute the first row
for(; j <= end; j++) {
row[j] = row[j - 1] + cost(b, j, a, i, b, j - 1);
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
i++;
// process remaining rows
for(; i < aLength; i++) {
// reset min for the row
min = Double.POSITIVE_INFINITY;
// change rows
prevRow = row;
row = getRow(i);
// start, end and mid of window
prevEnd = end;
mid = i * step;
// if using variable length time series and window size is fractional then the window may part cover an
// element. Any part covered element is truncated from the window. I.e. mid point of 5.5 with window of 2.3
// would produce a start point of 2.2. The window would start from index 3 as it does not fully cover index
// 2. The same thing happens at the end, 5.5 + 2.3 = 7.8, so the end index is 7 as it does not fully cover 8
start = Math.max(0, (int) Math.ceil(mid - windowSize));
end = Math.min(bLength - 1, (int) Math.floor(mid + windowSize));
j = start;
// set the values above the current row and outside of previous window to inf
Arrays.fill(prevRow, prevEnd + 1, end + 1, Double.POSITIVE_INFINITY);
// set the value left of the window to inf
if(j > 0) row[j - 1] = Double.POSITIVE_INFINITY;
// if assessing the left most column then only mapping option is top - not left or topleft
if(j == 0) {
row[j] = prevRow[j] + cost(a, i, a, i - 1, b, j);
min = Math.min(min, row[j++]);
}
// compute the distance for each cell in the row
for(; j <= end; j++) {
final double topLeft = prevRow[j - 1] + directCost(a, i, b, j);
final double top = prevRow[j] + cost(a, i, a, i - 1, b, j);
final double left = row[j - 1] + cost(b, j, a, i, b, j - 1);
row[j] = Math.min(top, Math.min(left, topLeft));
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
}
// last value in the current row is the distance
final double distance = row[row.length - 1];
teardown();
return distance;
}
@Override
public ParamSet getParams() {
return super.getParams().add(C_FLAG, c);
}
@Override
public void setParams(final ParamSet param) throws Exception {
super.setParams(param);
setC(param.get(C_FLAG, getC()));
}
}
| 7,545 | 33.935185 | 163 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/msm/spaces/MSMDistanceContinuousParams.java | package tsml.classifiers.distance_based.distances.msm.spaces;
import tsml.classifiers.distance_based.distances.msm.MSMDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.distribution.CompositeDistribution;
import tsml.classifiers.distance_based.utils.collections.params.distribution.Distribution;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
import static utilities.ArrayUtilities.unique;
public class MSMDistanceContinuousParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
Distribution<Double> costParams = CompositeDistribution
.newUniformDoubleCompositeFromRange(newArrayList(0.01, 0.1, 1d, 10d, 100d));
ParamMap params = new ParamMap();
params.add(MSMDistance.C_FLAG, costParams);
return new ParamSpace(params);
}
}
| 1,221 | 52.130435 | 126 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/msm/spaces/MSMDistanceContinuousSpace.java | package tsml.classifiers.distance_based.distances.msm.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.msm.MSMDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class MSMDistanceContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new MSMDistance()), new MSMDistanceContinuousParams().build(data)));
}
}
| 894 | 51.647059 | 169 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/msm/spaces/MSMDistanceParams.java | package tsml.classifiers.distance_based.distances.msm.spaces;
import tsml.classifiers.distance_based.distances.msm.MSMDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import java.util.List;
import static utilities.ArrayUtilities.unique;
public class MSMDistanceParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
double[] costValues = {
// <editor-fold defaultstate="collapsed" desc="hidden for space">
0.01,
0.01375,
0.0175,
0.02125,
0.025,
0.02875,
0.0325,
0.03625,
0.04,
0.04375,
0.0475,
0.05125,
0.055,
0.05875,
0.0625,
0.06625,
0.07,
0.07375,
0.0775,
0.08125,
0.085,
0.08875,
0.0925,
0.09625,
0.1,
0.136,
0.172,
0.208,
0.244,
0.28,
0.316,
0.352,
0.388,
0.424,
0.46,
0.496,
0.532,
0.568,
0.604,
0.64,
0.676,
0.712,
0.748,
0.784,
0.82,
0.856,
0.892,
0.928,
0.964,
1,
1.36,
1.72,
2.08,
2.44,
2.8,
3.16,
3.52,
3.88,
4.24,
4.6,
4.96,
5.32,
5.68,
6.04,
6.4,
6.76,
7.12,
7.48,
7.84,
8.2,
8.56,
8.92,
9.28,
9.64,
10,
13.6,
17.2,
20.8,
24.4,
28,
31.6,
35.2,
38.8,
42.4,
46,
49.6,
53.2,
56.8,
60.4,
64,
67.6,
71.2,
74.8,
78.4,
82,
85.6,
89.2,
92.8,
96.4,
100// </editor-fold>
};
List<Double> costValuesUnique = unique(costValues);
ParamMap params = new ParamMap();
params.add(MSMDistance.C_FLAG, costValuesUnique);
return new ParamSpace(params);
}
}
| 3,218 | 24.959677 | 82 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/msm/spaces/MSMDistanceSpace.java | package tsml.classifiers.distance_based.distances.msm.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.msm.MSMDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class MSMDistanceSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new MSMDistance()), new MSMDistanceParams().build(data)));
}
}
| 874 | 50.470588 | 159 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/transformed/BaseTransformDistanceMeasure.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.classifiers.distance_based.distances.transformed;
/*
Purpose: // todo - docs - type the purpose of the code here
Contributors: goastler
*/
import tsml.classifiers.distance_based.distances.BaseDistanceMeasure;
import tsml.classifiers.distance_based.distances.MatrixBasedDistanceMeasure;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.ed.EDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamHandler;
import tsml.classifiers.distance_based.utils.collections.params.ParamHandlerUtils;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.data_containers.TimeSeriesInstance;
import tsml.transformers.Transformer;
import weka.core.Instance;
import java.util.Objects;
public class BaseTransformDistanceMeasure extends BaseDistanceMeasure implements TransformDistanceMeasure {
public BaseTransformDistanceMeasure(String name, Transformer transformer,
DistanceMeasure distanceMeasure) {
setDistanceMeasure(distanceMeasure);
setTransformer(transformer);
setName(name);
}
public BaseTransformDistanceMeasure() {
this(null, null, new EDistance());
}
public BaseTransformDistanceMeasure(String name) {
this(name, null, new EDistance());
}
public static final String TRANSFORMER_FLAG = "t";
private DistanceMeasure distanceMeasure;
private Transformer transformer;
private String name;
@Override public String getName() {
return name;
}
public void setName(String name) {
if(name == null) {
name = distanceMeasure.getName();
if(transformer != null) {
name = transformer.getClass().getSimpleName() + "_" + name;
}
}
this.name = name;
}
@Override public boolean isSymmetric() {
return distanceMeasure.isSymmetric();
}
public TimeSeriesInstance transform(TimeSeriesInstance inst) {
return transform(inst, true);
}
public TimeSeriesInstance transform(TimeSeriesInstance inst, boolean transform) {
if(transform) {
if(transformer != null) {
inst = transformer.transform(inst);
}
}
return inst;
}
public double distance(final TimeSeriesInstance a, final boolean transformA, final TimeSeriesInstance b, final boolean transformB, final double limit) {
try {
// users must call fit method on transformer if required before calling distance
final TimeSeriesInstance at = transform(a, transformA);
// need to take the interval here, before the transform
final TimeSeriesInstance bt = transform(b, transformB);
return distanceMeasure.distance(at, bt, limit);
} catch(Exception e) {
throw new IllegalStateException(e);
}
}
public DistanceMeasure getDistanceMeasure() {
return distanceMeasure;
}
public void setDistanceMeasure(DistanceMeasure distanceMeasure) {
this.distanceMeasure = Objects.requireNonNull(distanceMeasure);
}
@Override public ParamSet getParams() {
final ParamSet paramSet = super.getParams();
paramSet.add(TRANSFORMER_FLAG, transformer);
paramSet.add(DistanceMeasure.DISTANCE_MEASURE_FLAG, distanceMeasure);
return paramSet;
}
@Override
public void setParams(final ParamSet param) throws Exception {
setTransformer(param.get(TRANSFORMER_FLAG, transformer));
setDistanceMeasure(param.get(DISTANCE_MEASURE_FLAG, distanceMeasure));
super.setParams(param);
}
public Transformer getTransformer() {
return transformer;
}
public void setTransformer(Transformer a) {
transformer = a;
}
@Override public String toString() {
return getName() + " " + distanceMeasure.getParams();
}
}
| 4,794 | 33.496403 | 156 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/transformed/TransformDistanceMeasure.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.classifiers.distance_based.distances.transformed;
/*
Purpose: // todo - docs - type the purpose of the code here
Contributors: goastler
*/
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.data_containers.TimeSeriesInstance;
import tsml.data_containers.TimeSeriesInstances;
import tsml.transformers.TrainableTransformer;
import tsml.transformers.Transformer;
import weka.core.DistanceFunction;
import java.util.Collections;
import java.util.List;
public interface TransformDistanceMeasure extends DistanceMeasure {
DistanceMeasure getDistanceMeasure();
Transformer getTransformer();
void setDistanceMeasure(DistanceMeasure distanceMeasure);
void setTransformer(Transformer transformer);
void setName(String name);
default void buildDistanceMeasure(TimeSeriesInstances data, boolean transformed) {
// transform the data if not already
if(!transformed) {
final Transformer transformer = getTransformer();
if(transformer instanceof TrainableTransformer) {
((TrainableTransformer) transformer).fit(data);
}
data = transformer.transform(data);
}
getDistanceMeasure().buildDistanceMeasure(data);
}
default void buildDistanceMeasure(TimeSeriesInstances data) {
buildDistanceMeasure(data, true);
}
default double distance(TimeSeriesInstance a, TimeSeriesInstance b, double limit) {
return distance(a, true, b, true, limit);
}
double distance(TimeSeriesInstance a, boolean transformA, TimeSeriesInstance b, boolean transformB, double limit);
default double distance(TimeSeriesInstance a, boolean transformA, TimeSeriesInstance b, boolean transformB) {
return distance(a, transformA, b, transformB, Double.POSITIVE_INFINITY);
}
default double distanceUnivariate(double[] a, boolean transformA, double[] b, boolean transformB, double limit) {
return distance(new TimeSeriesInstance(a), transformA, new TimeSeriesInstance(b), transformB, limit);
}
default double distanceUnivariate(double[] a, boolean transformA, double[] b, boolean transformB) {
return distanceUnivariate(a, transformA, b, transformB, Double.POSITIVE_INFINITY);
}
default double distanceMultivariate(double[][] a, boolean transformA, double[][] b, boolean transformB, double limit) {
return distance(new TimeSeriesInstance(a), transformA, new TimeSeriesInstance(b), transformB, limit);
}
default double distanceMultivariate(double[][] a, boolean transformA, double[][] b, boolean transformB) {
return distanceMultivariate(a, transformA, b, transformB, Double.POSITIVE_INFINITY);
}
default double distanceUnivariate(List<Double> a, boolean transformA, List<Double> b, boolean transformB, double limit) {
return distanceMultivariate(Collections.singletonList(a), transformA, Collections.singletonList(b), transformB, limit);
}
default double distanceUnivariate(List<Double> a, boolean transformA, List<Double> b, boolean transformB) {
return distanceUnivariate(a, transformA, b, transformB, Double.POSITIVE_INFINITY);
}
default double distanceMultivariate(List<List<Double>> a, boolean transformA, List<List<Double>> b, boolean transformB, double limit) {
return distance(new TimeSeriesInstance(a), transformA, new TimeSeriesInstance(b), transformB, limit);
}
default double distanceMultivariate(List<List<Double>> a, boolean transformA, List<List<Double>> b, boolean transformB) {
return distanceMultivariate(a, transformA, b, transformB, Double.POSITIVE_INFINITY);
}
}
| 4,480 | 42.931373 | 139 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/twed/TWEDistance.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.classifiers.distance_based.distances.twed;
import tsml.classifiers.distance_based.distances.MatrixBasedDistanceMeasure;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import utilities.ArrayUtilities;
import java.util.Arrays;
/**
* TWED distance measure.
* <p>
* Contributors: goastler
*/
public class TWEDistance
extends MatrixBasedDistanceMeasure {
private double lambda = 1;
private double nu = 1;
public static final String NU_FLAG = "n";
public static final String LAMBDA_FLAG = "l";
private double cost(final TimeSeriesInstance a, final int aIndex, final TimeSeriesInstance b, final int bIndex) {
double sum = 0;
for(int i = 0; i < a.getNumDimensions(); i++) {
final TimeSeries aDim = a.get(i);
final TimeSeries bDim = b.get(i);
final double aValue = aDim.get(aIndex);
final double bValue = bDim.get(bIndex);
final double sqDiff = StrictMath.pow(aValue - bValue, 2);
sum += sqDiff;
}
return sum;
}
private double cellCost(final TimeSeriesInstance a, final int aIndex) {
double sum = 0;
for(int i = 0; i < a.getNumDimensions(); i++) {
final TimeSeries aDim = a.get(i);
final double aValue = aDim.get(aIndex);
final double sq = StrictMath.pow(aValue, 2);
sum += sq;
}
return sum;
}
@Override
public double distance(TimeSeriesInstance a, TimeSeriesInstance b, final double limit) {
// make a the longest time series
if(a.getMaxLength() < b.getMaxLength()) {
TimeSeriesInstance tmp = a;
a = b;
b = tmp;
}
final int aLength = a.getMaxLength();
final int bLength = b.getMaxLength();
setup(aLength + 1, bLength + 1, true);
// step is the increment of the mid point for each row
final double step = (double) (bLength) / (aLength);
final double windowSize = 1d * bLength + 1; // +1 because of padding col
// row index
int i = 0;
// start and end of window
int start = 0;
double mid = 0;
int end = Math.min(bLength, (int) Math.floor(windowSize)); // +1 as matrix padded by 1 row and 1 col
int prevEnd; // store end of window from previous row to fill in shifted space with inf
double[] row = getRow(i);
double[] prevRow;
double[] jCosts = new double[bLength + 1];
double min, iCost;
// col index
int j = start;
// border of the cost matrix initialization
row[j++] = 0;
row[j] = jCosts[j] = cellCost(b, i);
j++;
// compute the first padded row
for(; j <= end; j++) {
//CHANGE AJB 8/1/16: Only use power of 2 for speed up
jCosts[j] = cost(b, j - 2, b, j - 1);
row[j] = row[j - 1] + jCosts[j];
}
i++;
// process remaining rows
for(; i < aLength + 1; i++) {
// reset min for the row
min = Double.POSITIVE_INFINITY;
// change rows
prevRow = row;
row = getRow(i);
// start, end and mid of window
prevEnd = end;
mid = i * step;
// if using variable length time series and window size is fractional then the window may part cover an
// element. Any part covered element is truncated from the window. I.e. mid point of 5.5 with window of 2.3
// would produce a start point of 2.2. The window would start from index 3 as it does not fully cover index
// 2. The same thing happens at the end, 5.5 + 2.3 = 7.8, so the end index is 7 as it does not fully cover 8
start = Math.max(0, (int) Math.ceil(mid - windowSize));
end = Math.min(bLength, (int) Math.floor(mid + windowSize));
j = start;
// set the values above the current row and outside of previous window to inf
Arrays.fill(prevRow, prevEnd + 1, end + 1, Double.POSITIVE_INFINITY);
// set the value left of the window to inf
if(j > 0) row[j - 1] = Double.POSITIVE_INFINITY; // >1 as matrix padded with 1 row and 1 col
// fill any jCosts which have not yet been visited
for(int x = prevEnd + 1; x <= end; x++) {
jCosts[x] = cost(b, x - 2, b, x - 1);
}
// the ith cost for this row
if(i > 1) {
iCost = cost(a, i - 2, a, i - 1);
} else {
iCost = cellCost(a, i - 1);
}
// if assessing the left most column then only mapping option is top - not left or topleft
if(j == 0) {
row[j] = prevRow[j] + iCost;
min = Math.min(min, row[j++]);
}
// compute the distance for each cell in the row
for(; j <= end; j++) {
double dist = cost(a, i - 1, b, j - 1);
double htrans = Math.abs(i - j);
if(i > 1 && j > 1) {
dist += cost(a, i - 2, b, j - 2);
htrans *= 2;
}
final double topLeft = prevRow[j - 1] + nu * htrans + dist;
final double top = iCost + prevRow[j] + lambda + nu;
final double left = jCosts[j] + row[j - 1] + lambda + nu;
row[j] = Math.min(topLeft, Math.min(top, left));
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
}
// last value in the current row is the distance
final double distance = row[row.length - 1];
teardown();
return distance;
}
public double getLambda() {
return lambda;
}
public void setLambda(double lambda) {
this.lambda = lambda;
}
public double getNu() {
return nu;
}
public void setNu(double nu) {
this.nu = nu;
}
@Override
public ParamSet getParams() {
return super.getParams().add(NU_FLAG, nu).add(LAMBDA_FLAG, lambda);
}
@Override
public void setParams(final ParamSet param) throws Exception {
super.setParams(param);
setLambda(param.get(LAMBDA_FLAG, getLambda()));
setNu(param.get(NU_FLAG, getNu()));
}
public static void main(String[] args) {
final TWEDistance dm = new TWEDistance();
dm.setRecordCostMatrix(true);
System.out.println(dm.distance(new TimeSeriesInstance(new double[][]{{1,2,3,3,2,4,5,2}}), new TimeSeriesInstance(new double[][] {{2,3,4,5,6,2,2,2}})));
System.out.println(ArrayUtilities.toString(dm.costMatrix()));
}
}
| 7,728 | 34.948837 | 159 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/twed/spaces/TWEDistanceContinuousParams.java | package tsml.classifiers.distance_based.distances.twed.spaces;
import tsml.classifiers.distance_based.distances.twed.TWEDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.distribution.CompositeDistribution;
import tsml.classifiers.distance_based.utils.collections.params.distribution.Distribution;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
import static utilities.ArrayUtilities.unique;
public class TWEDistanceContinuousParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
Distribution<Double> nuDistribution = CompositeDistribution.newUniformDoubleCompositeFromRange(newArrayList(0.00001,
0.0001,
0.0005,
0.001,
0.005,
0.01,
0.05,
0.1,
0.5,
1d));
UniformDoubleDistribution lambdaDistribution = new UniformDoubleDistribution();
ParamMap params = new ParamMap();
params.add(TWEDistance.LAMBDA_FLAG, lambdaDistribution);
params.add(TWEDistance.NU_FLAG, nuDistribution);
return new ParamSpace(params);
}
}
| 1,634 | 47.088235 | 124 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/twed/spaces/TWEDistanceContinuousSpace.java | package tsml.classifiers.distance_based.distances.twed.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.twed.TWEDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class TWEDistanceContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new TWEDistance()),
new TWEDistanceContinuousParams().build(data)));
}
}
| 912 | 49.722222 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/twed/spaces/TWEDistanceParams.java | package tsml.classifiers.distance_based.distances.twed.spaces;
import tsml.classifiers.distance_based.distances.twed.TWEDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import java.util.List;
import static utilities.ArrayUtilities.unique;
public class TWEDistanceParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
double[] nuValues = {
// <editor-fold defaultstate="collapsed" desc="hidden for space">
0.00001,
0.0001,
0.0005,
0.001,
0.005,
0.01,
0.05,
0.1,
0.5,
1,// </editor-fold>
};
double[] lambdaValues = {
// <editor-fold defaultstate="collapsed" desc="hidden for space">
0,
0.011111111,
0.022222222,
0.033333333,
0.044444444,
0.055555556,
0.066666667,
0.077777778,
0.088888889,
0.1,// </editor-fold>
};
List<Double> nuValuesUnique = unique(nuValues);
List<Double> lambdaValuesUnique = unique(lambdaValues);
ParamMap params = new ParamMap();
params.add(TWEDistance.LAMBDA_FLAG, lambdaValuesUnique);
params.add(TWEDistance.NU_FLAG, nuValuesUnique);
return new ParamSpace(params);
}
}
| 1,731 | 34.346939 | 82 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/twed/spaces/TWEDistanceSpace.java | package tsml.classifiers.distance_based.distances.twed.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.twed.TWEDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class TWEDistanceSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new TWEDistance()),
new TWEDistanceParams().build(data)));
}
}
| 892 | 48.611111 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/wdtw/WDTW.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.classifiers.distance_based.distances.wdtw;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.dtw.DTW;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public interface WDTW extends DistanceMeasure {
String G_FLAG = "g";
double getG();
void setG(double g);
}
| 1,171 | 30.675676 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/wdtw/WDTWDistance.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.classifiers.distance_based.distances.wdtw;
import tsml.classifiers.distance_based.distances.MatrixBasedDistanceMeasure;
import tsml.classifiers.distance_based.utils.collections.params.ParamHandlerUtils;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
import static tsml.classifiers.distance_based.distances.dtw.DTWDistance.cost;
/**
* WDTW distance measure.
* <p>
* Contributors: goastler
*/
public class WDTWDistance
extends MatrixBasedDistanceMeasure implements WDTW {
private double g = 0.05;
private double[] weights = new double[0];
@Override
public double getG() {
return g;
}
@Override
public void setG(double g) {
if(g != this.g) {
// reset the weights if g changes
weights = new double[0];
}
this.g = g;
}
private void generateWeights(int length) {
if(weights.length < length) {
final double halfLength = (double) length / 2;
double[] oldWeights = weights;
weights = new double[length];
System.arraycopy(oldWeights, 0, weights, 0, oldWeights.length);
for(int i = oldWeights.length; i < length; i++) {
weights[i] = 1d / (1d + Math.exp(-g * (i - halfLength)));
}
}
}
@Override
public double distance(TimeSeriesInstance a, TimeSeriesInstance b, final double limit) {
// make a the longest time series
if(a.getMaxLength() < b.getMaxLength()) {
TimeSeriesInstance tmp = a;
a = b;
b = tmp;
}
final int aLength = a.getMaxLength();
final int bLength = b.getMaxLength();
setup(aLength, bLength, true);
// step is the increment of the mid point for each row
final double step = (double) (bLength - 1) / (aLength - 1);
final double window = 1;
final double windowSize = window * bLength;
// generate weights for soft weighting of costs
generateWeights(Math.max(aLength, bLength));
// row index
int i = 0;
// start and end of window
int start = 0;
double mid = 0;
int end = Math.min(bLength - 1, (int) Math.floor(windowSize));
int prevEnd; // store end of window from previous row to fill in shifted space with inf
double[] row = getRow(i);
double[] prevRow;
// col index
int j = start;
// process top left cell of mat
double min = row[j] = weights[j] * cost(a, i, b, j);
j++;
// compute the first row
for(; j <= end; j++) {
row[j] = row[j - 1] + weights[j] * cost(a, i, b, j);
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
i++;
// process remaining rows
for(; i < aLength; i++) {
// reset min for the row
min = Double.POSITIVE_INFINITY;
// change rows
prevRow = row;
row = getRow(i);
// start, end and mid of window
prevEnd = end;
mid = i * step;
// if using variable length time series and window size is fractional then the window may part cover an
// element. Any part covered element is truncated from the window. I.e. mid point of 5.5 with window of 2.3
// would produce a start point of 2.2. The window would start from index 3 as it does not fully cover index
// 2. The same thing happens at the end, 5.5 + 2.3 = 7.8, so the end index is 7 as it does not fully cover 8
start = Math.max(0, (int) Math.ceil(mid - windowSize));
end = Math.min(bLength - 1, (int) Math.floor(mid + windowSize));
j = start;
// set the values above the current row and outside of previous window to inf
Arrays.fill(prevRow, prevEnd + 1, end + 1, Double.POSITIVE_INFINITY);
// set the value left of the window to inf
if(j > 0) row[j - 1] = Double.POSITIVE_INFINITY;
// if assessing the left most column then only mapping option is top - not left or topleft
if(j == 0) {
row[j] = prevRow[j] + weights[Math.abs(i - j)] * cost(a, i, b, j);
min = Math.min(min, row[j++]);
}
// compute the distance for each cell in the row
for(; j <= end; j++) {
row[j] = Math.min(prevRow[j], Math.min(row[j - 1], prevRow[j - 1])) + weights[Math.abs(i - j)] * cost(a, i, b, j);;
min = Math.min(min, row[j]);
}
if(min > limit) return Double.POSITIVE_INFINITY; // quit if beyond limit
}
// last value in the current row is the distance
final double distance = row[row.length - 1];
teardown();
return distance;
}
@Override
public ParamSet getParams() {
return super.getParams().add(WDTW.G_FLAG, g);
}
@Override
public void setParams(final ParamSet param) throws Exception {
super.setParams(param);
setG(param.get(G_FLAG, getG()));
}
}
| 6,131 | 35.070588 | 131 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/wdtw/spaces/WDDTWDistanceContinuousSpace.java | package tsml.classifiers.distance_based.distances.wdtw.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.distances.wdtw.spaces.WDDTWDistanceSpace.newWDDTWDistance;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class WDDTWDistanceContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(newWDDTWDistance()),
new WDTWDistanceContinuousSpace().build(data)));
}
}
| 954 | 49.263158 | 121 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/wdtw/spaces/WDDTWDistanceSpace.java | package tsml.classifiers.distance_based.distances.wdtw.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.transformed.BaseTransformDistanceMeasure;
import tsml.classifiers.distance_based.distances.transformed.TransformDistanceMeasure;
import tsml.classifiers.distance_based.distances.wdtw.WDTWDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import tsml.transformers.Derivative;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class WDDTWDistanceSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(newWDDTWDistance()),
new WDTWDistanceSpace().build(data)));
}
/**
* build WDDTW
*
* @return
*/
public static TransformDistanceMeasure newWDDTWDistance() {
return new BaseTransformDistanceMeasure("WDDTWDistance", new Derivative(), new WDTWDistance());
}
}
| 1,344 | 42.387097 | 121 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/wdtw/spaces/WDTWDistanceContinuousParams.java | package tsml.classifiers.distance_based.distances.wdtw.spaces;
import tsml.classifiers.distance_based.distances.wdtw.WDTW;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import tsml.data_containers.TimeSeriesInstances;
import static utilities.ArrayUtilities.unique;
public class WDTWDistanceContinuousParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
final ParamMap subSpace = new ParamMap();
subSpace.add(WDTW.G_FLAG, new UniformDoubleDistribution(0d, 1d));
return new ParamSpace(subSpace);
}
}
| 891 | 43.6 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/wdtw/spaces/WDTWDistanceContinuousSpace.java | package tsml.classifiers.distance_based.distances.wdtw.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.wdtw.WDTWDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class WDTWDistanceContinuousSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new WDTWDistance()),
new WDTWDistanceContinuousParams().build(data)));
}
}
| 917 | 47.315789 | 121 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/wdtw/spaces/WDTWDistanceParams.java | package tsml.classifiers.distance_based.distances.wdtw.spaces;
import tsml.classifiers.distance_based.distances.wdtw.WDTW;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import java.util.List;
import static utilities.ArrayUtilities.unique;
public class WDTWDistanceParams implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
double[] gValues = new double[101];
for(int i = 0; i < gValues.length; i++) {
gValues[i] = (double) i / 100;
}
List<Double> gValuesUnique = unique(gValues);
ParamMap params = new ParamMap();
params.add(WDTW.G_FLAG, gValuesUnique);
return new ParamSpace(params);
}
}
| 953 | 35.692308 | 82 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/distances/wdtw/spaces/WDTWDistanceSpace.java | package tsml.classifiers.distance_based.distances.wdtw.spaces;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.wdtw.WDTWDistance;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.data_containers.TimeSeriesInstances;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class WDTWDistanceSpace implements ParamSpaceBuilder {
@Override public ParamSpace build(final TimeSeriesInstances data) {
return new ParamSpace(new ParamMap().add(DistanceMeasure.DISTANCE_MEASURE_FLAG, newArrayList(new WDTWDistance()),
new WDTWDistanceParams().build(data)));
}
}
| 897 | 46.263158 | 121 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/elastic_ensemble/ElasticEnsemble.java | package tsml.classifiers.distance_based.elastic_ensemble;
import evaluation.evaluators.Evaluator;
import evaluation.evaluators.InternalEstimateEvaluator;
import evaluation.storage.ClassifierResults;
import tsml.classifiers.TSClassifier;
import tsml.classifiers.TrainEstimateTimeable;
import tsml.classifiers.distance_based.distances.dtw.spaces.*;
import tsml.classifiers.distance_based.distances.ed.spaces.EDistanceSpace;
import tsml.classifiers.distance_based.distances.erp.spaces.ERPDistanceSpace;
import tsml.classifiers.distance_based.distances.lcss.spaces.LCSSDistanceSpace;
import tsml.classifiers.distance_based.distances.msm.spaces.MSMDistanceSpace;
import tsml.classifiers.distance_based.distances.twed.spaces.TWEDistanceSpace;
import tsml.classifiers.distance_based.distances.wdtw.spaces.WDDTWDistanceSpace;
import tsml.classifiers.distance_based.distances.wdtw.spaces.WDTWDistanceSpace;
import tsml.classifiers.distance_based.optimised.KnnAgent;
import tsml.classifiers.distance_based.optimised.OptimisedClassifier;
import tsml.classifiers.distance_based.utils.classifiers.BaseClassifier;
import tsml.classifiers.distance_based.utils.classifiers.configs.Configs;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.CheckpointConfig;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.Checkpointed;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTest;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTrain;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ProgressiveBuild;
import tsml.classifiers.distance_based.utils.classifiers.results.ResultUtils;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.iteration.RandomSearch;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatchable;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatcher;
import tsml.classifiers.distance_based.utils.system.timing.StopWatch;
import tsml.data_containers.TimeSeriesInstance;
import tsml.data_containers.TimeSeriesInstances;
import utilities.ArrayUtilities;
import utilities.Utilities;
import java.util.*;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class ElasticEnsemble extends BaseClassifier implements ContractedTrain, ContractedTest, ProgressiveBuild, Checkpointed,
MemoryWatchable, TrainEstimateTimeable {
public final static Configs<ElasticEnsemble> CONFIGS = buildConfigs().immutable();
public static Configs<ElasticEnsemble> buildConfigs() {
final Configs<ElasticEnsemble> configs = new Configs<>();
configs.add("EE", "Elastic ensemble with default constituents (ED, DTW, Full DTW, DDTW, Full DDTW, ERP, LCSS, MSM, TWED, WDTW, WDDTW", ElasticEnsemble::new, ee -> {
ee.setTestTimeLimit(-1);
ee.setTrainTimeLimit(-1);
ee.setDistanceMeasureSpaceBuilders(newArrayList(
new EDistanceSpace(),
new DTWDistanceFullWindowSpace(),
new DTWDistanceSpace(),
new DDTWDistanceFullWindowSpace(),
new DDTWDistanceSpace(),
new WDTWDistanceSpace(),
new WDDTWDistanceSpace(),
new LCSSDistanceSpace(),
new ERPDistanceSpace(),
new TWEDistanceSpace(),
new MSMDistanceSpace()
));
});
return configs;
}
public ElasticEnsemble() {
super(true);
CONFIGS.get("EE").configure(this);
}
private final StopWatch runTimer = new StopWatch();
private final StopWatch evaluationTimer = new StopWatch();
private final StopWatch testTimer = new StopWatch();
private final MemoryWatcher memoryWatcher = new MemoryWatcher();
private final CheckpointConfig checkpointConfig = new CheckpointConfig();
private long trainTimeLimit = -1;
private long testTimeLimit = -1;
private long longestTrainStageTime = 0;
private List<ParamSpaceBuilder> distanceMeasureSpaceBuilders = new ArrayList<>();
private List<OptimisedClassifier> constiteunts;
private List<OptimisedClassifier> remainingConstituents;
@Override public CheckpointConfig getCheckpointConfig() {
return checkpointConfig;
}
@Override public long getMaxMemoryUsage() {
return memoryWatcher.getMaxMemoryUsage();
}
@Override public long getTrainTime() {
return getRunTime() - getCheckpointingTime() - getTrainEstimateTime();
}
@Override public long getTrainEstimateTime() {
throw new UnsupportedOperationException();
}
@Override public long getRunTime() {
return runTimer.elapsedTime();
}
@Override public long getTestTime() {
return testTimer.elapsedTime();
}
@Override public boolean isFullyBuilt() {
return remainingConstituents.isEmpty();
}
@Override public void buildClassifier(final TimeSeriesInstances trainData) throws Exception {
final long timeStamp = System.nanoTime();
memoryWatcher.start();
checkpointConfig.setLogger(getLogger());
// several scenarios for entering this method:
// 1) from scratch: isRebuild() is true
// 1a) checkpoint found and loaded, resume from wherever left off
// 1b) checkpoint not found, therefore initialise classifier and build from scratch
// 2) rebuild off, i.e. buildClassifier has been called before and already handled 1a or 1b. We can safely continue building from current state. This is often the case if a smaller contract has been executed (e.g. 1h), then the contract is extended (e.g. to 2h) and we enter into this method again. There is no need to reinitialise / discard current progress - simply continue on under new constraints.
if(isRebuild()) {
// case (1)
// load from a checkpoint
if(loadCheckpoint()) {
memoryWatcher.start();
checkpointConfig.setLogger(getLogger());
} else {
runTimer.reset();
evaluationTimer.reset();
checkpointConfig.resetCheckpointingTime();
memoryWatcher.reset();
// case (1b)
// let super build anything necessary (will handle isRebuild accordingly in super class)
super.buildClassifier(trainData);
// if rebuilding
// then init vars
checkRandom();
longestTrainStageTime = 0;
// for each distance measure space
constiteunts = new ArrayList<>();
remainingConstituents = new LinkedList<>(); // the classifiers which are not fully built
for(ParamSpaceBuilder builder : distanceMeasureSpaceBuilders) {
// build the agent to guide knn tuning
final KnnAgent agent = new KnnAgent();
agent.setParamSpaceBuilder(builder);
agent.setSearch(new RandomSearch());
agent.setEvaluatorBuilder(InternalEstimateEvaluator::new);
agent.setScorer(ClassifierResults::getAcc);
// build the optimised classifier, which uses the agent to do the optimisation
final OptimisedClassifier classifier = new OptimisedClassifier();
classifier.setAgent(agent);
classifier.setSeed(getSeed());
// kick off the classifier
classifier.beforeBuild();
if(!classifier.isFullyBuilt()) {
remainingConstituents.add(classifier);
}
constiteunts.add(classifier);
}
} // else case (1a)
} // else case (2)
runTimer.start(timeStamp);
// loop through tuned knns until no further increments remain or out of time
final StopWatch trainStageTimer = new StopWatch();
boolean workDone = false;
// multiply up the longest train stage time to leave time for consolidating results into 1
while(insideTrainTimeLimit(System.nanoTime() + longestTrainStageTime * constiteunts.size()) && !remainingConstituents.isEmpty()) {
trainStageTimer.resetAndStart();
final OptimisedClassifier classifier = remainingConstituents.remove(0);
classifier.nextBuildStep();
if(classifier.hasNextBuildStep()) {
remainingConstituents.add(classifier);
}
workDone = true;
saveCheckpoint();
longestTrainStageTime = Math.max(longestTrainStageTime, trainStageTimer.elapsedTime());
}
if(workDone || trainResults.getPredClassVals() == null) {
// init the train results
trainResults = new ClassifierResults();
final double[][] distributions = new double[trainData.numInstances()][trainData.numClasses()];
final long[] predictionTimes = new long[trainData.numInstances()];
// consolidate train results via ensembling
for(OptimisedClassifier classifier : constiteunts) {
// finalise the build for the constituent
classifier.afterBuild();
// get the train results for the constituent
final ClassifierResults trainResults = classifier.getTrainResults();
final double acc = trainResults.getAcc();
for(int i = 0; i < trainData.numInstances(); i++) {
final double prediction = trainResults.getPredClassValue(i);
distributions[i][(int) prediction] += acc;
predictionTimes[i] += trainResults.getPredictionTime(i);
}
}
for(int i = 0; i < distributions.length; i++) {
// normalise predictions
ArrayUtilities.normalise(distributions[i]);
final int prediction = Utilities.argMax(distributions[i], getRandom());
final long predictionTime = predictionTimes[i];
final int labelIndex = trainData.get(i).getLabelIndex();
trainResults.addPrediction(labelIndex, distributions[i], prediction, predictionTime, null);
}
}
memoryWatcher.stop();
runTimer.stop();
if(workDone || trainResults.getPredClassVals() == null) {
forceSaveCheckpoint();
ResultUtils.setInfo(trainResults, this, trainData);
}
}
@Override public double[] distributionForInstance(final TimeSeriesInstance inst) throws Exception {
final double[] distribution = new double[getLabels().length];
for(OptimisedClassifier classifier : constiteunts) {
final double[] constituentDistribution = classifier.distributionForInstance(inst);
final int prediction = Utilities.argMax(constituentDistribution, getRandom());
distribution[prediction] += classifier.getTrainResults().getAcc();
}
ArrayUtilities.normalise(distribution);
return distribution;
}
public boolean withinTrainContract(long time) {
return insideTrainTimeLimit(time);
}
public List<ParamSpaceBuilder> getDistanceMeasureSpaceBuilders() {
return distanceMeasureSpaceBuilders;
}
public void setDistanceMeasureSpaceBuilders(
final List<ParamSpaceBuilder> distanceMeasureSpaceBuilders) {
this.distanceMeasureSpaceBuilders = distanceMeasureSpaceBuilders;
Objects.requireNonNull(distanceMeasureSpaceBuilders);
}
public static class Constituent {
public Constituent(final Evaluator evaluator, final TSClassifier classifier) {
this.evaluator = Objects.requireNonNull(evaluator);
this.classifier = Objects.requireNonNull(classifier);
}
private final Evaluator evaluator;
private final TSClassifier classifier;
public Evaluator getEvaluator() {
return evaluator;
}
public TSClassifier getClassifier() {
return classifier;
}
}
public long getTestTimeLimit() {
return testTimeLimit;
}
public void setTestTimeLimit(final long testTimeLimit) {
this.testTimeLimit = testTimeLimit;
}
public long getTrainTimeLimit() {
return trainTimeLimit;
}
public void setTrainTimeLimit(final long trainTimeLimit) {
this.trainTimeLimit = trainTimeLimit;
}
}
| 12,902 | 44.755319 | 410 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/knn/KNN.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.classifiers.distance_based.knn;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;
import evaluation.storage.ClassifierResults;
import experiments.data.DatasetLoading;
import tsml.classifiers.TrainEstimateTimeable;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.ed.EDistance;
import tsml.classifiers.distance_based.utils.classifiers.configs.Configs;
import tsml.classifiers.distance_based.utils.collections.pruned.PrunedMap;
import tsml.classifiers.distance_based.utils.classifiers.BaseClassifier;
import tsml.classifiers.distance_based.utils.system.copy.CopierUtils;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.CheckpointConfig;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.Checkpointed;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTest;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTrain;
import tsml.classifiers.distance_based.utils.classifiers.results.ResultUtils;
import tsml.classifiers.distance_based.utils.collections.CollectionUtils;
import tsml.classifiers.distance_based.utils.collections.checks.Checks;
import tsml.classifiers.distance_based.utils.collections.lists.UnorderedArrayList;
import tsml.classifiers.distance_based.utils.collections.params.ParamHandler;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.system.random.RandomUtils;
import tsml.classifiers.distance_based.utils.system.timing.StopWatch;
import tsml.data_containers.TimeSeriesInstance;
import tsml.data_containers.TimeSeriesInstances;
import utilities.ArrayUtilities;
import utilities.ClassifierTools;
public class KNN extends BaseClassifier implements ParamHandler, Checkpointed, ContractedTrain, TrainEstimateTimeable,
ContractedTest {
public static void main(String[] args) throws Exception {
final int seed = 0;
final KNN classifier = new KNN();
classifier.setSeed(seed);
classifier.setEstimateOwnPerformance(true);
classifier.setEarlyPredict(true);
// final List<Integer> neighboursByClass = Arrays.asList(5, 20, 15, 18, 40, 3, 22);
// final List<Integer> nearestNeighbourClassDistribution = Arrays.asList(3, 0, 0, 0, 1, 0, 1);
// final ArrayList<Integer> list = new ArrayList<>(new IndexList(neighboursByClass.size()));
// Collections.sort(list, ((Comparator<Integer>) (a, b) -> Boolean.compare(nearestNeighbourClassDistribution.get(a) == 0,
// nearestNeighbourClassDistribution.get(b) == 0))
// .thenComparing(Comparator.comparingInt(neighboursByClass::get).reversed()).reversed());
// Utilities.sleep(10000);
// final Instances[] insts = DatasetLoading.sampleGunPoint(seed);
// final TimeSeriesInstances data = Converter.fromArff(insts[0]);
//
// long timeStamp;
// final int num = 5;
// final long[] timeSums = new long[num];
// final int numRepeats = 1000;
// String output = null;
//
// for(int i = 0; i < numRepeats; i++) {
// for(int j = 3; j < num; j++) {
// if(j == 3) {
// classifier.earlyPredict = false;
// } else {
// classifier.earlyPredict = true;
// }
//// classifier.setLogLevel(Level.ALL);
// timeStamp = System.nanoTime();
// classifier.setCheckpointPath("checkpoints");
// classifier.getCheckpointConfig().setInterval(1, TimeUnit.MINUTES);
// classifier.buildClassifier(data);
// final long time = System.nanoTime() - timeStamp;
// timeSums[j] += time;
// if(i == 0) {
// System.out.println(classifier.getTrainResults().writeFullResultsToString());
// if(output == null) {
// output = classifier.getTrainResults().writeFullResultsToString();
// } else {
// Assert.assertEquals(output, classifier.getTrainResults().writeFullResultsToString());
// }
// }
// }
//
// }
//
// System.out.println(Arrays.toString(Arrays.stream(timeSums).map(i -> i / numRepeats).toArray()));
// classifier.setCheckpointPath("checkpoints");
classifier.setK(20);
classifier.setAutoK(true);
classifier.setCheckpointInterval(1, TimeUnit.MINUTES);
ClassifierTools.trainTestPrint(classifier, DatasetLoading.sampleGunPoint(seed), seed);
}
public final static Configs<KNN> CONFIGS = buildConfigs().immutable();
public static Configs<KNN> buildConfigs() {
final Configs<KNN> configs = new Configs<>();
configs.add("1NN_ED", "Euclidean distance", KNN::new, knn -> {
knn.setTestTimeLimit(-1);
knn.setTrainTimeLimit(-1);
knn.setDistanceMeasure(new EDistance());
knn.setK(1);
knn.setAutoK(false);
knn.setEarlyPredict(false);
knn.setEarlyAbandonDistances(false);
knn.setNeighbourhoodSizeLimit(-1);
knn.setNeighbourhoodSizeLimitProportional(1d);
});
return configs;
}
private DistanceMeasure distanceMeasure;
private int k;
private TimeSeriesInstances trainData;
private List<Search> searches;
private List<Integer> remainingSearchIndices;
// will ensure loocv searches use at least this many neighbours. The limit may be exceeded if the distance measure
// is symmetric and neighbours are produced as a by product from other searches
private int neighbourhoodSizeLimit;
private double neighbourhoodSizeLimitProportional;
private int neighbourhoodSize;
private boolean earlyPredict;
private boolean earlyAbandonDistances;
private boolean autoK;
private int bestK;
// track the total run time of the build
private final StopWatch runTimer = new StopWatch();
// track the time to test an inst
private final StopWatch testTimer = new StopWatch();
// track the time to build the train estimate
private final StopWatch evaluationTimer = new StopWatch();
// the max amount of time taken to add a neighbour
private long longestAddNeighbourTime;
public static final String EARLY_PREDICT_FLAG = "p";
public static final String EARLY_ABANDON_DISTANCES_FLAG = "e";
public static final String NEIGHBOURHOOD_SIZE_LIMIT_FLAG = "n";
public static final String AUTO_K_FLAG = "a";
private final CheckpointConfig checkpointConfig = new CheckpointConfig();
private long trainTimeLimit = -1;
private long testTimeLimit = -1;
@Override public long getRunTime() {
return runTimer.elapsedTime();
}
@Override public long getTrainTime() {
return getRunTime() - getCheckpointingTime() - getTrainEstimateTime();
}
@Override public long getTrainEstimateTime() {
return evaluationTimer.elapsedTime();
}
@Override public CheckpointConfig getCheckpointConfig() {
return checkpointConfig;
}
public KNN() {
super(true);
CONFIGS.get("1NN_ED").configure(this);
}
@Override public ParamSet getParams() {
return super.getParams()
.add(DistanceMeasure.DISTANCE_MEASURE_FLAG, distanceMeasure)
.add(EARLY_ABANDON_DISTANCES_FLAG, earlyAbandonDistances)
.add(EARLY_PREDICT_FLAG, earlyPredict)
.add(NEIGHBOURHOOD_SIZE_LIMIT_FLAG, neighbourhoodSizeLimit)
.add(AUTO_K_FLAG, autoK);
}
@Override public void setParams(final ParamSet params) throws Exception {
super.setParams(params);
setDistanceMeasure(params.get(DistanceMeasure.DISTANCE_MEASURE_FLAG, distanceMeasure));
setEarlyAbandonDistances(params.get(EARLY_ABANDON_DISTANCES_FLAG, earlyAbandonDistances));
setEarlyPredict(params.get(EARLY_PREDICT_FLAG, earlyPredict));
setAutoK(params.get(AUTO_K_FLAG, autoK));
}
@Override public boolean isFullyBuilt() {
final boolean inside = neighbourhoodSize >= neighbourhoodSizeLimit;
final boolean inactive = neighbourhoodSizeLimit < 0;
final boolean insideProp = getNeighbourhoodSizeProportional() >= neighbourhoodSizeLimitProportional;
return !getEstimateOwnPerformance() || ((inside || inactive) && insideProp);
}
public int getNeighbourhoodSize() {
return neighbourhoodSize;
}
public double getNeighbourhoodSizeProportional() {
return (double) neighbourhoodSize / getMaxNeighbourhoodSize();
}
public boolean insideNeighbourhoodLimit() {
final boolean inside = neighbourhoodSize < neighbourhoodSizeLimit;
final boolean inactive = neighbourhoodSizeLimit < 0;
final boolean insideProp = (double) neighbourhoodSize / getMaxNeighbourhoodSize() < neighbourhoodSizeLimitProportional;
return (inactive || inside) && insideProp;
}
private int getMaxNeighbourhoodSize() {
final int numInstances = trainData.numInstances();
return numInstances * (numInstances - 1); // -1 because each left out inst cannot be a neighbour for itself
}
@Override public boolean withinTrainContract(final long time) {
return ContractedTrain.super.withinTrainContract(time);
}
private List<List<Integer>> neighbourIndicesByClass(int instIndex) {
// break the neighbours into classes
final List<List<Integer>> neighboursByClass = new ArrayList<>();
for(int i = 0; i < trainData.numClasses(); i++) {
neighboursByClass.add(new UnorderedArrayList<>());
}
for(int i = 0; i < trainData.numInstances(); i++) {
// if inst is in the neighbours data then skip it
if(i != instIndex) {
final int labelIndex = trainData.get(i).getLabelIndex();
neighboursByClass.get(labelIndex).add(i);
}
}
return neighboursByClass;
}
@Override public void buildClassifier(final TimeSeriesInstances data) throws Exception {
final long timeStamp = System.nanoTime();
runTimer.start(timeStamp);
if(isRebuild()) {
// attempt to load from a checkpoint
if(loadCheckpoint()) {
// internals of this object have been changed, so the run timer needs restarting
runTimer.start(timeStamp); // start from same time point though, no time missed while dealing with chkp
} else {
// failed to load checkpoint, so initialise classifier from scratch
super.buildClassifier(data);
neighbourhoodSize = 0;
trainData = data;
longestAddNeighbourTime = 0;
runTimer.reset();
runTimer.start(timeStamp);
evaluationTimer.reset();
checkpointConfig.resetCheckpointingTime();
if(getEstimateOwnPerformance()) {
evaluationTimer.start();
// init the searches for loocv
searches = new ArrayList<>();
remainingSearchIndices = new UnorderedArrayList<>();
// build a search per left out inst
for(int i = 0; i < data.numInstances(); i++) {
final Search search = new Search(i);
searches.add(search);
if(search.hasNext()) {
remainingSearchIndices.add(i);
}
}
evaluationTimer.stop();
}
}
}
// set the last checkpoint time to now (as we've either loaded from a checkpoint, started from scratch or
// already had some work done, all of which should already be saved in a checkpoint)
checkpointConfig.setLastCheckpointRunTime(System.nanoTime());
if(getEstimateOwnPerformance()) {
estimatePerformance();
}
runTimer.stop();
// we do this after the timers have been stopped, etc, otherwise times are inaccurate
// this sets the classifier name / dataset name / timings / meta in the results
ResultUtils.setInfo(trainResults, this, trainData);
}
private void estimatePerformance() throws Exception {
evaluationTimer.start();
// if neighbourhood is empty, then set workDone to true to regenerate the (not yet made) train results
// otherwise, more neighbours must be added before the train results are regenerated
boolean workDone = neighbourhoodSize == 0;
// while there are remaining searches
while(!remainingSearchIndices.isEmpty() && insideNeighbourhoodLimit()
&& insideTrainTimeLimit(getRunTime() + longestAddNeighbourTime)) {
final long timeStamp = System.nanoTime();
workDone = true;
// note that due to a symmetric distance measure, the remaining neighbours / searches may not line up
// exactly with the neighbour count. This is because the distance counts for both neighbours (i.e. a-->b
// and b-->a). So the neighbour count gets incremented twice, but the unseen neighbours / remaining searches
// may not be updated until subsequent iterations of this loop - in which case they do a no-op and skip
// the neighbour as we've already seen it. So just bare in mind that even though there's remaining searches
// / unseen neighbours apparently remaining, they may have already been seen. The neighbourhoodSize is the
// ground truth
// randomly iterate over searches
final int remainingSearchIndex = RandomUtils.choiceIndex(remainingSearchIndices.size(), getRandom());
final int searchIndex = remainingSearchIndices.get(remainingSearchIndex);
final Search search = searches.get(searchIndex);
// add a neighbour to the search
search.next();
// remove the search if it has no more neighbours available
if(!search.hasNext()) {
remainingSearchIndices.remove(remainingSearchIndex);
}
// optionally update the longest time taken to add a neighbour to assist with contracting
longestAddNeighbourTime = Math.max(longestAddNeighbourTime, System.nanoTime() - timeStamp);
saveCheckpoint();
}
// when searches have been exhausted
if(remainingSearchIndices.isEmpty()) {
// sanity check all neighbours have been seen
if(getMaxNeighbourhoodSize() != neighbourhoodSize) {
throw new IllegalStateException("expected neighbourhood to be full: " + neighbourhoodSize + " != " + getMaxNeighbourhoodSize());
}
}
if(workDone) {
if(autoK) {
// take a backup of the searches as they are currently
final List<Search> searchesBackup = new ArrayList<>();
for(Search search : searches) {
searchesBackup.add(CopierUtils.deepCopy(search));
}
// loop through the searches, adjusted the k decrementally. Take best k and best score so far
generateTrainResults();
bestK = k;
double bestAcc = trainResults.getAcc();
for(int i = k - 1; i > 0; i--) {
for(Search search : searches) {
search.setK(i);
}
generateTrainResults();
final double acc = trainResults.getAcc();
if(acc >= bestAcc) {
bestK = i;
bestAcc = acc;
}
}
// restore the original searches and trim down to the optimum k
searches = searchesBackup;
for(Search search : searches) {
search.setK(bestK);
}
}
}
// if work done or train results have been cleared
if(workDone || trainResults.getPredClassVals() == null) {
generateTrainResults();
saveCheckpoint(true);
}
evaluationTimer.stop();
}
private void generateTrainResults() {
trainResults = new ClassifierResults();
for(int i = 0; i < trainData.numInstances(); i++) {
final Search search = searches.get(i);
final double[] distribution = search.predict();
final int prediction = CollectionUtils.bestIndex(ArrayUtilities.asList(distribution), getRandom());
final long time = search.getTime();
final TimeSeriesInstance instance = trainData.get(i);
trainResults.addPrediction(instance.getLabelIndex(), distribution, prediction, time, null);
}
}
@Override public double[] distributionForInstance(final TimeSeriesInstance testInst) throws Exception {
testTimer.resetAndStart();
final Search search = new Search(testInst);
if(autoK) {
search.setK(bestK);
}
long longestAddNeighbourTime = 0;
while(search.hasNext() && insideTestTimeLimit(getTestTime() + longestAddNeighbourTime)) {
final long timeStamp = System.nanoTime();
search.next();
longestAddNeighbourTime = Math.max(longestAddNeighbourTime, System.nanoTime() - timeStamp);
}
testTimer.stop();
return search.predict();
}
public DistanceMeasure getDistanceMeasure() {
return distanceMeasure;
}
public void setDistanceMeasure(final DistanceMeasure distanceMeasure) {
this.distanceMeasure = Objects.requireNonNull(distanceMeasure);
}
public int getK() {
return k;
}
public void setK(final int k) {
this.k = k;
}
public int getNeighbourhoodSizeLimit() {
return neighbourhoodSizeLimit;
}
public void setNeighbourhoodSizeLimit(final int neighbourhoodSizeLimit) {
this.neighbourhoodSizeLimit = neighbourhoodSizeLimit;
}
public boolean isEarlyPredict() {
return earlyPredict;
}
public void setEarlyPredict(final boolean earlyPredict) {
this.earlyPredict = earlyPredict;
}
public boolean earlyPredictActive() {
return k == 1 && earlyPredict;
}
public boolean isEarlyAbandonDistances() {
return earlyAbandonDistances;
}
public void setEarlyAbandonDistances(final boolean earlyAbandonDistances) {
this.earlyAbandonDistances = earlyAbandonDistances;
}
@Override public long getTrainTimeLimit() {
return trainTimeLimit;
}
@Override public void setTrainTimeLimit(final long trainTimeLimit) {
this.trainTimeLimit = trainTimeLimit;
}
@Override public long getTestTimeLimit() {
return testTimeLimit;
}
@Override public void setTestTimeLimit(final long testTimeLimit) {
this.testTimeLimit = testTimeLimit;
}
@Override public long getTestTime() {
return testTimer.elapsedTime();
}
public boolean isAutoK() {
return autoK;
}
public void setAutoK(final boolean autoK) {
this.autoK = autoK;
}
public double getNeighbourhoodSizeLimitProportional() {
return neighbourhoodSizeLimitProportional;
}
public void setNeighbourhoodSizeLimitProportional(final double neighbourhoodSizeLimitProportional) {
this.neighbourhoodSizeLimitProportional = Checks.requireUnitInterval(neighbourhoodSizeLimitProportional);
}
// class to search for the nearest neighbour for a given instance
private class Search implements Iterator<Neighbour>, Serializable {
public Search(final TimeSeriesInstance target) {
this(-1, target);
}
public Search(final int i) {
this(i, null);
}
private Search(final int i, final TimeSeriesInstance target) {
targetIndexInTrainData = i;
this.target = target;
if(target == null && (i < 0 || i > trainData.numInstances() - 1)) {
throw new IllegalStateException("target cannot be null and have invalid index in train data: " + targetIndexInTrainData);
}
unseenNeighbourIndicesByClass = neighbourIndicesByClass(targetIndexInTrainData);
for(int j = 0; j < trainData.numClasses(); j++) {
if(!unseenNeighbourIndicesByClass.get(j).isEmpty()) {
availableClassIndices.add(j);
}
}
nearestNeighbourIndices = PrunedMap.asc(k);
}
private final TimeSeriesInstance target;
private final int targetIndexInTrainData;
private double limit = Double.POSITIVE_INFINITY;
private final BitSet seenNeighbours = new BitSet(trainData.numInstances());
private final PrunedMap<Double, Integer> nearestNeighbourIndices;
private boolean updateDistribution = false;
private final double[] distribution = ArrayUtilities.uniformDistribution(trainData.numClasses());
private long time = 0;
private int size = 0;
private int homogeneousLabelIndex = -1;
private final List<List<Integer>> unseenNeighbourIndicesByClass;
private final List<Integer> availableClassIndices = new UnorderedArrayList<>();
public boolean isTargetInTrainData() {
return targetIndexInTrainData >= 0;
}
public TimeSeriesInstance getTarget() {
if(isTargetInTrainData()) {
return trainData.get(targetIndexInTrainData);
} else {
return target;
}
}
public void setK(int k) {
if(nearestNeighbourIndices.setLimit(k)) {
updateDistribution = true;
}
}
public int getUnseenCount() {
int count = trainData.numInstances();
if(isTargetInTrainData()) {
count--;
}
count -= size();
return count;
}
private int getNumUnavailableHomogeneousClasses() {
return homogeneousLabelIndex >= 0 ? 1 : 0;
}
@Override public boolean hasNext() {
// if there are active classes, then there remains unseen neighbours in those corresponding classes
return availableClassIndices.size() - getNumUnavailableHomogeneousClasses() > 0;
}
private boolean add(int neighbourIndexInTrainData, double distance) {
if(seenNeighbours.get(neighbourIndexInTrainData)) {
throw new IllegalStateException("already examined neighbour " + neighbourIndexInTrainData + " for inst " + targetIndexInTrainData);
}
final boolean nearest = nearestNeighbourIndices.add(distance, neighbourIndexInTrainData);
if(nearest) {
if(earlyAbandonDistances) {
// update the limit for early abandoning distances
this.limit = nearestNeighbourIndices.lastKey();
} // else leave limit at pos inf
updateDistribution = true;
}
// getLog().info("adding neighbour " + neighbourIndexInTrainData + " to search " + targetIndexInTrainData + ", distance " + distance + (nearest ? ", nearest neighbour" : ""));
seenNeighbours.set(neighbourIndexInTrainData, true);
size++; // we've examined another neighbour
neighbourhoodSize++;
return nearest;
}
@Override public Neighbour next() {
final long timeStamp = System.nanoTime();
// pick an active class index
int availableClassIndex = RandomUtils.choiceIndex(availableClassIndices.size() - getNumUnavailableHomogeneousClasses(), getRandom());
int classIndex = availableClassIndices.get(availableClassIndex);
if(classIndex == homogeneousLabelIndex) {
// pick again if hit the homogeneous class label index (i.e. if the nearest neighbours are all from the
// same class, look at neighbours from other classes to attempt to change the output of the knn
availableClassIndex++;
classIndex = availableClassIndices.get(availableClassIndex);
}
// pick a random neighbour from
final List<Integer> unseenNeighbourIndices = unseenNeighbourIndicesByClass.get(classIndex);
final Integer neighbourIndexInTrainData = RandomUtils.remove(unseenNeighbourIndices, getRandom());
if(unseenNeighbourIndices.isEmpty()) {
// no more insts from this class so make class inactive
availableClassIndices.remove(availableClassIndex);
}
// sanity checks
if(neighbourIndexInTrainData == targetIndexInTrainData) {
throw new IllegalArgumentException("cannot add itself as neighbour: " + neighbourIndexInTrainData);
}
final TimeSeriesInstance neighbour = trainData.get(neighbourIndexInTrainData);
final int labelIndex = neighbour.getLabelIndex();
if(labelIndex != classIndex) {
throw new IllegalStateException("class label mismatch");
}
// might have already seen the neighbour (because the distance measure is symmetric and distance was reused
// from adding us as a neighbour
// therefore just skip over this distance computation and adding of neighbours to the nearest neighbours
double distance = -1; // -1 indicates distance is invalid / cached from another search with symmetry
boolean nearest = false;
if(!seenNeighbours.get(neighbourIndexInTrainData)) {
final boolean symmetric = symmetricNeighbours();
double limit = this.limit;
Search altSearch = null;
if(symmetric) {
// this search is searching for the nearest neighbour for a train inst
// in this case, if the distance measure is symmetric we can add the target inst of this search as a
// neighbour to the corresponding neighbour search
altSearch = searches.get(neighbourIndexInTrainData);
// set the limit to the max of both, as we will reuse the distance in both searches to must adhere to
// the furthest distance in both searches respectively
limit = Math.max(this.limit, altSearch.getLimit());
}
// compute the distance to the neighbour
distance = distanceMeasure.distance(getTarget(), neighbour, limit);
nearest = add(neighbourIndexInTrainData, distance);
if(nearest && earlyPredict) {
// neighbour is one of k nearest
// update the early predict homogeneity of the nearest neighbours
if(!(isHomogeneousNearestNeighbours() && labelIndex == homogeneousLabelIndex)) {
// recalculate homogeneous-ness
boolean first = true;
for(Integer neighbourIndex : nearestNeighbourIndices.valuesList()) {
final int neighbourLabelIndex = trainData.get(neighbourIndex).getLabelIndex();
if(first) {
// haven't seen any neighbours at this point, so this first neighbour will indicate the
// potential homogeneous class
homogeneousLabelIndex = neighbourLabelIndex;
first = false;
} else if(neighbourLabelIndex != homogeneousLabelIndex) {
// looking at the second or later neighbour
homogeneousLabelIndex = -1;
break;
}
}
}
}
if(symmetric) {
// then we can add this target inst as a neighbour to the corresponding search for the neighbour
altSearch.add(targetIndexInTrainData, distance);
// note that we DO NOT remove the corresponding unseen neighbour index in the alt search. This is
// because we'd have to do a linear removal on a list
// so instead, at some point, the alt search will find the target inst as a neighbour. It will check
// the seen neighbours and find that it has already been handled and just skip over it.
// likewise, this doesn't update the active classes for the alt search for the same reasons
}
}
time += System.nanoTime() - timeStamp;
return new Neighbour(distance, neighbourIndexInTrainData, nearest);
}
public boolean symmetricNeighbours() {
// if the target is an inst in the train data AND distance measure is symmetric, we can reuse the distance
// and provide the target and distance as a precomputed neighbour to the corresponding alternative search
return targetIndexInTrainData >= 0 && distanceMeasure.isSymmetric();
}
public BitSet getSeenNeighbours() {
return seenNeighbours;
}
public int getHomogeneousLabelIndex() {
return homogeneousLabelIndex;
}
public boolean isHomogeneousNearestNeighbours() {
return homogeneousLabelIndex >= 0;
}
public double[] predict() {
if(updateDistribution) {
updateDistribution = false;
Arrays.fill(distribution, 0d);
// note that more than k neighbours may be held as the nearest neighbours if there are ties.
// it makes most sense to keep the ties. The ties should get the kth
final Double lastKey = nearestNeighbourIndices.lastKey();
for(Double distance : nearestNeighbourIndices.keySet()) {
final List<Integer> instIndices = nearestNeighbourIndices.get(distance);
final double weight;
if(distance.equals(lastKey)) {
// last list contains any tie breaks for the kth nearest neighbour
// give any ties equal share for the kth vote
weight = 1d / instIndices.size();
} else {
weight = 1d;
}
for(Integer i : instIndices) {
final TimeSeriesInstance nearestNeighbour = trainData.get(i);
distribution[nearestNeighbour.getLabelIndex()] += weight;
}
}
ArrayUtilities.normalise(distribution, true);
}
return distribution;
}
public int getTargetIndexInTrainData() {
return targetIndexInTrainData;
}
public int size() {
return size;
}
public double getLimit() {
return limit;
}
public long getTime() {
return time;
}
}
}
| 33,363 | 42.957839 | 186 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/knn/Neighbour.java | package tsml.classifiers.distance_based.knn;
public class Neighbour {
public Neighbour(final double distance, final int indexInTrainData, final boolean wasNearestNeighbour) {
this.distance = distance;
this.indexInTrainData = indexInTrainData;
this.wasNearestNeighbour = wasNearestNeighbour;
}
private final double distance;
private final int indexInTrainData;
private final boolean wasNearestNeighbour;
public double getDistance() {
return distance;
}
public int getIndexInTrainData() {
return indexInTrainData;
}
/**
* Is the neighbour a nearest neighbour? Note this is only valid at the time of adding the neighbour to the search.
* I.e. it may no longer be a nearest neighbour if more neighbours have been examined in the search.
* @return
*/
public boolean wasNearestNeighbour() {
return wasNearestNeighbour;
}
}
| 938 | 29.290323 | 119 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/Agent.java | package tsml.classifiers.distance_based.optimised;
import tsml.classifiers.distance_based.utils.system.logging.Loggable;
import tsml.classifiers.distance_based.utils.system.random.Randomised;
import tsml.data_containers.TimeSeriesInstances;
import weka.core.Randomizable;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
public interface Agent extends Iterator<Evaluation>, Serializable, Randomised, Loggable {
// build anything needing the train data
void buildAgent(TimeSeriesInstances trainData);
// called when an evaluation task has been completed, i.e. results have been populated in an evaluation
void feedback(Evaluation evaluations);
List<Evaluation> getBestEvaluations();
}
| 752 | 33.227273 | 107 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/BaseAgent.java | package tsml.classifiers.distance_based.optimised;
import tsml.classifiers.distance_based.utils.collections.pruned.PrunedMap;
import tsml.classifiers.distance_based.utils.system.logging.LogUtils;
import tsml.data_containers.TimeSeriesInstances;
import java.util.*;
import java.util.logging.Logger;
public abstract class BaseAgent implements Agent {
private transient Logger log = LogUtils.DEFAULT_LOG;
// guard to make sure evaluations are selected / evaluated / fedback in proper order (i.e. no way to accidentally evaluate the same evaluation twice)
private HashSet<Evaluation> pendingEvaluations;
private boolean exploit = false;
private boolean explore = false;
private int evaluationIdCount;
private int seed;
private Random random = null;
private List<Evaluation> evaluations;
@Override public Logger getLogger() {
return log;
}
@Override public void setLogger(final Logger logger) {
this.log = Objects.requireNonNull(logger);
}
protected List<Evaluation> getEvaluations() {
return evaluations;
}
@Override public List<Evaluation> getBestEvaluations() {
final PrunedMap<Double, Evaluation> prunedMap = PrunedMap.desc(1);
for(Evaluation evaluation : evaluations) {
prunedMap.add(evaluation.getScore(), evaluation);
}
return prunedMap.valuesList();
}
@Override public void setSeed(final int seed) {
this.seed = seed;
}
@Override public int getSeed() {
return seed;
}
@Override public void setRandom(final Random random) {
this.random = random;
}
@Override public Random getRandom() {
return random;
}
protected Evaluation buildEvaluation() {
return new Evaluation(evaluationIdCount++);
}
@Override public void buildAgent(final TimeSeriesInstances trainData) {
checkRandom();
evaluationIdCount = 0;
pendingEvaluations = new HashSet<>();
evaluations = new ArrayList<>();
}
protected boolean dropResultsOnFeedback() {
return true;
}
@Override public void feedback(final Evaluation evaluation) {
if(!pendingEvaluations.remove(evaluation)) {
throw new IllegalStateException("unexpected feedback received for evaluation " + evaluation.getId());
}
// discard classifier results in the evaluation to decrease memory footprint - note this requires them to be
// recomputed if needed at a later date for train estimate, etc
if(dropResultsOnFeedback()) {
// depends on how expensive these are to recompute, sub classes can turn this off at the expense of memory
evaluation.getResults().cleanPredictionInfo();
evaluation.setResults(null);
}
// update the evaluations set
// fill in any missing evaluations (although there shouldn't be any by the end, this is just if they get fed
// back in the wrong order)
for(int i = evaluations.size(); i <= evaluation.getId(); i++) {
evaluations.add(null);
}
evaluations.set(evaluation.getId(), evaluation);
}
public abstract boolean hasNextExplore();
public boolean hasNextExploit() {
return false;
}
protected Evaluation nextExploit() {
throw new UnsupportedOperationException();
}
protected abstract Evaluation nextExplore();
@Override public boolean hasNext() {
// either of two actions can be taken: exploit or explore. If neither, then we're done.
exploit = hasNextExploit();
explore = hasNextExplore();
return exploit || explore;
}
@Override public Evaluation next() {
if(!hasNext()) {
throw new IllegalStateException("hasNext false");
}
// work out whether exploring / exploiting
if(exploit && explore) {
// must pick between exploring or exploit
if(exploreOrExploit()) {
exploit = false;
} else {
explore = false;
}
}
final Evaluation evaluation;
if(explore) {
evaluation = nextExplore();
evaluation.setExplore();
} else if(exploit) {
evaluation = nextExploit();
evaluation.setExploit();
} else {
throw new IllegalStateException("both explore and exploit false");
}
if(!pendingEvaluations.add(evaluation)) {
throw new IllegalStateException("already waiting on evaluation " + evaluation.getId());
}
return evaluation;
}
/**
*
* @return true for explore, false for exploit
*/
protected boolean exploreOrExploit() {
return true; // by default always explore over exploit
}
}
| 4,915 | 31.130719 | 153 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/BaseParamAgent.java | package tsml.classifiers.distance_based.optimised;
import evaluation.evaluators.Evaluator;
import evaluation.storage.ClassifierResults;
import tsml.classifiers.TSClassifier;
import tsml.classifiers.distance_based.utils.classifiers.configs.Builder;
import tsml.classifiers.distance_based.utils.collections.params.ParamHandlerUtils;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.iteration.AbstractSearch;
import tsml.data_containers.TimeSeriesInstances;
import java.util.Objects;
public class BaseParamAgent extends BaseAgent implements ParamAgent {
public BaseParamAgent() {
}
private ParamSpaceBuilder paramSpaceBuilder;
private AbstractSearch search;
private Builder<? extends TSClassifier> classifierBuilder;
private Builder<? extends Evaluator> evaluatorBuilder;
private ResultsScorer scorer = ClassifierResults::getAcc;
@Override public void buildAgent(final TimeSeriesInstances trainData) {
super.buildAgent(trainData);
Objects.requireNonNull(paramSpaceBuilder);
Objects.requireNonNull(search);
Objects.requireNonNull(classifierBuilder);
Objects.requireNonNull(evaluatorBuilder);
final ParamSpace paramSpace = paramSpaceBuilder.build(trainData);
copyRandomTo(search);
search.buildSearch(paramSpace);
}
@Override public boolean hasNextExplore() {
return search.hasNext();
}
@Override protected Evaluation nextExplore() {
final ParamSet paramSet = search.next();
final TSClassifier classifier = classifierBuilder.build();
copySeedTo(classifier);
ParamHandlerUtils.setParams(classifier, paramSet);
final Evaluator evaluator = evaluatorBuilder.build();
copySeedTo(evaluator);
final Evaluation evaluation = buildEvaluation();
evaluation.setClassifier(classifier);
evaluation.setEvaluator(evaluator);
evaluation.setScorer(scorer);
return evaluation;
}
@Override public Builder<? extends TSClassifier> getClassifierBuilder() {
return classifierBuilder;
}
@Override public AbstractSearch getSearch() {
return search;
}
@Override public ParamSpaceBuilder getParamSpaceBuilder() {
return paramSpaceBuilder;
}
@Override public Builder<? extends Evaluator> getEvaluatorBuilder() {
return evaluatorBuilder;
}
@Override public void setParamSpaceBuilder(
final ParamSpaceBuilder paramSpaceBuilder) {
this.paramSpaceBuilder = paramSpaceBuilder;
}
@Override public void setSearch(final AbstractSearch search) {
this.search = search;
}
@Override public void setClassifierBuilder(
final Builder<? extends TSClassifier> classifierBuilder) {
this.classifierBuilder = classifierBuilder;
}
@Override public void setEvaluatorBuilder(
final Builder<? extends Evaluator> evaluatorBuilder) {
this.evaluatorBuilder = evaluatorBuilder;
}
public ResultsScorer getScorer() {
return scorer;
}
public void setScorer(final ResultsScorer scorer) {
this.scorer = scorer;
}
}
| 3,435 | 33.36 | 89 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/Evaluation.java | package tsml.classifiers.distance_based.optimised;
import evaluation.evaluators.Evaluator;
import evaluation.storage.ClassifierResults;
import tsml.classifiers.TSClassifier;
import weka.classifiers.Classifier;
import java.util.Objects;
public class Evaluation implements Comparable<Evaluation> {
public ClassifierResults getResults() {
return results;
}
public void setResults(final ClassifierResults results) {
this.results = results;
if(results != null) {
score = scorer.score(results);
}
}
public Evaluation(final int id) {
this.id = id;
setScorer(ClassifierResults::getAcc);
}
private TSClassifier classifier;
private Evaluator evaluator;
private ClassifierResults results;
private final int id;
private double score;
private ResultsScorer scorer;
private boolean explore = true;
public boolean isExploit() {
return !isExplore();
}
public void setExploit() {
explore = false;
}
public TSClassifier getClassifier() {
return classifier;
}
public int getId() {
return id;
}
@Override public boolean equals(final Object o) {
if(!(o instanceof Evaluation)) {
return false;
}
final Evaluation that = (Evaluation) o;
return that.id == id;
}
@Override public int hashCode() {
return id;
}
public Evaluator getEvaluator() {
return evaluator;
}
public void setClassifier(final TSClassifier classifier) {
this.classifier = Objects.requireNonNull(classifier);
}
public void setEvaluator(final Evaluator evaluator) {
this.evaluator = Objects.requireNonNull(evaluator);
}
public void setClassifier(Classifier classifier) {
setClassifier(TSClassifier.wrapClassifier(classifier));
}
@Override public String toString() {
return String.valueOf(id);
}
public String toStringVerbose() {
return (explore ? "explore" : "exploit") + " " + id + " ( " + classifier.toString() + " )" + " : " + score;
}
public ResultsScorer getScorer() {
return scorer;
}
public void setScorer(final ResultsScorer scorer) {
this.scorer = scorer;
}
public double getScore() {
return score;
}
public boolean isExplore() {
return explore;
}
public void setExplore() {
this.explore = explore;
}
@Override public int compareTo(final Evaluation evaluation) {
return Double.compare(score, evaluation.getScore());
}
}
| 2,660 | 22.758929 | 115 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/IterableBuild.java | package tsml.classifiers.distance_based.optimised;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ProgressiveBuild;
import tsml.data_containers.TimeSeriesInstances;
public interface IterableBuild extends ProgressiveBuild {
void beforeBuild() throws Exception;
boolean hasNextBuildStep() throws Exception;
void nextBuildStep() throws Exception;
void afterBuild() throws Exception;
@Override default boolean isFullyBuilt() {
try {
return !hasNextBuildStep();
} catch(Exception e) {
throw new IllegalStateException(e);
}
}
void setTrainData(TimeSeriesInstances trainData);
default void buildClassifier(TimeSeriesInstances trainData) throws Exception {
beforeBuild();
while(hasNextBuildStep()) {
nextBuildStep();
}
afterBuild();
}
}
| 921 | 25.342857 | 86 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/KnnAgent.java | package tsml.classifiers.distance_based.optimised;
import evaluation.evaluators.Evaluator;
import evaluation.evaluators.InternalEstimateEvaluator;
import tsml.classifiers.TSClassifier;
import tsml.classifiers.distance_based.distances.dtw.spaces.DTWDistanceSpace;
import tsml.classifiers.distance_based.knn.KNN;
import tsml.classifiers.distance_based.utils.classifiers.configs.Builder;
import tsml.classifiers.distance_based.utils.classifiers.configs.ClassifierBuilder;
import tsml.classifiers.distance_based.utils.collections.checks.Checks;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.iteration.AbstractSearch;
import tsml.classifiers.distance_based.utils.collections.params.iteration.GridSearch;
import tsml.classifiers.distance_based.utils.collections.patience.Patience;
import tsml.data_containers.TimeSeriesInstances;
import java.util.*;
public class KnnAgent extends BaseAgent {
public KnnAgent() {
setNeighbourhoodSizeLimitProportional(1);
setParamSpaceBuilder(new DTWDistanceSpace());
setSearch(new GridSearch());
setEvaluatorBuilder(InternalEstimateEvaluator::new);
paramAgent.setClassifierBuilder((ClassifierBuilder<TSClassifier>) () -> {
final KNN classifier = new KNN();
classifier.setNeighbourhoodSizeLimit(neighbourhoodSize);
classifier.setSeed(getSeed());
return classifier;
});
}
private double neighbourhoodSizeLimitProportional;
private final BaseParamAgent paramAgent = new BaseParamAgent();
private List<Evaluation> exploits;
private List<Evaluation> nextExploits;
private int maxNumParamSets;
private int maxNeighbourhoodSize;
private int neighbourhoodSize;
private boolean usePatience;
// the patience mechanisms for exploring / exploiting (may have different windows, etc, based on sensitivity)
private final Patience explorePatience = new Patience(10);
private final Patience exploitPatience = new Patience(100);
private double bestExploitScore;
private int exploitExpireCount;
private int exploreExpireCount;
private boolean exploreImprovement;
private boolean exploitImprovement;
private boolean explore;
private final int expireCountThreshold = 2;
public boolean isUsePatience() {
return usePatience;
}
public void setUsePatience(final boolean usePatience) {
this.usePatience = usePatience;
}
private boolean exploreOrExploitByPatience() {
return explore;
}
private boolean exploreOrExploitByThreshold() {
// need size of param space
// need max neighbourhood size
// then compare count of explores / exploits against limits
// if less than 10% of param sets have been explored
if(getEvaluations().size() < maxNumParamSets / 10) {
// then explore more param sets
return true;
}
// if less than 10% of neighbours have been looked at
if(neighbourhoodSize < maxNeighbourhoodSize / 10) {
// then exploit more neighbours
return false;
}
// if less than 50% of param sets have been explored
if(getEvaluations().size() < maxNumParamSets / 2) {
// then explore more param sets
return true;
}
// if less than 50% of neighbours have been looked at
if(neighbourhoodSize < maxNeighbourhoodSize / 2) {
// then exploit more neighbours
return false;
}
// if less than 100% of param sets have been explored
if(getEvaluations().size() < maxNumParamSets) {
// then explore more param sets
return true;
}
// if less than 100% of neighbours have been looked at
if(neighbourhoodSize < maxNeighbourhoodSize) {
// then exploit more neighbours
return false;
}
throw new IllegalStateException("neighbours and param sets maxed out already");
}
@Override protected boolean exploreOrExploit() {
if(usePatience) {
return exploreOrExploitByPatience();
} else {
return exploreOrExploitByThreshold();
}
}
@Override public void buildAgent(final TimeSeriesInstances trainData) {
super.buildAgent(trainData);
copyRandomTo(paramAgent);
paramAgent.buildAgent(trainData);
exploits = new LinkedList<>();
nextExploits = new LinkedList<>();
maxNumParamSets = paramAgent.getSearch().size();
maxNeighbourhoodSize = trainData.numInstances();
neighbourhoodSize = 1;
if(usePatience) {
exploitPatience.reset();
explorePatience.reset();
explorePatience.add(0);
exploitPatience.add(0);
bestExploitScore = 0;
exploitImprovement = false;
exploreImprovement = false;
exploreExpireCount = 0;
exploitExpireCount = 0;
explore = true;
}
}
@Override public void feedback(final Evaluation evaluation) {
super.feedback(evaluation);
if(!getClassifier(evaluation).isFullyBuilt()) {
// can add more neighbours to improve the evaluation
nextExploits.add(evaluation);
}
if(usePatience) {
if(evaluation.isExplore() != explore) throw new IllegalStateException("received different type of evaluation than expected");
if(evaluation.isExplore()) {
exploreImprovement |= explorePatience.add(evaluation.getScore());
if(explorePatience.isExpired()) {
exploitPatience.reset();
exploitPatience.add(explorePatience.getBest());
exploitImprovement = false;
bestExploitScore = 0;
if(exploreImprovement) {
exploreExpireCount = 0;
exploitExpireCount = 0;
} else {
exploreExpireCount++;
}
explore = false;
}
} else {
bestExploitScore = Math.max(bestExploitScore, evaluation.getScore());
if(exploits.isEmpty()) {
exploitImprovement |= exploitPatience.add(bestExploitScore);
if(exploitPatience.isExpired()) {
explorePatience.reset();
explorePatience.add(exploitPatience.getBest());
exploreImprovement = false;
if(exploitImprovement) {
exploitExpireCount = 0;
exploreExpireCount = 0;
} else {
exploitExpireCount++;
}
explore = true;
}
}
}
}
}
@Override public boolean hasNextExploit() {
return !(exploits.isEmpty() && nextExploits.isEmpty()) && exploitExpireCount < expireCountThreshold;
}
@Override protected Evaluation nextExploit() {
if(exploits.isEmpty()) {
exploits = nextExploits;
nextExploits = new LinkedList<>();
}
final Evaluation evaluation = exploits.remove(0);
evaluation.setResults(null); // clear the results (do not clear the score!)
final KNN classifier = getClassifier(evaluation);
int prevNeighbourhoodSize = classifier.getNeighbourhoodSize();
// if the distance measure is symmetric then there's a 2 for the price of 1 on the neighbours
final int increase = classifier.getDistanceMeasure().isSymmetric() ? 2 : 1;
neighbourhoodSize = prevNeighbourhoodSize + increase;
if(prevNeighbourhoodSize > neighbourhoodSize) {
throw new IllegalStateException("neighbourhood size mismatch");
}
classifier.setNeighbourhoodSizeLimit(this.neighbourhoodSize);
classifier.setRebuild(false); // stop the classifier from rebuilding from scratch (i.e. carry on from where it left off)
return evaluation;
}
private KNN getClassifier(Evaluation evaluation) {
final TSClassifier classifier = evaluation.getClassifier();
if(!(classifier instanceof KNN)) {
throw new IllegalStateException("expected knn");
}
return (KNN) classifier;
}
public boolean hasNextExploreParamSet() {
return paramAgent.hasNextExplore();
}
@Override public boolean hasNextExplore() {
return hasNextExploreParamSet() && exploreExpireCount < expireCountThreshold;
}
@Override protected Evaluation nextExplore() {
return paramAgent.nextExplore();
}
public double getNeighbourhoodSizeLimitProportional() {
return neighbourhoodSizeLimitProportional;
}
public void setNeighbourhoodSizeLimitProportional(final double neighbourhoodSizeLimitProportional) {
this.neighbourhoodSizeLimitProportional = Checks.requireUnitInterval(neighbourhoodSizeLimitProportional);
}
public AbstractSearch getSearch() {
return paramAgent.getSearch();
}
public ParamSpaceBuilder getParamSpaceBuilder() {
return paramAgent.getParamSpaceBuilder();
}
public void setParamSpaceBuilder(
final ParamSpaceBuilder paramSpaceBuilder) {
paramAgent.setParamSpaceBuilder(paramSpaceBuilder);
}
public void setSearch(final AbstractSearch search) {
paramAgent.setSearch(search);
}
public Builder<? extends Evaluator> getEvaluatorBuilder() {
return paramAgent.getEvaluatorBuilder();
}
public void setEvaluatorBuilder(Builder<? extends Evaluator> builder) {
paramAgent.setEvaluatorBuilder(builder);
}
public ResultsScorer getScorer() {
return paramAgent.getScorer();
}
public void setScorer(final ResultsScorer scorer) {
paramAgent.setScorer(scorer);
}
public Patience getExploitPatience() {
return exploitPatience;
}
public Patience getExplorePatience() {
return explorePatience;
}
}
| 10,381 | 36.615942 | 137 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/OptimisedClassifier.java | package tsml.classifiers.distance_based.optimised;
import evaluation.storage.ClassifierResults;
import experiments.data.DatasetLoading;
import tsml.classifiers.TSClassifier;
import tsml.classifiers.TestTimeContractable;
import tsml.classifiers.TrainEstimateTimeable;
import tsml.classifiers.distance_based.distances.dtw.spaces.DTWDistanceSpace;
import tsml.classifiers.distance_based.utils.classifiers.BaseClassifier;
import tsml.classifiers.distance_based.utils.classifiers.contracting.TimedTest;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.CheckpointConfig;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.Checkpointed;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTrain;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ProgressiveBuild;
import tsml.classifiers.distance_based.utils.classifiers.contracting.TimedTrain;
import tsml.classifiers.distance_based.utils.classifiers.results.ResultUtils;
import tsml.classifiers.distance_based.utils.collections.params.iteration.RandomSearch;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatchable;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatcher;
import tsml.classifiers.distance_based.utils.system.random.RandomUtils;
import tsml.classifiers.distance_based.utils.system.timing.StopWatch;
import tsml.data_containers.TimeSeriesInstance;
import tsml.data_containers.TimeSeriesInstances;
import utilities.ClassifierTools;
import weka.core.Instances;
import java.util.List;
import java.util.Objects;
public class OptimisedClassifier extends BaseClassifier implements Checkpointed, ProgressiveBuild, TimedTrain, TimedTest,
ContractedTrain, MemoryWatchable,
TrainEstimateTimeable, IterableBuild {
public static void main(String[] args) throws Exception {
final int seed = 0;
final OptimisedClassifier classifier = new OptimisedClassifier();
final KnnAgent agent = new KnnAgent();
// agent.setParamSpaceBuilder(new EDistanceSpace());
agent.setParamSpaceBuilder(new DTWDistanceSpace());
agent.setSearch(new RandomSearch());
agent.setUsePatience(true);
classifier.setAgent(agent);
final Instances[] instances = DatasetLoading.sampleGunPoint(seed);
// while(instances[0].size() > 5) {
// instances[0].remove(instances[0].size() - 1);
// }
ClassifierTools.trainTestPrint(classifier, instances, seed);
}
private Agent agent;
private Evaluation bestEvaluation;
private final CheckpointConfig checkpointConfig = new CheckpointConfig();
private final StopWatch runTimer = new StopWatch();
private final StopWatch testTimer = new StopWatch();
private final StopWatch trainEstimateTimer = new StopWatch();
private final MemoryWatcher memoryWatcher = new MemoryWatcher();
private long trainTimeLimit = -1;
private long testTimeLimit = -1;
private long longestEvaluationTime;
private TimeSeriesInstances trainData;
private boolean explore;
public boolean withinTrainContract(long time) {
return insideTrainTimeLimit(time);
}
public void setTrainData(TimeSeriesInstances trainData) {
this.trainData = Objects.requireNonNull(trainData);
}
@Override public boolean isFullyBuilt() {
return IterableBuild.super.isFullyBuilt();
}
@Override public void beforeBuild() throws Exception {
long timeStamp = System.nanoTime();
memoryWatcher.start();
checkpointConfig.setLogger(getLogger());
if(isRebuild()) {
// attempt to load from a checkpoint
if(loadCheckpoint()) {
memoryWatcher.start();
checkpointConfig.setLogger(getLogger());
} else {
super.buildClassifier(trainData);
if(agent == null) {
throw new IllegalStateException("agent must be set");
}
checkRandom();
copyRandomTo(agent);
agent.buildAgent(trainData);
longestEvaluationTime = 0;
runTimer.reset();
trainEstimateTimer.reset();
}
}
runTimer.start(timeStamp);
memoryWatcher.stop();
runTimer.stop();
}
@Override public boolean hasNextBuildStep() throws Exception {
// x2 on the longest eval time because we need an extra slot of eval time to recompute the results
// granted this means we end up re-evaluating the best classifier again, but a) some classifiers like knn bare
// little cost in doing this and b) it's better to do this than store all the results for every single
// evaluation and eat a million gigs of ram
return agent.hasNext() && insideTrainTimeLimit(getRunTime() + longestEvaluationTime * 2);
}
@Override public void nextBuildStep() throws Exception {
runTimer.start();
memoryWatcher.stop();
final long timeStamp = System.nanoTime();
final Evaluation evaluation = agent.next();
if(explore != evaluation.isExplore()) {
explore = !explore;
getLogger().info("----");
}
execute(evaluation, trainData);
agent.feedback(evaluation);
longestEvaluationTime = Math.max(longestEvaluationTime, System.nanoTime() - timeStamp);
memoryWatcher.stop();
runTimer.stop();
}
@Override public void afterBuild() throws Exception {
runTimer.start();
memoryWatcher.start();
final List<Evaluation> bestEvaluations = agent.getBestEvaluations();
bestEvaluation = RandomUtils.choice(bestEvaluations, getRandom());
// best evaluation may need results recalculating if they're dropped because of memory requirements
if(bestEvaluation.getResults() == null) {
getLogger().info("----");
getLogger().info("recomputing evaluation for best");
execute(bestEvaluation, trainData);
}
trainResults = bestEvaluation.getResults();
memoryWatcher.stop();
runTimer.stop();
// we do this after the timers have been stopped, etc, otherwise times are inaccurate
// this sets the classifier name / dataset name / timings / meta in the results
ResultUtils.setInfo(trainResults, this, trainData);
}
private void execute(Evaluation evaluation, TimeSeriesInstances trainData) throws Exception {
trainEstimateTimer.start();
final TSClassifier classifier = evaluation.getClassifier();
final ClassifierResults results = evaluation.getEvaluator().evaluate(classifier, trainData);
evaluation.setResults(results);
getLogger().info(evaluation::toStringVerbose);
trainEstimateTimer.stop();
}
@Override public double[] distributionForInstance(final TimeSeriesInstance inst) throws Exception {
testTimer.resetAndStart();
final TSClassifier classifier = bestEvaluation.getClassifier();
if(classifier instanceof TestTimeContractable) {
((TestTimeContractable) classifier).setTestTimeLimit(testTimeLimit);
}
final double[] distribution = classifier.distributionForInstance(inst);
testTimer.stop();
return distribution;
}
public Agent getAgent() {
return agent;
}
public void setAgent(final Agent agent) {
this.agent = agent;
}
public CheckpointConfig getCheckpointConfig() {
return checkpointConfig;
}
@Override public long getTrainTime() {
return getRunTime() - getCheckpointingTime() - getTrainEstimateTime();
}
@Override public long getTrainEstimateTime() {
return trainEstimateTimer.elapsedTime();
}
@Override public long getRunTime() {
return runTimer.elapsedTime();
}
@Override public long getTestTime() {
return testTimer.elapsedTime();
}
public long getTestTimeLimit() {
return testTimeLimit;
}
public void setTestTimeLimit(final long testTimeLimit) {
this.testTimeLimit = testTimeLimit;
}
@Override public long getTrainTimeLimit() {
return trainTimeLimit;
}
@Override public void setTrainTimeLimit(final long trainTimeLimit) {
this.trainTimeLimit = trainTimeLimit;
}
@Override public long getMaxMemoryUsage() {
return memoryWatcher.getMaxMemoryUsage();
}
}
| 8,730 | 38.506787 | 121 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/ParamAgent.java | package tsml.classifiers.distance_based.optimised;
import evaluation.evaluators.Evaluator;
import tsml.classifiers.TSClassifier;
import tsml.classifiers.distance_based.utils.classifiers.configs.Builder;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.iteration.AbstractSearch;
public interface ParamAgent extends Agent {
Builder<? extends TSClassifier> getClassifierBuilder();
AbstractSearch getSearch();
ParamSpaceBuilder getParamSpaceBuilder();
Builder<? extends Evaluator> getEvaluatorBuilder();
void setParamSpaceBuilder(
final ParamSpaceBuilder paramSpaceBuilder);
void setSearch(final AbstractSearch search);
void setClassifierBuilder(
final Builder<? extends TSClassifier> classifierBuilder);
void setEvaluatorBuilder(
final Builder<? extends Evaluator> evaluatorBuilder);
}
| 959 | 31 | 89 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/optimised/ResultsScorer.java | package tsml.classifiers.distance_based.optimised;
import evaluation.storage.ClassifierResults;
import java.io.Serializable;
public interface ResultsScorer extends Serializable {
double score(ClassifierResults results);
}
| 234 | 20.363636 | 53 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/HConcatenator.java | package tsml.classifiers.distance_based.proximity;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import tsml.transformers.Transformer;
import weka.core.Instances;
import java.util.*;
public class HConcatenator implements Transformer {
public HConcatenator() {
}
@Override public Instances determineOutputFormat(final Instances data) throws IllegalArgumentException {
return data;
}
@Override public TimeSeriesInstance transform(final TimeSeriesInstance inst) {
final List<Double> values = new ArrayList<>();
for(TimeSeries series : inst) {
for(Double value : series) {
values.add(value);
}
}
return new TimeSeriesInstance(Collections.singletonList(values), inst.getLabelIndex());
}
@Override public String toString() {
return "HC";
}
}
| 922 | 26.147059 | 108 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/HConcatenatorTest.java | package tsml.classifiers.distance_based.proximity;
import org.junit.Assert;
import org.junit.Test;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
public class HConcatenatorTest {
@Test
public void test() {
final HConcatenator t = new HConcatenator();
final TimeSeries a = new TimeSeries(new double[]{1, 2, 3, 4, 5});
final TimeSeries b = new TimeSeries(new double[]{6, 7, 8, 9, 10});
final TimeSeriesInstance inst = new TimeSeriesInstance(1, Arrays.asList(a, b));
final TimeSeriesInstance other = t.transform(inst);
Assert.assertEquals(1, other.getNumDimensions());
Assert.assertArrayEquals(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, other.get(0).toValueArray(), 0d);
}
}
| 813 | 34.391304 | 112 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/HReorderer.java | package tsml.classifiers.distance_based.proximity;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import tsml.transformers.Transformer;
import weka.core.Instances;
import java.util.ArrayList;
import java.util.List;
public class HReorderer implements Transformer {
public HReorderer() {
}
private List<Integer> indices;
@Override public Instances determineOutputFormat(final Instances data) throws IllegalArgumentException {
return data;
}
@Override public TimeSeriesInstance transform(final TimeSeriesInstance inst) {
if(indices == null) {
return inst;
}
if(indices.size() != inst.getNumDimensions()) {
throw new IllegalArgumentException("inst contains " + inst.getNumDimensions() + " dims, only configured to reorder " + indices.size() + " dims");
}
return inst.getHSlice(indices);
}
public List<Integer> getIndices() {
return indices;
}
public void setIndices(final List<Integer> indices) {
this.indices = indices;
}
}
| 1,133 | 26 | 157 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/HReordererTest.java | package tsml.classifiers.distance_based.proximity;
import org.junit.Assert;
import org.junit.Test;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
public class HReordererTest {
@Test
public void test() {
final HReorderer t = new HReorderer();
final TimeSeries a = new TimeSeries(new double[]{1, 2, 3, 4, 5});
final TimeSeries b = new TimeSeries(new double[]{6, 7, 8, 9, 10});
t.setIndices(Arrays.asList(1, 0));
final TimeSeriesInstance inst = new TimeSeriesInstance(1, Arrays.asList(a, b));
final TimeSeriesInstance other = t.transform(inst);
Assert.assertEquals(2, other.getNumDimensions());
Assert.assertEquals(inst.get(0), other.get(1));
Assert.assertEquals(inst.get(1), other.get(0));
}
}
| 846 | 32.88 | 87 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/HSlicer.java | package tsml.classifiers.distance_based.proximity;
import tsml.data_containers.TimeSeriesInstance;
import tsml.transformers.Transformer;
import weka.core.Instances;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class HSlicer implements Transformer {
public HSlicer() {
this(Collections.emptyList());
}
public HSlicer(List<Integer> indices) {
setIndices(indices);
}
private List<Integer> indices;
@Override public Instances determineOutputFormat(final Instances data) throws IllegalArgumentException {
return data;
}
@Override public TimeSeriesInstance transform(final TimeSeriesInstance inst) {
return inst.getHSlice(indices);
}
public List<Integer> getIndices() {
return indices;
}
public void setIndices(final List<Integer> indices) {
this.indices = Objects.requireNonNull(indices);
}
@Override public String toString() {
return "H" + indices.toString();
}
}
| 1,044 | 23.302326 | 108 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/HSlicerTest.java | package tsml.classifiers.distance_based.proximity;
import org.junit.Assert;
import org.junit.Test;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
public class HSlicerTest {
@Test
public void test() {
final HSlicer hSlicer = new HSlicer();
hSlicer.setIndices(Arrays.asList(1));
final TimeSeries a = new TimeSeries(new double[]{1, 2, 3, 4, 5});
final TimeSeries b = new TimeSeries(new double[]{6, 7, 8, 9, 10});
final TimeSeriesInstance inst = new TimeSeriesInstance(1, Arrays.asList(a, b));
final TimeSeriesInstance other = hSlicer.transform(inst);
Assert.assertEquals(1, other.getNumDimensions());
Assert.assertEquals(b, other.get(0));
}
}
| 790 | 31.958333 | 87 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/ProximityForest.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.classifiers.distance_based.proximity;
import evaluation.evaluators.CrossValidationEvaluator;
import evaluation.evaluators.Evaluator;
import evaluation.evaluators.OutOfBagEvaluator;
import evaluation.storage.ClassifierResults;
import experiments.data.DatasetLoading;
import tsml.classifiers.TrainEstimateTimeable;
import tsml.classifiers.distance_based.utils.classifiers.*;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.CheckpointConfig;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.Checkpointed;
import tsml.classifiers.distance_based.utils.classifiers.configs.Builder;
import tsml.classifiers.distance_based.utils.classifiers.configs.Config;
import tsml.classifiers.distance_based.utils.classifiers.configs.Configs;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTest;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTrain;
import tsml.classifiers.distance_based.utils.system.logging.LogUtils;
import tsml.classifiers.distance_based.utils.classifiers.results.ResultUtils;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatchable;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatcher;
import tsml.classifiers.distance_based.utils.system.timing.StopWatch;
import tsml.data_containers.TimeSeriesInstance;
import tsml.data_containers.TimeSeriesInstances;
import utilities.ClassifierTools;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static utilities.ArrayUtilities.*;
import static utilities.Utilities.argMax;
/**
* Proximity Forest
* <p>
* Contributors: goastler
*/
public class ProximityForest extends BaseClassifier implements ContractedTrain, ContractedTest, TrainEstimateTimeable,
Checkpointed, MemoryWatchable {
public static void main(String[] args) throws Exception {
//// Thread.sleep(10000);
for(int i = 0; i < 1; i++) {
int seed = i;
ProximityForest classifier = CONFIGS.get("PF_R5").build();
// classifier.setEstimateOwnPerformance(true);
// classifier.setEstimatorMethod("oob");
classifier.setSeed(seed);
// classifier.setNumTreeLimit(3);
// classifier.setCheckpointPath("checkpoints");
// classifier.setNumTreeLimit(14);
// classifier.setCheckpointPath("checkpoints/PF");
// classifier.setTrainTimeLimit(1, TimeUnit.SECONDS);
// classifier.setTrainTimeLimit(30, TimeUnit.SECONDS);
classifier.setLogLevel("all");
// classifier.setEstimateOwnPerformance(true);
// classifier.setTrainEstimateMethod("oob");
// classifier.setCheckpointPath("checkpoints");
// classifier.setCheckpointInterval(5, TimeUnit.SECONDS);
ClassifierTools
.trainTestPrint(classifier, DatasetLoading
.sampleDataset("/bench/phd/data/all_2019", "ItalyPowerDemand", seed), seed);
}
// Thread.sleep(10000);
// String root = "/bench/phd/experiments/";
// String expName = "pf_correctness";
// String expDir = root + "/" + expName + "/";
// String analysisName = "analysis_pf_v2_vs_pf_wrapped";
//
//
// MultipleEstimatorEvaluation mce = new MultipleEstimatorEvaluation(expDir, analysisName, 30);
//
// mce.setDatasets("/bench/phd/data/lists/uni_2015_pigless.txt");
// mce.readInClassifier("PF_R5", "mine", expDir + "v1/results/");
// mce.readInClassifier("ORIG_PF", "theirs", expDir + "wrapped/results/");
// mce.setTestResultsOnly(true);
// mce.setUseAllStatistics();
// mce.setIgnoreMissingResults(true);
// mce.setBuildMatlabDiagrams(true, true);
// mce.runComparison();
}
public static final Configs<ProximityForest> CONFIGS = buildConfigs().immutable();
public static Configs<ProximityForest> buildConfigs() {
final Configs<ProximityForest> configs = new Configs<>();
configs.add("PF_R1", "PF with 1 split per node", ProximityForest::new,
pf -> {
pf.setTrainTimeLimit(-1);
pf.setTestTimeLimit(-1);
pf.setTrainEstimateMethod("none");
pf.setEstimateOwnPerformance(false);
pf.setNumTreeLimit(100);
pf.setProximityTreeFactory(ProximityTree.CONFIGS.get("PT_R1"));
});
configs.add("PF_R5", "PF with 5 splits per node", "PF_R1", pf -> pf.setProximityTreeFactory(ProximityTree.CONFIGS.get("PT_R5")));
configs.add("PF_R10", "PF with 10 splits per node", "PF_R1", pf -> pf.setProximityTreeFactory(ProximityTree.CONFIGS.get("PT_R10")));
for(String method : Arrays.asList("OOB", "CV")) {
for(String name : Arrays.asList("PF_R1", "PF_R5", "PF_R10")) {
final Config<ProximityForest> conf = configs.get(name);
configs.add(name + "_" + method, method, conf, pf -> pf.setTrainEstimateMethod(method));
}
}
return configs;
}
public ProximityForest() {
super(CAN_ESTIMATE_OWN_PERFORMANCE);
CONFIGS.get("PF_R5").configure(this);
}
private static final long serialVersionUID = 1;
// the list of trees in this forest
private List<ProximityTree> trees;
private List<Evaluator> treeEvaluators;
private List<ClassifierResults> treeTrainResults;
// the number of trees
private int numTreeLimit;
// the train time limit / contract
private long trainTimeLimit;
// the test time limit / contract
private long testTimeLimit;
// how long this took to build. THIS INCLUDES THE TRAIN ESTIMATE!
private final StopWatch runTimer = new StopWatch();
// how long testing took
private final StopWatch testTimer = new StopWatch();
// watch for memory usage
private final MemoryWatcher memoryWatcher = new MemoryWatcher();
// the longest tree build time for predicting train time requirements
private long longestTrainStageTime;
// the method of setting the config of the trees
private Builder<ProximityTree> proximityTreeBuilder;
// checkpoint config
private final CheckpointConfig checkpointConfig = new CheckpointConfig();
// train estimate variables
private double[][] trainEstimateDistributions;
private final StopWatch evaluationTimer = new StopWatch();
private long[] trainEstimatePredictionTimes;
@Override public long getMaxMemoryUsage() {
return memoryWatcher.getMaxMemoryUsage();
}
@Override
public void buildClassifier(TimeSeriesInstances trainData) throws Exception {
// timings:
// train time tracks the time spent processing the algorithm. This should not be used for contracting.
// run time tracks the entire time spent processing, whether this is work towards the algorithm or otherwise (e.g. saving checkpoints to disk). This should be used for contracting.
// evaluation time tracks the time spent evaluating the quality of the classifier, i.e. producing an estimate of the train data error.
// checkpoint time tracks the time spent loading / saving the classifier to disk.
// record the start time
final long timeStamp = System.nanoTime();
memoryWatcher.start();
checkpointConfig.setLogger(getLogger());
// several scenarios for entering this method:
// 1) from scratch: isRebuild() is true
// 1a) checkpoint found and loaded, resume from wherever left off
// 1b) checkpoint not found, therefore initialise classifier and build from scratch
// 2) rebuild off, i.e. buildClassifier has been called before and already handled 1a or 1b. We can safely continue building from current state. This is often the case if a smaller contract has been executed (e.g. 1h), then the contract is extended (e.g. to 2h) and we enter into this method again. There is no need to reinitialise / discard current progress - simply continue on under new constraints.
if(isRebuild()) {
// case (1)
if(loadCheckpoint()) {
memoryWatcher.start();
checkpointConfig.setLogger(getLogger());
} else {
// case (1b)
memoryWatcher.reset();
// let super build anything necessary (will handle isRebuild accordingly in super class)
super.buildClassifier(trainData);
// if rebuilding
// then init vars
// build timer is already started so just clear any time already accrued from previous builds. I.e. keep the time stamp of when the timer was started, but clear any record of accumulated time
runTimer.reset();
// clear other timers entirely
evaluationTimer.reset();
checkpointConfig.resetCheckpointingTime();
// no constituents to start with
trees = new ArrayList<>();
treeEvaluators = new ArrayList<>();
treeTrainResults = new ArrayList<>();
// zero tree build time so the first tree build will always set the bar
longestTrainStageTime = 0;
// init the running train estimate variables if using OOB
if(estimateOwnPerformance && trainEstimateMethod.equals(TrainEstimateMethod.OOB)) {
trainEstimatePredictionTimes = new long[trainData.numInstances()];
trainEstimateDistributions = new double[trainData.numInstances()][trainData.numClasses()];
treeEvaluators = new ArrayList<>();
treeTrainResults = new ArrayList<>();
}
} // case (1a)
} // else case (2)
// update the run timer with the start time of this session
// as the runtimer has been overwritten with the one from the checkpoint (if loaded)
// or the classifier has been initialised from scratch / resumed and can just start from the timestamp
runTimer.start(timeStamp);
evaluationTimer.checkStopped();
LogUtils.logTimeContract(runTimer.elapsedTime(), trainTimeLimit, getLogger(), "train");
// whether work has been done in this call to buildClassifier
boolean workDone = false;
// maintain a timer for how long trees take to build
final StopWatch trainStageTimer = new StopWatch();
// while remaining time / more trees need to be built
if(estimateOwnPerformance && trainEstimateMethod.equals(TrainEstimateMethod.CV)) {
// if there's a train contract then need to spend half the time CV'ing
evaluationTimer.start();
getLogger().info("cross validating");
// copy over the same configuration as this instance
final ProximityForest pf = deepCopy();
// turn off train estimation otherwise infinite recursion!
pf.setEstimateOwnPerformance(false);
// reset the state of pf to build from scratch
pf.setRebuild(true);
pf.setLogger(getLogger());
// disable checkpointing on pf
pf.setCheckpointPath(null);
// evaluate pf using cross validation
final CrossValidationEvaluator cv = new CrossValidationEvaluator();
final int numFolds = 10;
cv.setNumFolds(numFolds);
cv.setCloneData(false);
cv.setSeed(getSeed());
cv.setSetClassMissing(false);
if(hasTrainTimeLimit()) {
// must set PF train contract. The total CV time should be half of the train contract. This must be divided by numFolds+1 for a per-fold train contract. Note the +1 is to account for testing, as numFold test batches will be used which is the same size as the data, i.e. equivalent to another fold. Adds a single nano on in case the contract divides up to zero time.
pf.setTrainTimeLimit(findRemainingTrainTime(runTimer.elapsedTime()) / 2 / (numFolds + 1) + 1);
}
// evaluate
trainResults = cv.evaluate(pf, trainData);
// stop timer and set meta info in results
evaluationTimer.stop();
LogUtils.logTimeContract(runTimer.elapsedTime(), trainTimeLimit, getLogger(), "train");
getLogger().info("cross validation finished, acc " + trainResults.getAcc());
}
while(
// there's remaining trees to be built
insideNumTreeLimit()
&&
// and there's remaining time left to build more trees
insideTrainTimeLimit(runTimer.elapsedTime() + longestTrainStageTime)
) {
// reset the tree build timer
trainStageTimer.resetAndStart();
// setup a new tree
final int treeIndex = trees.size();
final ProximityTree tree = proximityTreeBuilder.build();
final int treeSeed = rand.nextInt();
tree.setSeed(treeSeed);
// setup the constituent
trees.add(tree);
// estimate the performance of the tree
if(estimateOwnPerformance && trainEstimateMethod.equals(TrainEstimateMethod.OOB)) {
// the timer for contracting the estimate of train error
evaluationTimer.start();
// build train estimate based on method
final OutOfBagEvaluator oobe = new OutOfBagEvaluator();
oobe.setCloneClassifier(false);
oobe.setSeed(treeSeed);
treeEvaluators.add(oobe);
getLogger().info(() -> "oob evaluating tree " + treeIndex);
// evaluate the tree
final ClassifierResults treeEvaluationResults = oobe.evaluate(tree, trainData);
treeTrainResults.add(treeEvaluationResults);
// for each index in the test data of the oobe
final List<Integer> outOfBagTestDataIndices = oobe.getOutOfBagTestDataIndices();
// for each instance in the oobe test data, add the distribution and prediction time to the corresponding instance predictions in the train estimate results
for(int oobeIndex = 0; oobeIndex < outOfBagTestDataIndices.size(); oobeIndex++) {
final int trainDataIndex = outOfBagTestDataIndices.get(oobeIndex);
// get the corresponding distribution from the oobe results
double[] distribution = treeEvaluationResults.getProbabilityDistribution(oobeIndex);
distribution = vote(treeIndex, distribution);
// get the corresponding distribution from the train estimate distribution
// add tree's distribution for this instance onto the overall train estimate distribution for this instance
add(trainEstimateDistributions[trainDataIndex], distribution);
// add the prediction time from the oobe to the time for this instance in the train estimate
trainEstimatePredictionTimes[trainDataIndex] += treeEvaluationResults.getPredictionTime(oobeIndex);
}
treeEvaluationResults.setErrorEstimateMethod(getEstimatorMethod());
evaluationTimer.stop();
}
// build the tree if not producing train estimate OR rebuild after evaluation
getLogger().info(() -> "building tree " + treeIndex);
tree.setRebuild(true);
tree.buildClassifier(trainData);
// tree fully built
trainStageTimer.stop();
workDone = true;
// optional checkpoint
saveCheckpoint();
// update train timer
LogUtils.logTimeContract(runTimer.elapsedTime(), trainTimeLimit, getLogger(), "train");
// update longest tree build time
longestTrainStageTime = Math.max(longestTrainStageTime, trainStageTimer.elapsedTime());
}
// if work has been done towards estimating the train error via OOB
if(estimateOwnPerformance && workDone && trainEstimateMethod.equals(TrainEstimateMethod.OOB)) {
// must format the OOB errors into classifier results
evaluationTimer.start();
getLogger().info("finalising train estimate");
// add the final predictions into the results
for(int i = 0; i < trainData.numInstances(); i++) {
double[] distribution = trainEstimateDistributions[i];
// i.e. [71, 29] --> [0.71, 0.29]
// copies as to not alter the original distribution. This is helpful if more trees are added in the future to avoid having to denormalise
// set ignoreZeroSum to true to produce a uniform distribution if there is no evaluation of the instance (i.e. it never ended up in an out-of-bag test data set because too few trees were built, say)
distribution = normalise(copy(distribution), true);
// get the prediction, rand tie breaking if necessary
final double prediction = argMax(distribution, rand);
final double classValue = trainData.get(i).getLabelIndex();
trainResults.addPrediction(classValue, distribution, prediction, trainEstimatePredictionTimes[i], null);
}
evaluationTimer.stop();
}
// finish up
LogUtils.logTimeContract(runTimer.elapsedTime(), trainTimeLimit, getLogger(), "train");
// sanity check that all timers have been stopped
evaluationTimer.checkStopped();
testTimer.checkStopped();
memoryWatcher.stop();
runTimer.stop();
// save the final checkpoint
if(workDone) {
ResultUtils.setInfo(trainResults, this, trainData);
forceSaveCheckpoint();
}
}
@Override
public double[] distributionForInstance(final TimeSeriesInstance instance) throws Exception {
// start timer
testTimer.resetAndStart();
// track how long every stage (i.e. every tree prediction) takes, recording the longest
long longestTestStageTimeNanos = 0;
// time each stage of the prediction
final StopWatch testStageTimer = new StopWatch();
final double[] finalDistribution = new double[getNumClasses()];
// while there's remaining constituents to be examined and remaining test time
for(int i = 0;
i < trees.size()
&&
(testTimeLimit <= 0 || testTimer.elapsedTime() + longestTestStageTimeNanos < testTimeLimit)
; i++) {
testStageTimer.resetAndStart();
// let the constituent vote
final double[] distribution = vote(i, instance);
// add the vote to the total votes
add(finalDistribution, distribution);
// update timings
testStageTimer.stop();
longestTestStageTimeNanos = Math.max(longestTestStageTimeNanos, testStageTimer.elapsedTime());
}
// normalise the final vote, i.e. [71,29] --> [.71,.29]
normalise(finalDistribution);
// finished prediction so stop timer
testTimer.stop();
return finalDistribution;
}
private double[] vote(int constituentIndex, TimeSeriesInstance instance) throws Exception {
final ProximityTree tree = trees.get(constituentIndex);
final double[] distribution = tree.distributionForInstance(instance);
return vote(constituentIndex, distribution);
}
private double[] vote(int constituentIndex, double[] distribution) {
// vote for the highest probability class
final int index = argMax(distribution, getRandom());
return oneHot(distribution.length, index);
}
@Override public boolean isFullyBuilt() {
return trees != null && trees.size() == numTreeLimit;
}
public boolean insideNumTreeLimit() {
return !hasNumTreeLimit() || trees.size() < numTreeLimit;
}
public boolean hasNumTreeLimit() {
return numTreeLimit > 0;
}
public int getNumTreeLimit() {
return numTreeLimit;
}
public void setNumTreeLimit(final int numTreeLimit) {
this.numTreeLimit = numTreeLimit;
}
public Builder<ProximityTree> getProximityTreeFactory() {
return proximityTreeBuilder;
}
public void setProximityTreeFactory(final Builder<ProximityTree> proximityTreeBuilder) {
this.proximityTreeBuilder = Objects.requireNonNull(proximityTreeBuilder);
}
@Override public long getRunTime() {
return runTimer.elapsedTime();
}
@Override
public long getTrainTimeLimit() {
return trainTimeLimit;
}
/**
* Overriding TrainTimeContract methods
* @param nanos
*/
@Override
public void setTrainTimeLimit(final long nanos) {
trainTimeLimit = nanos;
}
public boolean withinTrainContract(long time) {
return insideTrainTimeLimit(time);
}
@Override
public long getTestTimeLimit() {
return testTimeLimit;
}
@Override
public void setTestTimeLimit(final long nanos) {
testTimeLimit = nanos;
}
@Override public long getTrainTime() {
// train time is the overall run time minus any time spent estimating the train error and minus any time spent checkpointing
return getRunTime() - getTrainEstimateTime() - getCheckpointingTime();
}
@Override public long getTrainEstimateTime() {
return evaluationTimer.elapsedTime();
}
@Override public long getTestTime() {
return testTimer.elapsedTime();
}
@Override public CheckpointConfig getCheckpointConfig() {
return checkpointConfig;
}
}
| 23,009 | 47.75 | 414 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/ProximityForestWrapper.java | /*
* Copyright (C) 2019 xmw13bzu
*
* 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.classifiers.distance_based.proximity;
import core.AppContext;
import core.contracts.Dataset;
import datasets.ListDataset;
import evaluation.MultipleEstimatorEvaluation;
import experiments.ExperimentalArguments;
import experiments.ClassifierExperiments;
import java.util.Random;
import trees.ProximityForest;
import tsml.classifiers.distance_based.utils.classifiers.configs.Configs;
import weka.classifiers.AbstractClassifier;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Randomizable;
/**
*
* An in-progress wrapper/conversion class for the java Proximity Forest implementation.
*
* The code as-is on the github page does not return distributions when predicting. Therefore
* in our version of the jar I have added a predict_proba() to be used here instead of predict().
* Existing proximity code is UNEDITED, and predict_proba simply returns the distribution of
* the num_votes class member instead of resolving ties internally and returning the single,
* majority voted for, class value. As such, metrics that do not consider probabilistic performance
* (accuracy, most importantly) should be identical when training and testing on identical data
* with identical seeds. The only part where this falls down is in tie resolution for
* the majority class, todo.
*
* tl;dr, performance on average should be significantly the same towards vanishing p values
*
* NOTE1: we are by-passing the test method which is ultimately foreach inst { predict() },
* and so proximity forest's internal results object is empty. This has no other sides effects for
* our purposes here.
*
* NOTE2: because of the static AppContext holding e.g random seeds etc, do not run multiple
* experiments using ProximityForest in parallel, i.e with ClassifierExperiments.setupAndRunMultipleExperimentsThreaded(...)
*
* TODO: weka/tsc interface implementations etc, currently this is simply in a runnable state
* for basic experimental runs to compare against. Need: TechnicalInformationHandler, need to do the get/setOptions,
* could do parameter searches if wanted, etcetc.
*
*
* Github code: https://github.com/fpetitjean/ProximityForestWeka
*
* @article{DBLP:journals/corr/abs-1808-10594,
* author = {Benjamin Lucas and
* Ahmed Shifaz and
* Charlotte Pelletier and
* Lachlan O'Neill and
* Nayyar A. Zaidi and
* Bart Goethals and
* Fran{\c{c}}ois Petitjean and
* Geoffrey I. Webb},
* title = {Proximity Forest: An effective and scalable distance-based classifier
* for time series},
* journal = {CoRR},
* volume = {abs/1808.10594},
* year = {2018},
* url = {http://arxiv.org/abs/1808.10594},
* archivePrefix = {arXiv},
* eprint = {1808.10594},
* timestamp = {Mon, 03 Sep 2018 13:36:40 +0200},
* biburl = {https://dblp.org/rec/bib/journals/corr/abs-1808-10594},
* bibsource = {dblp computer science bibliography, https://dblp.org}
* }
*
* @author James Large (james.large@uea.ac.uk)
*/
public class ProximityForestWrapper extends AbstractClassifier implements Randomizable {
public static final Configs<ProximityForestWrapper> CONFIGS = buildConfigs().immutable();
public static Configs<ProximityForestWrapper> buildConfigs() {
final Configs<ProximityForestWrapper> configs = new Configs<>();
configs.add("PF_WRAPPER_R1", "", ProximityForestWrapper::new, pfw -> pfw.setR(1));
configs.add("PF_WRAPPER_R5", "", ProximityForestWrapper::new, pfw -> pfw.setR(5));
configs.add("PF_WRAPPER_R10", "", ProximityForestWrapper::new, pfw -> pfw.setR(10));
configs.add("PF_WRAPPER", "PF_WRAPPER_R5");
return configs;
}
//from paper, pg18-19:
/*
4.2 ClassifierExperiments on the UCR Archive
...
The Proximity Forest results are obtained for 100 trees
with selection between 5 candidates per node. A detailed discussion about the
Proximity Forest parameters will be performed in Section 4.2
*/
private int num_trees = 100;
private int num_candidates_per_split = 5;
private boolean random_dm_per_node = true;
public ProximityForest pf;
private int numClasses;
private Instances header;
public ProximityForestWrapper() {
}
public void setR(int r) {
num_candidates_per_split = r;
}
public int getNum_trees() {
return num_trees;
}
public void setNum_trees(int num_trees) {
this.num_trees = num_trees;
}
public int getNum_candidates_per_split() {
return num_candidates_per_split;
}
public void setNum_candidates_per_split(int num_candidates_per_split) {
this.num_candidates_per_split = num_candidates_per_split;
}
public boolean isRandom_dm_per_node() {
return random_dm_per_node;
}
public void setRandom_dm_per_node(boolean random_dm_per_node) {
this.random_dm_per_node = random_dm_per_node;
}
public void setSeed(int seed) {
AppContext.rand_seed = seed;
AppContext.rand = new Random(seed);
}
public int getSeed() {
return (int)AppContext.rand_seed;
}
private Dataset toPFDataset(Instances insts) {
Dataset dset = new ListDataset(insts.numInstances());
for (Instance inst : insts)
dset.add((int)inst.classValue(), getSeries(inst));
return dset;
}
private double[] getSeries(Instance inst) {
double[] d = new double[inst.numAttributes()-1];
for (int i = 0; i < d.length; i++)
d[i] = inst.value(i);
return d;
}
@Override
public void buildClassifier(Instances data) throws Exception {
//init
numClasses = data.numClasses();
header = new Instances(data,0);
if (AppContext.rand == null) AppContext.rand = new Random(AppContext.rand_seed);
AppContext.num_trees = num_trees;
AppContext.num_candidates_per_split = num_candidates_per_split;
AppContext.random_dm_per_node = random_dm_per_node;
pf = new ProximityForest((int) AppContext.rand_seed); //just an id
//actual work
Dataset pfdata = toPFDataset(data);
pf.train(pfdata);
}
@Override
public double[] distributionForInstance(Instance inst) throws Exception {
// header.add(inst);
// Dataset dset = toPFDataset(header);
// header.remove(0);
//
// double[] dist = new double[inst.numClasses()];
// ProximityForestResult pfres = pf.test(dset);
//
return pf.predict_proba(getSeries(inst), numClasses);
}
@Override
public double classifyInstance(Instance inst) throws Exception {
double[] probs = distributionForInstance(inst);
int maxClass = 0;
for (int n = 1; n < probs.length; ++n) {
if (probs[n] > probs[maxClass]) {
maxClass = n;
}
else if (probs[n] == probs[maxClass]){
if (AppContext.rand.nextBoolean()){
maxClass = n;
}
}
}
return maxClass;
}
public static void main(String[] args) throws Exception {
// ProximityForestWrapper pf = new ProximityForestWrapper();
// pf.setSeed(0);
// System.out.println(ClassifierTools.testUtils_getIPDAcc(pf));
// System.out.println(ClassifierTools.testUtils_confirmIPDReproduction(pf, 0.966958211856171, "2019_09_26"));
ExperimentalArguments exp = new ExperimentalArguments();
exp.dataReadLocation = "Z:/Data/TSCProblems2015/";
exp.resultsWriteLocation = "C:/Temp/ProximityForestWekaTest/";
exp.estimatorName = "ProximityForest";
// exp.datasetName = "BeetleFly";
// exp.foldId = 0;
// ClassifierExperiments.setupAndRunExperiment(exp);
String[] classifiers = { "ProximityForest" };
String[] datasets = {
"Beef", // 30,30,470,5
"Car", // 60,60,577,4
"Coffee", // 28,28,286,2
"CricketX", // 390,390,300,12
"CricketY", // 390,390,300,12
"CricketZ", // 390,390,300,12
"DiatomSizeReduction", // 16,306,345,4
"fish", // 175,175,463,7
"GunPoint", // 50,150,150,2
"ItalyPowerDemand", // 67,1029,24,2
"MoteStrain", // 20,1252,84,2
"OliveOil", // 30,30,570,4
"Plane", // 105,105,144,7
"SonyAIBORobotSurface1", // 20,601,70,2
"SonyAIBORobotSurface2", // 27,953,65,2
"SyntheticControl", // 300,300,60,6
"Trace", // 100,100,275,4
"TwoLeadECG", // 23,1139,82,2
};
int numFolds = 30;
//Because of the static app context, best not run multithreaded, stick to single threaded
for (String dataset : datasets) {
for (int f = 0; f < numFolds; f++) {
exp.datasetName = dataset;
exp.foldId = f;
ClassifierExperiments.setupAndRunExperiment(exp);
}
}
MultipleEstimatorEvaluation mee = new MultipleEstimatorEvaluation(exp.resultsWriteLocation +"ANA/", "sanityCheck", numFolds);
mee.setBuildMatlabDiagrams(false);
mee.setTestResultsOnly(true);
mee.setDatasets(datasets);
mee.readInEstimator(exp.estimatorName, exp.resultsWriteLocation);
// mee.readInClassifier("DTWCV", "Z:/Results_7_2_19/FinalisedRepo/"); //no probs, leaving it
mee.readInEstimator("RotF", "Z:/Results_7_2_19/FinalisedRepo/");
mee.runComparison();
}
}
| 10,806 | 35.510135 | 133 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/ProximityTree.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.classifiers.distance_based.proximity;
import com.google.common.collect.Lists;
import experiments.data.DatasetLoading;
import org.junit.Assert;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.IndependentDistanceMeasure;
import tsml.classifiers.distance_based.distances.dtw.spaces.*;
import tsml.classifiers.distance_based.distances.ed.spaces.EDistanceSpace;
import tsml.classifiers.distance_based.distances.erp.spaces.ERPDistanceRestrictedContinuousSpace;
import tsml.classifiers.distance_based.distances.lcss.spaces.LCSSDistanceRestrictedContinuousSpace;
import tsml.classifiers.distance_based.distances.msm.spaces.MSMDistanceSpace;
import tsml.classifiers.distance_based.distances.transformed.TransformDistanceMeasure;
import tsml.classifiers.distance_based.distances.twed.spaces.TWEDistanceSpace;
import tsml.classifiers.distance_based.distances.wdtw.spaces.WDDTWDistanceContinuousSpace;
import tsml.classifiers.distance_based.distances.wdtw.spaces.WDTWDistanceContinuousSpace;
import tsml.classifiers.distance_based.utils.classifiers.configs.Configs;
import tsml.classifiers.distance_based.utils.collections.pruned.PrunedMap;
import tsml.classifiers.distance_based.utils.classifiers.*;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.CheckpointConfig;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.Checkpointed;
import tsml.classifiers.distance_based.utils.collections.lists.IndexList;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceBuilder;
import tsml.classifiers.distance_based.utils.collections.params.iteration.RandomSearch;
import tsml.classifiers.distance_based.utils.collections.tree.BaseTree;
import tsml.classifiers.distance_based.utils.collections.tree.BaseTreeNode;
import tsml.classifiers.distance_based.utils.collections.tree.Tree;
import tsml.classifiers.distance_based.utils.collections.tree.TreeNode;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTest;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTrain;
import tsml.classifiers.distance_based.utils.classifiers.results.ResultUtils;
import tsml.classifiers.distance_based.utils.stats.scoring.*;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
import tsml.classifiers.distance_based.utils.system.logging.LogUtils;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatchable;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatcher;
import tsml.classifiers.distance_based.utils.system.random.RandomUtils;
import tsml.classifiers.distance_based.utils.system.timing.StopWatch;
import tsml.data_containers.TimeSeriesInstance;
import tsml.data_containers.TimeSeriesInstances;
import tsml.transformers.CachedTransformer;
import tsml.transformers.Derivative;
import tsml.transformers.TransformPipeline;
import tsml.transformers.Transformer;
import utilities.ArrayUtilities;
import utilities.ClassifierTools;
import java.io.Serializable;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
import static tsml.classifiers.distance_based.utils.collections.checks.Checks.requireReal;
/**
* Proximity tree
* <p>
* Contributors: goastler
*/
public class ProximityTree extends BaseClassifier implements ContractedTest, ContractedTrain, Checkpointed, MemoryWatchable {
public static void main(String[] args) throws Exception {
// System.out.println(CONFIGS);
for(int i = 0; i < 1; i++) {
int seed = i;
ProximityTree classifier = CONFIGS.get("PT_R5").build();
classifier.setSeed(seed);
// classifier.setCheckpointDirPath("checkpoints");
classifier.setLogLevel(Level.ALL);
// classifier.setDebug(true);
// classifier.setDistanceMode(DistanceMode.DEPENDENT);
// classifier.setDimensionConversion(DimensionConversionMode.NONE);
// classifier.setDimensionSamplingMode(DimensionSamplingMode.ALL);
// classifier.setMultivariateMode(DimensionSamplingMode.CONCAT_TO_UNIVARIATE);
// classifier.setEarlyAbandonDistances(true);
// classifier.setEarlyExemplarCheck(true);
// classifier.setPartitionExaminationReordering(true);
// classifier.setTrainTimeLimit(10, TimeUnit.SECONDS);
// classifier.setCheckpointPath("checkpoints");
// classifier.setCheckpointInterval(10, TimeUnit.SECONDS);
// classifier.setTrainTimeLimit(5, TimeUnit.SECONDS);
ClassifierTools.trainTestPrint(classifier, DatasetLoading.sampleItalyPowerDemand(seed), seed);
}
}
public final static Configs<ProximityTree> CONFIGS = buildConfigs().immutable();
public static Configs<ProximityTree> buildConfigs() {
final Configs<ProximityTree> configs = new Configs<>();
configs.add("PT_R1", "Proximity tree with a single split per node", ProximityTree::new,
pt -> {
pt.setDistanceMeasureSpaceBuilders(Lists.newArrayList(
new EDistanceSpace(),
new DTWDistanceFullWindowSpace(),
new DTWDistanceRestrictedContinuousSpace(),
new DDTWDistanceFullWindowSpace(),
new DDTWDistanceRestrictedContinuousSpace(),
new WDTWDistanceContinuousSpace(),
new WDDTWDistanceContinuousSpace(),
new LCSSDistanceRestrictedContinuousSpace(),
new ERPDistanceRestrictedContinuousSpace(),
new TWEDistanceSpace(),
new MSMDistanceSpace()
));
pt.setSplitScorer(new GiniEntropy());
pt.setR(1);
pt.setTrainTimeLimit(-1);
pt.setTestTimeLimit(-1);
pt.setBreadthFirst(false);
pt.setPartitionExaminationReordering(false);
pt.setEarlyExemplarCheck(false);
pt.setEarlyAbandonDistances(false);
pt.setDimensionConversion(DimensionConversionMode.NONE);
pt.setDistanceMode(DistanceMode.DEPENDENT);
pt.setDimensionSamplingMode(DimensionSamplingMode.SINGLE);
pt.setCacheTransforms(false);
});
configs.add("PT_R5", "5 random splits per node", "PT_R1", pt -> pt.setR(5));
configs.add("PT_R10", "10 random splits per node", "PT_R1", pt -> pt.setR(10));
for(DimensionSamplingMode samplingMode : DimensionSamplingMode.values()) {
for(DimensionConversionMode conversionMode : DimensionConversionMode.values()) {
for(DistanceMode distanceMode : DistanceMode.values()) {
String base = "PT_R5";
String name = base
+ "_" + (samplingMode.equals(DimensionSamplingMode.SINGLE) ? '1' :
samplingMode.name().charAt(0))
+ "_" + StrUtils.join("", Arrays.stream(conversionMode.name().split("_")).map(s -> s.substring(0, 1)).toArray(String[]::new))
+ "_" + distanceMode.name().charAt(0);
configs.add(name, "", "PT_R5", pt -> {
pt.setDimensionSamplingMode(samplingMode);
pt.setDimensionConversion(conversionMode);
pt.setDistanceMode(distanceMode);
});
}
}
}
return configs;
}
public ProximityTree() {
CONFIGS.get("PT_R1").configure(this);
}
private static final long serialVersionUID = 1;
// train timer
private final StopWatch runTimer = new StopWatch();
// test / predict timer
private final StopWatch testTimer = new StopWatch();
// method of tracking memory
private final MemoryWatcher memoryWatcher = new MemoryWatcher();
// the tree of splits
private Tree<Split> tree;
// the train time limit / contract
private long trainTimeLimit;
// the test time limit / contract
private long testTimeLimit;
// the longest time taken to build a node / split
private long longestTrainStageTime;
// the queue of nodes left to build
private Deque<TreeNode<Split>> nodeBuildQueue;
// the list of distance function space builders to produce distance functions in splits
private List<ParamSpaceBuilder> distanceMeasureSpaceBuilders;
// the number of splits to consider for this split
private int r;
// a method of scoring the split of data into partitions
private SplitScorer splitScorer;
// checkpoint config
private final CheckpointConfig checkpointConfig = new CheckpointConfig();
// whether to build the tree depth first or breadth first
private boolean breadthFirst = false;
// whether to use early abandon in the distance computations
private boolean earlyAbandonDistances;
// whether to use a quick check for exemplars
private boolean earlyExemplarCheck;
// enhanced early abandon distance computation via ordering partition examination to hit the most likely closest exemplar sooner
private boolean partitionExaminationReordering;
// cache certain transformers to avoid repetition
private Map<Transformer, CachedTransformer> transformerCache;
public DistanceMode getDistanceMode() {
return distanceMode;
}
public boolean withinTrainContract(long time) {
return insideTrainTimeLimit(time);
}
public void setDistanceMode(
final DistanceMode distanceMode) {
this.distanceMode = Objects.requireNonNull(distanceMode);
}
public DimensionConversionMode getDimensionConversion() {
return dimensionConversionMode;
}
public void setDimensionConversion(
final DimensionConversionMode dimensionConversionMode) {
this.dimensionConversionMode = Objects.requireNonNull(dimensionConversionMode);
}
// what strategy to use for handling multivariate data
private DimensionSamplingMode dimensionSamplingMode;
// multivariate conversion mode to convert multivariate data into an alternate form
private DimensionConversionMode dimensionConversionMode;
// multivariate distance can be interpreted as several isolated univariate pairings or delegated to the distance measure to manage
private DistanceMode distanceMode;
public DimensionSamplingMode getDimensionSamplingMode() {
return dimensionSamplingMode;
}
public void setDimensionSamplingMode(
final DimensionSamplingMode dimensionSamplingMode) {
this.dimensionSamplingMode = Objects.requireNonNull(dimensionSamplingMode);
}
public CheckpointConfig getCheckpointConfig() {
return checkpointConfig;
}
public boolean isCacheTransforms() {
return transformerCache != null;
}
public void setCacheTransforms(final boolean cacheTransforms) {
if(cacheTransforms) {
transformerCache = new HashMap<>();
} else {
transformerCache = null;
}
}
/**
* Set the cache to an external cache
* @param cache
*/
public void setCacheTransforms(final Map<Transformer, CachedTransformer> cache) {
transformerCache = cache;
}
public enum DimensionSamplingMode {
SINGLE, // randomly pick a single dimension, discarding others
SUBSET, // randomly pick a subset of dimensions (between 1 and all dimensions) and discard others
ALL, // retain all dimensions
;
}
public enum DimensionConversionMode {
NONE, // don't convert dimensions whatsoever
CONCAT, // concatenate dimensions into a single, long univariate time series
STRATIFY, // stratify dimensions into a single, long univariate time series
SHUFFLE_CONCAT, // shuffle, then concat
SHUFFLE_STRATIFY, // shuffle, then stratify
RANDOM, // random pick between the above conversions
;
}
public enum DistanceMode {
DEPENDENT, // let the distance measure consider all dimensions to compute distance
INDEPENDENT, // independently compute distance on each dimension, then sum for final distance
RANDOM, // randomly choose independent or dependent
;
}
@Override public boolean isFullyBuilt() {
return nodeBuildQueue != null && nodeBuildQueue.isEmpty() && tree != null && tree.getRoot() != null;
}
public boolean isBreadthFirst() {
return breadthFirst;
}
public void setBreadthFirst(final boolean breadthFirst) {
this.breadthFirst = breadthFirst;
}
public List<ParamSpaceBuilder> getDistanceMeasureSpaceBuilders() {
return distanceMeasureSpaceBuilders;
}
public void setDistanceMeasureSpaceBuilders(final List<ParamSpaceBuilder> distanceMeasureSpaceBuilders) {
this.distanceMeasureSpaceBuilders = Objects.requireNonNull(distanceMeasureSpaceBuilders);
Assert.assertFalse(distanceMeasureSpaceBuilders.isEmpty());
}
@Override public long getTrainTime() {
return getRunTime() - getCheckpointingTime();
}
@Override public long getRunTime() {
return runTimer.elapsedTime();
}
@Override public long getTestTime() {
return testTimer.elapsedTime();
}
@Override
public long getTestTimeLimit() {
return testTimeLimit;
}
@Override
public void setTestTimeLimit(final long nanos) {
testTimeLimit = nanos;
}
@Override
public long getTrainTimeLimit() {
return trainTimeLimit;
}
@Override
public void setTrainTimeLimit(long nanos) {
trainTimeLimit = nanos;
}
@Override
public void buildClassifier(TimeSeriesInstances trainData) throws Exception {
// timings:
// train time tracks the time spent processing the algorithm. This should not be used for contracting.
// run time tracks the entire time spent processing, whether this is work towards the algorithm or otherwise (e.g. saving checkpoints to disk). This should be used for contracting.
// evaluation time tracks the time spent evaluating the quality of the classifier, i.e. producing an estimate of the train data error.
// checkpoint time tracks the time spent loading / saving the classifier to disk.
// record the start time
final long timeStamp = System.nanoTime();
memoryWatcher.start();
checkpointConfig.setLogger(getLogger());
// several scenarios for entering this method:
// 1) from scratch: isRebuild() is true
// 1a) checkpoint found and loaded, resume from wherever left off
// 1b) checkpoint not found, therefore initialise classifier and build from scratch
// 2) rebuild off, i.e. buildClassifier has been called before and already handled 1a or 1b. We can safely continue building from current state. This is often the case if a smaller contract has been executed (e.g. 1h), then the contract is extended (e.g. to 2h) and we enter into this method again. There is no need to reinitialise / discard current progress - simply continue on under new constraints.
if(isRebuild()) {
// case (1)
// load from a checkpoint
if(loadCheckpoint()) {
memoryWatcher.start();
checkpointConfig.setLogger(getLogger());
} else {
// case (1b)
memoryWatcher.reset();
// let super build anything necessary (will handle isRebuild accordingly in super class)
super.buildClassifier(trainData);
// if rebuilding
// then init vars
// build timer is already started so just clear any time already accrued from previous builds. I.e. keep the time stamp of when the timer was started, but clear any record of accumulated time
runTimer.reset();
checkpointConfig.resetCheckpointingTime();
// setup the tree vars
tree = new BaseTree<>();
nodeBuildQueue = new LinkedList<>();
longestTrainStageTime = 0;
if(isCacheTransforms()) {
// clear out any old cached versions
transformerCache = new HashMap<>();
}
// setup the root node
final TreeNode<Split> root = new BaseTreeNode<>(new Split(trainData, new IndexList(trainData.numInstances())), null);
// add the root node to the tree
tree.setRoot(root);
// add the root node to the build queue
nodeBuildQueue.add(root);
} // else case (1a)
} // else case (2)
// update the run timer with the start time of this session
// as the runtimer has been overwritten with the one from the checkpoint (if loaded)
// or the classifier has been initialised from scratch / resumed and can just start from the timestamp
runTimer.start(timeStamp);
LogUtils.logTimeContract(runTimer.elapsedTime(), trainTimeLimit, getLogger(), "train");
boolean workDone = false;
// maintain a timer for how long nodes take to build
final StopWatch trainStageTimer = new StopWatch();
while(
// there's remaining nodes to be built
!nodeBuildQueue.isEmpty()
&&
// there is enough time for another split to be built
insideTrainTimeLimit( runTimer.elapsedTime() + longestTrainStageTime)
) {
// time how long it takes to build the node
trainStageTimer.resetAndStart();
// get the next node to be built
final TreeNode<Split> node = nodeBuildQueue.removeFirst();
// partition the data at the node
Split split = node.getValue();
// find the best of R partitioning attempts
split = buildSplit(split);
node.setValue(split);
// for each partition of data build a child node
final List<TreeNode<Split>> children = buildChildNodes(node);
// add the child nodes to the build queue
enqueueNodes(children);
// done building this node
trainStageTimer.stop();
workDone = true;
// checkpoint if necessary
saveCheckpoint();
// update the train timer
LogUtils.logTimeContract(runTimer.elapsedTime(), trainTimeLimit, getLogger(), "train");
// calculate the longest time taken to build a node given
longestTrainStageTime = Math.max(longestTrainStageTime, trainStageTimer.elapsedTime());
}
// stop resource monitoring
memoryWatcher.stop();
runTimer.stop();
// save the final checkpoint / info
if(workDone) {
ResultUtils.setInfo(trainResults, this, trainData);
forceSaveCheckpoint();
}
}
public Tree<Split> getTree() {
return tree;
}
@Override public long getMaxMemoryUsage() {
return memoryWatcher.getMaxMemoryUsage();
}
/**
* setup the child nodes given the parent node
*
* @param parent
* @return
*/
private List<TreeNode<Split>> buildChildNodes(TreeNode<Split> parent) {
final Split split = parent.getValue();
List<TreeNode<Split>> children = new ArrayList<>(split.numPartitions());
for(int i = 0; i < split.numPartitions(); i++) {
final TimeSeriesInstances data = split.getPartitionData(i);
final List<Integer> dataIndicesInTrainData = split.getPartitionDataIndicesInTrainData(i);
final Split child = new Split(data, dataIndicesInTrainData);
children.add(new BaseTreeNode<>(child, parent));
}
return children;
}
/**
* add nodes to the build queue if they fail the stopping criteria
*
* @param nodes
*/
private void enqueueNodes(List<TreeNode<Split>> nodes) {
// for each node
for(int i = 0; i < nodes.size(); i++) {
TreeNode<Split> node;
if(breadthFirst) {
// get the ith node if breath first
node = nodes.get(i);
} else {
// get the nodes in reverse order if depth first (as we add to the front of the build queue, so need
// to lookup nodes in reverse order here)
node = nodes.get(nodes.size() - i - 1);
}
// check the data at the node is not pure
final List<Integer> uniqueClassLabelIndices =
node.getValue().getData().stream().map(TimeSeriesInstance::getLabelIndex).distinct()
.collect(Collectors.toList());
if(uniqueClassLabelIndices.size() > 1) {
// if not hit the stopping condition then add node to the build queue
if(breadthFirst) {
nodeBuildQueue.addLast(node);
} else {
nodeBuildQueue.addFirst(node);
}
}
}
}
@Override
public double[] distributionForInstance(final TimeSeriesInstance instance) throws Exception {
// enable resource monitors
testTimer.resetAndStart();
long longestPredictTime = 0;
// start at the tree node
TreeNode<Split> node = tree.getRoot();
if(node.isEmpty()) {
// root node has not been built, just return random guess
return ArrayUtilities.uniformDistribution(getNumClasses());
}
int index = -1;
int i = 0;
Split split = node.getValue();
final StopWatch testStageTimer = new StopWatch();
// traverse the tree downwards from root
while(
!node.isLeaf()
&&
insideTestTimeLimit(testTimer.elapsedTime() + longestPredictTime)
) {
testStageTimer.resetAndStart();
// work out which branch to go to next
index = split.findPartitionIndexFor(instance);
// make this the next node to visit
node = node.get(index);
// get the split at that node
split = node.getValue();
// finish up this test stage
testStageTimer.stop();
longestPredictTime = testStageTimer.elapsedTime();
}
// hit a leaf node
// the split defines the distribution for this test inst. If the split is pure, this will be a one-hot dist.
double[] distribution = split.distributionForInstance(instance);
// disable the resource monitors
testTimer.stop();
return distribution;
}
public int height() {
return tree.height();
}
public int size() {
return tree.size();
}
public int getR() {
return r;
}
public void setR(final int r) {
Assert.assertTrue(r > 0);
this.r = r;
}
public SplitScorer getSplitScorer() {
return splitScorer;
}
public void setSplitScorer(final SplitScorer splitScorer) {
this.splitScorer = splitScorer;
}
@Override public String toString() {
return "ProximityTree{tree=" + tree + "}";
}
private Split buildSplit(Split unbuiltSplit) {
Split bestSplit = null;
final TimeSeriesInstances data = unbuiltSplit.getData();
final List<Integer> dataIndices = unbuiltSplit.getDataIndicesInTrainData();
// need to find the best of R splits
// linearly go through r splits and select the best
for(int i = 0; i < r; i++) {
// construct a new split
final Split split = new Split(data, dataIndices);
split.buildSplit();
final double score = split.getScore();
if(bestSplit == null || score > bestSplit.getScore()) {
bestSplit = split;
}
}
return Objects.requireNonNull(bestSplit);
}
public boolean isEarlyExemplarCheck() {
return earlyExemplarCheck;
}
public void setEarlyExemplarCheck(final boolean earlyExemplarCheck) {
this.earlyExemplarCheck = earlyExemplarCheck;
}
public boolean isEarlyAbandonDistances() {
return earlyAbandonDistances;
}
public void setEarlyAbandonDistances(final boolean earlyAbandonDistances) {
this.earlyAbandonDistances = earlyAbandonDistances;
}
public boolean isPartitionExaminationReordering() {
return partitionExaminationReordering;
}
public void setPartitionExaminationReordering(final boolean partitionExaminationReordering) {
this.partitionExaminationReordering = partitionExaminationReordering;
}
private class Split implements Serializable, Iterator<Integer> {
public Split(TimeSeriesInstances data, List<Integer> dataIndicesInTrainData) {
setData(data, dataIndicesInTrainData);
}
// the distance function for comparing instances to exemplars
private DistanceMeasure distanceMeasure;
// the data at this split (i.e. before being partitioned)
private TimeSeriesInstances data; // the split data
private List<Integer> dataIndicesInTrainData; // the indices of the split data in the train data
// the partitions of the data, each containing data for the partition and exemplars representing the partition
// store pairwise set of data in the partition and corresponding exemplar
private List<Integer> exemplarIndicesInSplitData;
private List<TimeSeriesInstance> exemplars;
private List<List<Integer>> partitionedDataIndicesInSplitData; // each list is a partition containing indices of insts in that partition. I.e. [[1,2,3],[4,5,6]] means partition 0 contains the 1,2,3rd inst at this split while partition 1 contains 4,5,6th inst at this split
// partitionIndices houses all the partitions to look at when partitioning. This obviously stays consistent (i.e. look at all partitions in order) when not using early abandon
private List<Integer> partitionIndices = null;
// maintain a list of desc partition sizes per class. This ensures (when enabled) partitions are examined in
// most likely first order
private List<List<Integer>> partitionOrderByClass;
// exemplars are normally checked ad-hoc during distance computation. Obviously checking which partition and exemplar belongs to is a waste of computation, as the distance will be zero and trump all other exemplars distances for other partitions. Therefore, it is important to check first. Original pf checked for exemplars as it went along, meaning for partition 5 it would compare exemplar 5 to exemplar 1..4 before realising it's an exemplar. Therefore, we can store the exemplar mapping to partition index and do a quick lookup before calculating distances. This is likely to only save a small amount of time, but increases as the breadth of trees / classes increases. I.e. for a 100 class problem, looking through 99 exemplars before realising we're examining the exemplar for the 100th partition is a large waste.
private Map<Integer, Integer> exemplarIndexInSplitDataToPartitionIndex = null;
// cache the scores
private boolean findScore = true;
// the score of this split
private double score = -1;
// track the stage of building
private int instIndexInSplitData = -1;
private TransformPipeline pipeline;
private TimeSeriesInstances transformedDataAtSplit;
private double[] distribution;
public double[] distributionForInstance(TimeSeriesInstance testInst) {
// report the prediction as the same as the data distribution at this split
if(distribution == null) {
distribution = new double[data.numClasses()];
for(TimeSeriesInstance inst : data) {
distribution[inst.getLabelIndex()]++;
}
ArrayUtilities.normalise(distribution);
}
return distribution;
}
public List<Integer> getPartitionIndices() {
return partitionIndices;
}
public List<List<Integer>> getPartitionOrderByClass() {
return partitionOrderByClass;
}
private Labels<Integer> getParentLabels() {
return new Labels<>(new AbstractList<Integer>() {
@Override public Integer get(final int i) {
return data.get(i).getLabelIndex();
}
@Override public int size() {
return data.numInstances();
}
}); // todo weights
}
public double getScore() {
if(findScore) {
findScore = false;
score = splitScorer.score(getParentLabels(), partitionedDataIndicesInSplitData.stream().map(partition -> new Labels<>(new AbstractList<Integer>() {
@Override public Integer get(final int i) {
final Integer instIndexInSplitData = partition.get(i);
return data.get(instIndexInSplitData).getLabelIndex();
}
@Override public int size() {
return partition.size();
}
})).collect(Collectors.toList()));
requireReal(score);
}
return score;
}
@Override public boolean hasNext() {
return instIndexInSplitData + 1 < data.numInstances();
}
public void setup() {
setupTransform();
setupDistanceMeasure();
setupExemplars();
setupMisc();
}
@Override public Integer next() {
// go through every instance and find which partition it should go into. This should be the partition
// with the closest exemplar associate
// shift i along to look at next inst
instIndexInSplitData++;
// mark that scores need recalculating, as we'd have added a new inst to a partition by the end of this method
findScore = true;
// get the inst to be partitioned
final TimeSeriesInstance inst = data.get(instIndexInSplitData);
Integer closestPartitionIndex = null;
if(earlyExemplarCheck) {
// check for exemplars. If the inst is an exemplar, we already know what partition it represents and therefore belongs to
closestPartitionIndex = exemplarIndexInSplitDataToPartitionIndex.get(instIndexInSplitData);
}
// if null then not exemplar / not doing quick exemplar checking
List<Integer> partitionIndicesOrder = null;
int closestPartitionIndexIndex = -1;
if(closestPartitionIndex == null) {
if(partitionExaminationReordering) {
// use the desc order of partition size for the given class
partitionIndicesOrder = partitionOrderByClass.get(inst.getLabelIndex());
} else {
// otherwise just loop through all partitions in order looking for the closest. Order is static and never changed
partitionIndicesOrder = partitionIndices;
}
closestPartitionIndexIndex = findPartitionIndexIndexFor(inst, instIndexInSplitData, partitionIndicesOrder);
closestPartitionIndex = partitionIndicesOrder.get(closestPartitionIndexIndex);
}
final List<Integer> partition = partitionedDataIndicesInSplitData.get(closestPartitionIndex);
partition.add(instIndexInSplitData);
// if using partition reordering and order has been set
if(partitionExaminationReordering && partitionIndicesOrder != null) {
// we know the partition which the inst will be allocated to
// need to update the partition order to maintain desc size
partitionIndicesOrder.set(closestPartitionIndexIndex, partition.size());
// continue shifting up the current partition until it is in the correct ascending order
// e.g. index: [2,4,0,3,1]
// sizes: [3,2,2,2,1]
// would become (after incrementing size of partition 3, the closest partition, say):
// index: [2,4,0,3,1]
// sizes: [3,2,2,3,1]
// shift the partition 3 upwards until desc order restored:
// index: [2,3,4,0,1]
// sizes: [3,3,2,2,1]
int i = closestPartitionIndexIndex - 1;
while(i >= 1 && partitionIndicesOrder.get(i - 1) > partitionIndicesOrder.get(i)) {
Collections.swap(partitionIndicesOrder, i - 1, i);
}
}
return closestPartitionIndex;
}
public void cleanup() {
transformedDataAtSplit = null;
// quick check that partitions line up with num insts
if(isDebug()) {
final HashSet<Integer> set = new HashSet<>();
partitionedDataIndicesInSplitData.forEach(set::addAll);
if(!new HashSet<>(new IndexList(data.numInstances())).containsAll(set)) {
throw new IllegalStateException("data indices mismatch");
}
}
}
/**
* Get the cached version of a transformer. The cached version can persist transforms to avoid repetition.
* @param transformer
* @return
*/
private Transformer getCachedTransformer(Transformer transformer) {
if(transformerCache != null) {
// get from internal source
return transformerCache.computeIfAbsent(transformer, x -> new CachedTransformer(transformer));
} else {
return transformer;
}
}
private void setupTransform() {
pipeline = new TransformPipeline();
if(data.isMultivariate()) {
// if sampling dimensions, then wrap distance measure in a sampler
int numDimensions = data.getMaxNumDimensions();
if(DimensionSamplingMode.SINGLE.equals(dimensionSamplingMode) || DimensionSamplingMode.SUBSET.equals(dimensionSamplingMode)) {
final int numChoices;
if(DimensionSamplingMode.SUBSET.equals(dimensionSamplingMode)) {
// select anywhere between 1..all dimensions
numDimensions = RandomUtils.choiceIndex(numDimensions, getRandom()) + 1;
} else {
// select only 1 dimension
numDimensions = 1;
}
final List<Integer> dimensionIndices = RandomUtils.choiceIndex(data.getMaxNumDimensions(), getRandom(), numDimensions);
// build a hSlicer to slice insts to the specified dimensions
final HSlicer hSlicer = new HSlicer(dimensionIndices);
// add the hslice to the transform pipeline
pipeline.add(hSlicer);
} else if(DimensionSamplingMode.ALL.equals(dimensionSamplingMode)) {
// do nothing
} else {
throw new IllegalStateException("unknown dimension sampling mode");
}
// if converting multivariate data somehow, then do so
// if shuffling before the convert, then do so
if(DimensionConversionMode.SHUFFLE_STRATIFY.equals(dimensionConversionMode) ||
DimensionConversionMode.SHUFFLE_CONCAT.equals(dimensionConversionMode)) {
if(numDimensions > 1) {
final HReorderer reorderer = new HReorderer();
reorderer.setIndices(new ArrayList<>(new IndexList(numDimensions)));
pipeline.add(reorderer);
}
}
// then apply conversion from multivariate to univariate if need be
if(DimensionConversionMode.CONCAT.equals(dimensionConversionMode)) {
// concat the dimensions into one (i.e. concat all the hSlices in turn)
pipeline.add(new HConcatenator());
} else if(DimensionConversionMode.STRATIFY.equals(dimensionConversionMode)) {
// stratify the dimensions into one (i.e. concat all the vSlices in turn)
pipeline.add(new VConcatenator());
} else if(DimensionConversionMode.NONE.equals(dimensionConversionMode)
|| DimensionConversionMode.SHUFFLE_CONCAT.equals(dimensionConversionMode)
|| DimensionConversionMode.SHUFFLE_STRATIFY.equals(dimensionConversionMode)) {
// do nothing, each mode already handled
} else {
throw new IllegalStateException("unknown dimension conversion mode");
}
}
transformedDataAtSplit = pipeline.fitTransform(data);
}
private void setupDistanceMeasure() {
// pick the distance function
// pick a random space
ParamSpaceBuilder distanceMeasureSpaceBuilder = RandomUtils.choice(distanceMeasureSpaceBuilders, getRandom());
// built that space
ParamSpace distanceMeasureSpace = distanceMeasureSpaceBuilder.build(transformedDataAtSplit);
// randomly pick the distance function / parameters from that space
final ParamSet paramSet = RandomSearch.choice(distanceMeasureSpace, getRandom());
// there is only one distance function in the ParamSet returned
distanceMeasure = Objects.requireNonNull((DistanceMeasure) paramSet.get(DistanceMeasure.DISTANCE_MEASURE_FLAG));
// if we can cache the transforms
if(isCacheTransforms()) {
// check whether the distance measure involves a transform
if(distanceMeasure instanceof TransformDistanceMeasure) {
Transformer transformer = ((TransformDistanceMeasure) distanceMeasure).getTransformer();
// check if transformer is of a type which can be cached
if(transformer instanceof Derivative) {
// cache all der transforms as they're simple, pure functions
transformer = getCachedTransformer(transformer);
}
// update the transformer with the cached version
((TransformDistanceMeasure) distanceMeasure).setTransformer(transformer);
}
}
// wrap distance measure in multivariate handling capabilities (i.e. dependent / indep dist, etc)
if(transformedDataAtSplit.isMultivariate()) {
// apply the distance mode
DistanceMode distanceMode = ProximityTree.this.distanceMode;
// if randomly picking distance mode
if(distanceMode.equals(DistanceMode.RANDOM)) {
// then random pick from the remaining modes
final Integer index = RandomUtils
.choiceIndexExcept(DistanceMode.values().length, getRandom(),
DistanceMode.RANDOM.ordinal());
distanceMode = DistanceMode.values()[index];
}
// if in independent mode
if(distanceMode.equals(DistanceMode.INDEPENDENT)) {
// then wrap the distance measure to evaluate each dimension in isolation
distanceMeasure = new IndependentDistanceMeasure(distanceMeasure);
} else if(distanceMode.equals(DistanceMode.DEPENDENT)) {
// do nothing, dependent is the default in distance measures
} else {
throw new IllegalStateException("unknown distance mode");
}
}
// setup the distance function (note this JUST sets up the distance measure, not the transformed distance measure)
distanceMeasure.buildDistanceMeasure(transformedDataAtSplit);
}
private void setupExemplars() {
// pick the exemplars
Objects.requireNonNull(transformedDataAtSplit);
Assert.assertTrue(transformedDataAtSplit.iterator().hasNext());
// change the view of the data into per class
final List<List<Integer>> instIndicesByClass = data.getInstIndicesByClass();
// pick exemplars per class
partitionedDataIndicesInSplitData = new ArrayList<>(data.numClasses());
exemplars = new ArrayList<>(data.numClasses());
exemplarIndicesInSplitData = new ArrayList<>(data.numClasses());
// generate a partition per class
for(final List<Integer> sameClassInstIndices : instIndicesByClass) {
// avoid empty classes, no need to create partition / exemplars from them
if(!sameClassInstIndices.isEmpty()) {
// get the indices of all instances with the specified class
// random pick exemplars from this
final Integer exemplarIndexInSplitData = RandomUtils.choice(sameClassInstIndices, getRandom());
exemplarIndicesInSplitData.add(exemplarIndexInSplitData);
// generate the partition with empty data and the chosen exemplar instances
final ArrayList<Integer> partition = new ArrayList<>();
partitionedDataIndicesInSplitData.add(partition);
// find the index of the exemplar in the dataIndices (i.e. the exemplar may be the 5th instance
// in the data but the 5th instance may have index 33 in the train data)
TimeSeriesInstance exemplar = transformedDataAtSplit.get(exemplarIndexInSplitData);
exemplars.add(exemplar);
}
}
}
private void setupMisc() {
// the list of partition indices to browse through when allocating an inst to a partition
partitionIndices = new IndexList(partitionedDataIndicesInSplitData.size());
if(partitionExaminationReordering) {
// init the desc order of partitions for each class
// for each class, make a list holding the partition indices in desc order of size
// this order will be maintained as insts are allocated to partitions, hence maintaining a list of
// the most likely partition to end up in given an inst is of a certain class
partitionOrderByClass = new ArrayList<>(data.numClasses());
for(int i = 0; i < data.numClasses(); i++) {
partitionOrderByClass.add(new ArrayList<>(partitionIndices));
}
}
if(earlyExemplarCheck) {
exemplarIndexInSplitDataToPartitionIndex = new HashMap<>();
// chuck all exemplars in a map to check against before doing distance computation
for(int i = 0; i < exemplarIndicesInSplitData.size(); i++) {
final Integer exemplarIndexInSplitData = exemplarIndicesInSplitData.get(i);
exemplarIndexInSplitDataToPartitionIndex.put(exemplarIndexInSplitData, i);
}
}
}
/**
* Partition the data and derive score for this split.
*/
public void buildSplit() {
setup();
while(hasNext()) {
next();
}
cleanup();
}
public DistanceMeasure getDistanceMeasure() {
return distanceMeasure;
}
public int findPartitionIndexFor(final TimeSeriesInstance inst, int instIndexInSplitData, List<Integer> partitionIndices) {
final int partitionIndexIndex = findPartitionIndexIndexFor(inst, instIndexInSplitData, partitionIndices);
return partitionIndices.get(partitionIndexIndex);
}
/**
* get the partition of the given instance. The returned partition is the set of data the given instance belongs to based on its proximity to the exemplar instances representing the partition.
*
* @param inst
* @param instIndexInSplitData the index of the inst in the data at this node. If the inst is not in the data at this node then set this to -1
* @return
*/
public int findPartitionIndexIndexFor(TimeSeriesInstance inst, int instIndexInSplitData, List<Integer> partitionIndicesIterator) {
// replace inst with transformed version (i.e. apply the multivariate strategy)
if(instIndexInSplitData >= 0) {
inst = transformedDataAtSplit.get(instIndexInSplitData);
} else {
inst = pipeline.transform(inst);
}
// a map to maintain the closest partition indices
final PrunedMap<Double, Integer> filter = PrunedMap.asc(1);
// maintain a limit on distance computation
double limit = Double.POSITIVE_INFINITY;
// loop through exemplars / partitions
for(int i = 0; i < partitionIndicesIterator.size(); i++) {
final Integer exemplarIndexInSplitData = exemplarIndicesInSplitData.get(i);
// check the instance isn't an exemplar
if(!earlyExemplarCheck && instIndexInSplitData == exemplarIndexInSplitData) {
return i;
}
final TimeSeriesInstance exemplar = exemplars.get(i);
// find the distance
final double distance = distanceMeasure.distance(exemplar, inst, limit);
// add the distance and partition to the map
if(filter.add(distance, i)) {
// new min dist
// set new limit if early abandon enabled
if(earlyAbandonDistances) {
limit = distance;
}
}
}
// random pick the best partition for the instance
return RandomUtils.choice(filter.valuesList(), rand);
}
/**
* Find the partition index of an unseen instance (i.e. a test inst)
* @param inst
* @return
*/
public int findPartitionIndexFor(final TimeSeriesInstance inst) {
return findPartitionIndexFor(inst, -1, partitionIndices);
}
public TimeSeriesInstances getData() {
return data;
}
public void setData(TimeSeriesInstances data, List<Integer> dataIndices) {
this.dataIndicesInTrainData = Objects.requireNonNull(dataIndices);
this.data = Objects.requireNonNull(data);
Assert.assertEquals(data.numInstances(), dataIndices.size());
}
public List<Integer> getDataIndicesInTrainData() {
return dataIndicesInTrainData;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if(distanceMeasure != null) {
// then split has been built
sb.append("df=").append(distanceMeasure);
sb.append(", partitionedDataIndices=").append(getPartitionedDataIndicesInTrainData());
sb.append(", ");
}
sb.append("dataIndices=").append(dataIndicesInTrainData);
return sb.toString();
}
public int numPartitions() {
return partitionedDataIndicesInSplitData.size();
}
public List<List<Integer>> getPartitionedDataIndicesInTrainData() {
List<List<Integer>> indices = new ArrayList<>();
for(int i = 0; i < numPartitions(); i++) {
indices.add(getPartitionDataIndicesInTrainData(i));
}
return indices;
}
public List<TimeSeriesInstances> getPartitionedData() {
List<TimeSeriesInstances> data = new ArrayList<>();
for(int i = 0; i < numPartitions(); i++) {
data.add(getPartitionData(i));
}
return data;
}
public TimeSeriesInstances getPartitionData(int i) {
final List<TimeSeriesInstance> data =
partitionedDataIndicesInSplitData.get(i).stream().map(this.data::get)
.collect(Collectors.toList());
return new TimeSeriesInstances(data, this.data.getClassLabels());
}
public List<Integer> getPartitionDataIndicesInTrainData(int i) {
return partitionedDataIndicesInSplitData.get(i).stream().map(dataIndicesInTrainData::get).collect(Collectors.toList());
}
}
}
| 51,483 | 45.591855 | 827 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/Transposer.java | package tsml.classifiers.distance_based.proximity;
import tsml.data_containers.TimeSeriesInstance;
import tsml.transformers.Transformer;
import weka.core.Instances;
public class Transposer implements Transformer {
@Override public Instances determineOutputFormat(final Instances data) throws IllegalArgumentException {
return data; // todo transpose it
}
@Override public TimeSeriesInstance transform(final TimeSeriesInstance inst) {
return new TimeSeriesInstance(inst.toTransposedArray(), inst.getLabelIndex());
}
}
| 552 | 33.5625 | 108 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/TransposerTest.java | package tsml.classifiers.distance_based.proximity;
import org.junit.Assert;
import org.junit.Test;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
public class TransposerTest {
@Test
public void test() {
final Transposer t = new Transposer();
final TimeSeries a = new TimeSeries(new double[]{1, 2, 3, 4, 5});
final TimeSeries b = new TimeSeries(new double[]{6, 7, 8, 9, 10});
final TimeSeriesInstance inst = new TimeSeriesInstance(1, Arrays.asList(a, b));
final TimeSeriesInstance other = t.transform(inst);
Assert.assertEquals(5, other.getNumDimensions());
Assert.assertArrayEquals(new double[] {1,6}, other.get(0).toValueArray(), 0d);
Assert.assertArrayEquals(new double[] {2,7}, other.get(1).toValueArray(), 0d);
Assert.assertArrayEquals(new double[] {3,8}, other.get(2).toValueArray(), 0d);
Assert.assertArrayEquals(new double[] {4,9}, other.get(3).toValueArray(), 0d);
Assert.assertArrayEquals(new double[] {5,10}, other.get(4).toValueArray(), 0d);
}
}
| 1,132 | 39.464286 | 87 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/VConcatenator.java | package tsml.classifiers.distance_based.proximity;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import tsml.transformers.Transformer;
import weka.core.Instances;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class VConcatenator implements Transformer {
public VConcatenator() {
}
@Override public Instances determineOutputFormat(final Instances data) throws IllegalArgumentException {
return data;
}
@Override public TimeSeriesInstance transform(final TimeSeriesInstance inst) {
final List<Double> values = new ArrayList<>();
for(int i = 0; i < inst.getMaxLength(); i++) {
for(int j = 0; j < inst.getNumDimensions(); j++) {
values.add(inst.get(j).get(i));
}
}
return new TimeSeriesInstance(Collections.singletonList(values), inst.getLabelIndex());
}
@Override public String toString() {
return "VC";
}
}
| 1,052 | 26.710526 | 108 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/VConcatenatorTest.java | package tsml.classifiers.distance_based.proximity;
import org.junit.Assert;
import org.junit.Test;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
public class VConcatenatorTest {
@Test
public void test() {
final VConcatenator t = new VConcatenator();
final TimeSeries a = new TimeSeries(new double[]{1, 2, 3, 4, 5});
final TimeSeries b = new TimeSeries(new double[]{6, 7, 8, 9, 10});
final TimeSeriesInstance inst = new TimeSeriesInstance(1, Arrays.asList(a, b));
final TimeSeriesInstance other = t.transform(inst);
Assert.assertEquals(1, other.getNumDimensions());
Assert.assertArrayEquals(new double[] {1, 6, 2, 7, 3, 8, 4, 9, 5, 10}, other.get(0).toValueArray(), 0d);
}
}
| 813 | 34.391304 | 112 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/VSlicer.java | package tsml.classifiers.distance_based.proximity;
import tsml.data_containers.TimeSeriesInstance;
import tsml.transformers.Transformer;
import weka.core.Instances;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class VSlicer implements Transformer {
public VSlicer() {
this(Collections.emptyList());
}
public VSlicer(List<Integer> indices) {
setIndices(indices);
}
private List<Integer> indices;
@Override public Instances determineOutputFormat(final Instances data) throws IllegalArgumentException {
return data;
}
@Override public TimeSeriesInstance transform(final TimeSeriesInstance inst) {
return inst.getVSlice(indices);
}
public List<Integer> getIndices() {
return indices;
}
public void setIndices(final List<Integer> indices) {
this.indices = Objects.requireNonNull(indices);
}
@Override public String toString() {
return "V" + indices.toString();
}
}
| 1,032 | 23.023256 | 108 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/proximity/VSlicerTest.java | package tsml.classifiers.distance_based.proximity;
import org.junit.Assert;
import org.junit.Test;
import tsml.data_containers.TimeSeries;
import tsml.data_containers.TimeSeriesInstance;
import java.util.Arrays;
public class VSlicerTest {
@Test
public void test() {
final VSlicer vSlicer = new VSlicer();
vSlicer.setIndices(Arrays.asList(1, 3));
final TimeSeries a = new TimeSeries(new double[]{1, 2, 3, 4, 5});
final TimeSeries b = new TimeSeries(new double[]{6, 7, 8, 9, 10});
final TimeSeriesInstance inst = new TimeSeriesInstance(1, Arrays.asList(a, b));
final TimeSeriesInstance other = vSlicer.transform(inst);
Assert.assertEquals(2, other.getNumDimensions());
Assert.assertArrayEquals(new double[] {2,4}, other.get(0).toValueArray(), 0d);
Assert.assertArrayEquals(new double[] {7,9}, other.get(1).toValueArray(), 0d);
}
}
| 917 | 35.72 | 87 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/BaseClassifier.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.classifiers.distance_based.utils.classifiers;
import evaluation.storage.ClassifierResults;
import java.util.Objects;
import java.util.Random;
import java.util.logging.Logger;
import tsml.classifiers.EnhancedAbstractClassifier;
import tsml.classifiers.distance_based.utils.system.copy.Copier;
import tsml.classifiers.distance_based.utils.system.logging.LogUtils;
import tsml.classifiers.distance_based.utils.system.logging.Loggable;
import tsml.classifiers.distance_based.utils.collections.params.ParamHandler;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.system.random.Randomised;
import tsml.data_containers.TimeSeriesInstance;
import tsml.data_containers.TimeSeriesInstances;
import tsml.data_containers.utilities.Converter;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Utils;
/**
* Purpose: base classifier implementing all common interfaces for the classifiers.distance_based.
* Note, this is only for distance based classifiers, which currently run a parallel code structure to the other classifiers
* there is duplication here that could be removed (e.g. TrainEstimateable and seedSet variable)
* <p>
* Contributors: goastler
*/
public abstract class BaseClassifier extends EnhancedAbstractClassifier implements Rebuildable, ParamHandler, Copier, TrainEstimateable, Loggable,
Randomised {
private transient Logger log = LogUtils.getLogger(getClass());
// whether the classifier is to be built from scratch or not. Set this to true to incrementally improve the model on every buildClassifier call
private boolean rebuild = true;
protected BaseClassifier() {
this(false);
}
protected BaseClassifier(boolean a) {
super(a);
}
public String[] getLabels() {
return getTSTrainData().getClassLabels();
}
@Override public Logger getLogger() {
return log;
}
@Override public void setLogger(final Logger logger) {
log = Objects.requireNonNull(logger);
}
@Override public void setClassifierName(final String classifierName) {
super.setClassifierName(Objects.requireNonNull(classifierName));
}
@Override public void buildClassifier(final TimeSeriesInstances trainData) throws Exception {
if(rebuild) {
// reset train results
trainResults = new ClassifierResults();
// check the seed has been set
checkRandom();
// remember the data
setTSTrainData(trainData);
// we're rebuilding so set the seed / params, etc, using super
super.buildClassifier(Converter.toArff(Objects.requireNonNull(trainData)));
}
}
@Override
public final void buildClassifier(Instances trainData) throws Exception {
buildClassifier(Converter.fromArff(trainData));
}
@Override
public ParamSet getParams() {
return new ParamSet();
}
@Override
public void setParams(ParamSet params) throws Exception {
Objects.requireNonNull(params);
}
@Override
public String getParameters() {
return super.getParameters() + ",params," + getParams().toString();
}
public boolean isRebuild() {
return rebuild;
}
public void setRebuild(boolean rebuild) {
this.rebuild = rebuild;
}
@Override
public void setSeed(int seed) {
super.setSeed(seed);
setRandom(new Random(seed));
}
@Override
public final double[] distributionForInstance(final Instance instance) throws Exception {
return distributionForInstance(Converter.fromArff(instance));
}
@Override public abstract double[] distributionForInstance(final TimeSeriesInstance inst) throws Exception;
@Override public String[] getOptions() {
return ParamHandler.super.getOptions();
}
@Override public void setOptions(final String[] options) throws Exception {
ParamHandler.super.setOptions(options);
}
@Override public String toString() {
final String options = Utils.joinOptions(getOptions());
if(!options.isEmpty()) {
return getClassifierName() + " " + options;
} else {
return getClassifierName();
}
}
}
| 5,193 | 33.626667 | 147 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/Parallelisable.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.classifiers.distance_based.utils.classifiers;
/**
* Purpose: manage parallelism. At the moment this is just to detect whether we've yielded to another process, but it
* could control parallelisation further in future.
*
* Contributors: goastler
*/
public interface Parallelisable {
boolean hasYielded();
}
| 1,091 | 36.655172 | 117 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/Rebuildable.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.classifiers.distance_based.utils.classifiers;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public interface Rebuildable {
boolean isRebuild();
void setRebuild(boolean state);
}
| 1,023 | 31 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/TrainEstimateable.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.classifiers.distance_based.utils.classifiers;
import evaluation.storage.ClassifierResults;
/**
* Purpose: control estimating the train error.
* <p>
* Contributors: goastler
*/
public interface TrainEstimateable {
ClassifierResults getTrainResults();
boolean getEstimateOwnPerformance();
void setEstimateOwnPerformance(boolean estimateOwnPerformance);
}
| 1,154 | 31.083333 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/checkpointing/CheckpointConfig.java | package tsml.classifiers.distance_based.utils.classifiers.checkpointing;
import tsml.classifiers.distance_based.utils.system.logging.Loggable;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class CheckpointConfig implements Serializable, Loggable {
public CheckpointConfig() {
setCheckpointInterval(TimeUnit.NANOSECONDS.convert(4, TimeUnit.HOURS));
setKeepCheckpoints(false);
setCheckpointPath(null);
setLogger(null);
clear();
}
private boolean keepCheckpoints;
private String checkpointPath;
private long checkpointInterval;
private long lastCheckpointRunTime;
private long checkpointLoadTime;
private long checkpointSaveTime;
private transient Logger logger;
public void clear() {
lastCheckpointRunTime = 0;
checkpointLoadTime = 0;
checkpointSaveTime = 0;
}
public boolean isKeepCheckpoints() {
return keepCheckpoints;
}
public void setKeepCheckpoints(final boolean keepCheckpoints) {
this.keepCheckpoints = keepCheckpoints;
}
public String getCheckpointPath() {
return checkpointPath;
}
public boolean setCheckpointPath(final String checkpointPath) {
this.checkpointPath = checkpointPath;
return checkpointPath != null;
}
public long getCheckpointInterval() {
return checkpointInterval;
}
public void setCheckpointInterval(final long checkpointInterval) {
this.checkpointInterval = checkpointInterval;
}
public long getLastCheckpointRunTime() {
return lastCheckpointRunTime;
}
public void setLastCheckpointRunTime(final long lastCheckpointRunTime) {
this.lastCheckpointRunTime = lastCheckpointRunTime;
}
public long getCheckpointLoadTime() {
return checkpointLoadTime;
}
public long getCheckpointSaveTime() {
return checkpointSaveTime;
}
public void addSaveTime(long time) {
checkpointSaveTime += time;
}
public void addLoadTime(long time) {
checkpointLoadTime += time;
}
@Override public Logger getLogger() {
return logger;
}
@Override public void setLogger(final Logger logger) {
this.logger = logger;
}
public void resetSaveTime() {
checkpointSaveTime = 0;
}
public void resetLoadTime() {
checkpointLoadTime = 0;
}
public void resetCheckpointingTime() {
resetLoadTime();
resetSaveTime();
}
}
| 2,614 | 24.144231 | 79 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/checkpointing/Checkpointed.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.classifiers.distance_based.utils.classifiers.checkpointing;
import tsml.classifiers.Checkpointable;
import tsml.classifiers.distance_based.utils.classifiers.contracting.TimedTrain;
import tsml.classifiers.distance_based.utils.experiment.TimeSpan;
import tsml.classifiers.distance_based.utils.system.copy.CopierUtils;
import utilities.FileUtils;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public interface Checkpointed extends Checkpointable, TimedTrain {
String CHECKPOINT_EXTENSION = "tar.gz";
String CHECKPOINT_EXTENSION_WITH_DOT = "." + CHECKPOINT_EXTENSION;
String CHECKPOINT_PREFIX = "checkpoint";
String CHECKPOINT_PREFIX_WITH_UNDERSCORE = CHECKPOINT_PREFIX + "_";
CheckpointConfig getCheckpointConfig();
default String getCheckpointPath() {
return getCheckpointConfig().getCheckpointPath();
}
/**
* Get the run time at the last checkpoint. We use this to work out whether the checkpoint interval has expired /
* allocate checkpoints to intervals in the case where checkpoints do not land exactly in the interval time points.
* @return
*/
default long getLastCheckpointRunTime() {
return getCheckpointConfig().getLastCheckpointRunTime();
}
/**
* time spent saving checkpoints
*/
default long getCheckpointSaveTime() {
return getCheckpointConfig().getCheckpointSaveTime();
}
/**
* time spent saving checkpoints
*/
default long getCheckpointLoadTime() {
return getCheckpointConfig().getCheckpointSaveTime();
}
default long getCheckpointInterval() {
return getCheckpointConfig().getCheckpointInterval();
}
default void setCheckpointInterval(final long checkpointInterval) {
getCheckpointConfig().setCheckpointInterval(checkpointInterval);
}
default void setCheckpointInterval(final long amount, final TimeUnit unit) {
setCheckpointInterval(TimeUnit.NANOSECONDS.convert(amount, unit));
}
default void setCheckpointInterval(final TimeSpan timeSpan) {
setCheckpointInterval(timeSpan.inNanos());
}
default boolean isCheckpointPathSet() {
return getCheckpointConfig().getCheckpointPath() != null;
}
/**
* the total time spent checkpointing
* @return
*/
default long getCheckpointingTime() {
return getCheckpointLoadTime() + getCheckpointSaveTime();
}
default boolean isKeepCheckpoints() {
return getCheckpointConfig().isKeepCheckpoints();
}
default void setKeepCheckpoints(boolean state) {
getCheckpointConfig().setKeepCheckpoints(state);
}
/**
* Load the most recent checkpoint
* @return
*/
default boolean loadCheckpoint() throws Exception {
final long startTimeStamp = System.nanoTime();
boolean loaded = false;
if(isCheckpointPathSet()) {
final Logger logger = getCheckpointConfig().getLogger();
final File dir = new File(getCheckpointPath());
if(!dir.exists()) {
logger.info("checkpoint dir does not exist, skipping load checkpoint");
} else if(!dir.isDirectory()) {
logger.info("checkpoint path is not a dir, skipping load checkpoint");
} else {
final String[] files = dir.list();
if(files == null || files.length <= 0) {
logger.info("no past checkpoints found");
} else {
// get the file with the largest timestamp. Files are saved with as <timestamp>.tar.gz
Arrays.sort(files, Comparator.comparingLong(file -> {
final String time = file.replace(CHECKPOINT_PREFIX_WITH_UNDERSCORE, "").replace(CHECKPOINT_EXTENSION_WITH_DOT, "");
return Long.parseLong(time);
}));
final String file = files[files.length - 1];
final String checkpointPath = dir + "/" + file;
loadFromFile(checkpointPath);
loaded = true;
logger.info("loaded checkpoint from " + checkpointPath);
}
}
}
// add time taken loading checkpoints onto total load time
CheckpointConfig config = getCheckpointConfig();
// set the last checkpoint time to now to avoid saveCheckpoint calls after this saving a new checkpoint when
// less than interval time has passed
config.setLastCheckpointRunTime(getRunTime());
config.addLoadTime(System.nanoTime() - startTimeStamp);
return loaded;
}
default boolean saveCheckpoint() throws Exception {
return saveCheckpoint(false);
}
/**
* Save checkpoint irrelevant of checkpoint interval
* @return
* @throws Exception
*/
default boolean forceSaveCheckpoint() throws Exception {
return saveCheckpoint(true);
}
default boolean saveCheckpoint(boolean force) throws Exception {
long timeStamp = System.nanoTime();
boolean saved = false;
if(isCheckpointPathSet()) {
if(isCheckpointIntervalExpired() || force) {
// get current checkpoints that already exist
final String path = getCheckpointPath();
final String[] files = new File(path).list();
// save this checkpoint
final long runTime = getRunTime();
final String checkpointPath = path + "/" + CHECKPOINT_PREFIX_WITH_UNDERSCORE + runTime + CHECKPOINT_EXTENSION_WITH_DOT;
final long timeStampBeforeSave = System.nanoTime();
// take snapshot of timings
getCheckpointConfig().addSaveTime(timeStampBeforeSave - timeStamp);
// update the start time as we've already accounted for time before save operation
timeStamp = timeStampBeforeSave;
saveToFile(checkpointPath);
// remove any previous checkpoints
if(!isKeepCheckpoints()) {
if(files != null) {
for(String file : files) {
final File f = new File(path + "/" + file);
final String name = f.getName();
if(name.startsWith(CHECKPOINT_PREFIX_WITH_UNDERSCORE) && name.endsWith(CHECKPOINT_EXTENSION_WITH_DOT)) {
if(!f.delete()) {
throw new IllegalStateException("failed to delete checkpoint " + f.getPath());
}
}
}
}
}
getCheckpointConfig().getLogger().info("saved checkpoint to " + checkpointPath);
// update the checkpoint time stamp
getCheckpointConfig().setLastCheckpointRunTime(runTime);
}
}
getCheckpointConfig().addSaveTime(System.nanoTime() - timeStamp);
return saved;
}
@Override default void copyFromSerObject(Object obj) throws Exception {
CopierUtils.shallowCopy(obj, this);
}
@Override default void saveToFile(String path) throws Exception {
FileUtils.makeParentDir(path);
Checkpointable.super.saveToFile(path);
}
@Override default boolean setCheckpointPath(String path) {
getCheckpointConfig().setCheckpointPath(path);
return true;
}
default boolean isCheckpointIntervalExpired() {
// need to work out what interval we're in. E.g. say the last checkpoint was at 11hrs and we've got an interval
// of 3hrs. The checkpoint should have occurred at 9hrs, but was missed due to processing / when checkpoints can
// be taken. Therefore, the checkpoint occurred at 11hrs. We still want to checkpoint at 12hrs, otherwise the
// pattern of intervals is ever changing. I.e. we want 3hrs, 6hrs, 9hrs, 12hrs, ... or as close to that as
// possible. Therefore, we'll work out what interval the last checkpoint time corresponds to (e.g. 11hr
// corresponding to the 9hr interval point) and find the next interval point from there (e.g. 9hr + 3hr = 12hr)
final long lastCheckpointTimeStamp = getLastCheckpointRunTime();
final long checkpointInterval = getCheckpointInterval();
final long startTimeStampForMostRecentInterval = lastCheckpointTimeStamp - lastCheckpointTimeStamp % checkpointInterval;
return getRunTime() >= startTimeStampForMostRecentInterval + checkpointInterval;
}
}
| 9,588 | 41.057018 | 139 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/configs/Builder.java | package tsml.classifiers.distance_based.utils.classifiers.configs;
import java.io.Serializable;
public interface Builder<A> extends Serializable {
A build();
}
| 166 | 19.875 | 66 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/configs/ClassifierBuilder.java | package tsml.classifiers.distance_based.utils.classifiers.configs;
import tsml.classifiers.TSClassifier;
public interface ClassifierBuilder<A extends TSClassifier> extends Builder<A> {
}
| 189 | 26.142857 | 79 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/configs/Config.java | package tsml.classifiers.distance_based.utils.classifiers.configs;
import java.util.Objects;
/**
* A config is targeted at a specific class, e.g. Proximity Tree. Then, given an object which is Proximity Tree or more specialised (extends PT) this config can configure it. Similarly, the default builder in this config may create instances which are Proximity Tree or more specialised (extends PT). The configurer may configure Proximity Tree or any class super to PT, e.g. configuring something in EAC say. This is fine because we know we always have at least a PT and at most something that extends PT, so a configurer which acts on anything in the inheritance hierarchy above PT is fine.
* @param <A>
*/
public class Config<A> implements Builder<A>, Configurer<A> {
public Config(final String name, final String description, final Builder<? extends A> template,
final Configurer<? super A> configurer) {
this.name = Objects.requireNonNull(name);
this.description = description == null ? "" : description;
this.template = Objects.requireNonNull(template);
this.configurer = Objects.requireNonNull(configurer);
if(name.length() == 0) {
throw new IllegalArgumentException("empty name not allowed");
}
}
private final String name;
private final String description;
/**
* Builds a default instance which the configuration can then be applied to. I.e. take Proximity Forest. This method would return a new PF instance with r=5, say. During the build() or configure() method, the r=5 is changed to r=10, say, as defined by this configuration setting. Thus this method just returns a fresh instance which has default parameters, etc, set and this configuration has not been applied.
* @return
*/
private final Builder<? extends A> template;
private final Configurer<? super A> configurer;
public void configure(A obj) {
configurer.configure(obj);
}
public final A build() {
final A inst = template.build();
configure(inst);
return inst;
}
public String name() {
return name;
}
public String description() {
return description;
}
@Override public String toString() {
return name;
}
}
| 2,307 | 42.54717 | 592 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/configs/Configs.java | package tsml.classifiers.distance_based.utils.classifiers.configs;
import tsml.classifiers.distance_based.utils.collections.iteration.TransformIterator;
import java.io.Serializable;
import java.util.*;
/**
* A set of configs are targeted at a specific type, say PT for example. Each config is mapped by name to create a factory which can produce fresh instances of that type, e.g. PT.
* @param <A>
*/
public class Configs<A> implements Iterable<Config<A>>, Serializable {
private final Map<String, Config<A>> map = new TreeMap<>(); // using treemap to maintain ordering of names
private void put(String name, Config<A> config) {
name = name.toUpperCase();
if(map.containsKey(name)) {
throw new IllegalArgumentException("mapping for " + name + " already exists");
}
map.put(name, config);
}
public void add(String alias, String target) {
final Config<A> config = get(target);
put(alias, new Config<>(alias, config.description(), config, config));
}
public void add(String name, String description, Builder<? extends A> template, Configurer<? super A> configurer) {
add(new Config<>(name, description, template, configurer));
}
public void add(String name, String description, String templateName, Configurer<? super A> configurer) {
final Config<A> template = get(templateName);
add(name, template.description() + ". " + description, template, (Configurer<A>) obj -> {
// configure the template
template.configure(obj);
// then apply the specialisation config over the template
configurer.configure(obj);
});
}
public void add(Config<A> config) {
put(config.name(), config);
}
public Config<A> remove(String name) {
return map.remove(name.toUpperCase());
}
public Config<A> get(String name) {
final Config<A> config = map.get(name.toUpperCase());
if(config == null) {
throw new IllegalArgumentException(name + " not found");
}
return config;
}
public void configure(String name, A obj) {
get(name).configure(obj);
}
public A build(String name) {
return get(name).build();
}
public boolean contains(String name) {
return map.containsKey(name.toUpperCase());
}
public Set<String> keySet() {
return Collections.unmodifiableSet(map.keySet());
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
final ArrayList<String> names = new ArrayList<>(keySet());
for(int i = 0; i < names.size(); i++) {
final Config<A> config = get(names.get(i));
sb.append(config);
if(i < names.size() - 1) {
sb.append(System.lineSeparator());
}
}
return sb.toString();
}
public Configs<A> immutable() {
final Configs<A> current = this;
return new Configs<A>() {
@Override public void add(final String name, final String description, final Builder<? extends A> template,
final Configurer<? super A> configurer) {
throw new UnsupportedOperationException();
}
@Override public void add(final String name, final String description, final String templateName,
final Configurer<? super A> configurer) {
throw new UnsupportedOperationException();
}
@Override public void add(final Config<A> config) {
throw new UnsupportedOperationException();
}
@Override public Config<A> remove(final String name) {
throw new UnsupportedOperationException();
}
@Override public Config<A> get(final String name) {
return current.get(name);
}
@Override public A build(final String name) {
return current.build(name);
}
@Override public Set<String> keySet() {
return current.keySet();
}
@Override public String toString() {
return current.toString();
}
@Override public Configs<A> immutable() {
return this;
}
};
}
public Map<String, Builder<A>> toBuilderMap() {
final HashMap<String, Builder<A>> map = new HashMap<>();
for(Config<A> config : this) {
map.put(config.name(), config);
}
return map;
}
@Override public Iterator<Config<A>> iterator() {
return new TransformIterator<>(keySet().iterator(), this::get);
}
}
| 4,808 | 32.629371 | 179 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/configs/Configurer.java | package tsml.classifiers.distance_based.utils.classifiers.configs;
import weka.classifiers.Classifier;
import java.io.Serializable;
public interface Configurer<A> extends Serializable {
void configure(A obj);
}
| 221 | 16.076923 | 66 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/contracting/ContractedTest.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.classifiers.distance_based.utils.classifiers.contracting;
import tsml.classifiers.TestTimeContractable;
public interface ContractedTest extends TimedTest, TestTimeContractable {
long getTestTimeLimit();
default boolean hasTestTimeLimit() {
return getTestTimeLimit() > 0;
}
default boolean insideTestTimeLimit(long nanos) {
return !hasTestTimeLimit() || nanos < getTestTimeLimit();
}
}
| 1,202 | 33.371429 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/contracting/ContractedTrain.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.classifiers.distance_based.utils.classifiers.contracting;
import tsml.classifiers.TrainTimeContractable;
import tsml.classifiers.TrainTimeable;
public interface ContractedTrain extends TrainTimeContractable, TimedTrain, ProgressiveBuild {
/**
* Is the classifier fully built? This is irrelevant of contract timings and is instead a reflection of whether
* work remains and further time could be allocated to the classifier to build the model further.
* @return
*/
@Override boolean isFullyBuilt();
long getTrainTimeLimit();
default boolean hasTrainTimeLimit() {
return getTrainTimeLimit() > 0;
}
/**
*
* @param nanos the amount of time currently taken (or the expectation of how long something will take and thus
* whether there is enough time to complete it). E.g. this could be the current run time of a clsf plus
* the predicted time to do some unit of work to improve the classifier. The result would indicate if
* there's enough time to get this unit of work done within the contract and can therefore be used to
* decide whether to do it in the first place.
* @return
*/
default boolean insideTrainTimeLimit(long nanos) {
return !hasTrainTimeLimit() || nanos < getTrainTimeLimit();
}
default boolean withinTrainContract(long time) {
return insideTrainTimeLimit(time);
}
default long findRemainingTrainTime(long trainTime) {
if(!hasTrainTimeLimit()) {
return Long.MAX_VALUE;
}
final long trainTimeLimit = getTrainTimeLimit();
return trainTimeLimit - trainTime;
}
default long findRemainingTrainTime() {
return findRemainingTrainTime(getRunTime());
}
}
| 2,594 | 37.731343 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/contracting/ProgressiveBuild.java | package tsml.classifiers.distance_based.utils.classifiers.contracting;
public interface ProgressiveBuild {
/**
* Has the classifier been fully built yet?
* @return true == yes, no further work can be done. false == no, more work can be done.
*/
boolean isFullyBuilt();
}
| 296 | 26 | 92 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/contracting/TimedTest.java | package tsml.classifiers.distance_based.utils.classifiers.contracting;
/**
* Purpose: get the test time. Implement if the classifier tracks the time taken to classify.
*
* Contributors: goastler
*/
public interface TimedTest {
long getTestTime();
}
| 258 | 22.545455 | 93 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/contracting/TimedTrain.java | package tsml.classifiers.distance_based.utils.classifiers.contracting;
public interface TimedTrain {
/**
* The total time spent training (i.e. not including checkpointing time / time spent estimating train error)
* @return
*/
default long getTrainTime() {
return getRunTime();
}
/**
* The total run time of the build, including everything and anything
* @return
*/
long getRunTime();
}
| 447 | 22.578947 | 112 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/classifiers/results/ResultUtils.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.classifiers.distance_based.utils.classifiers.results;
import evaluation.storage.ClassifierResults;
import java.util.concurrent.TimeUnit;
import tsml.classifiers.EnhancedAbstractClassifier;
import tsml.classifiers.TSClassifier;
import tsml.classifiers.TrainEstimateTimeable;
import tsml.classifiers.TrainTimeable;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatchable;
import tsml.data_containers.TimeSeriesInstances;
import weka.classifiers.Classifier;
import weka.core.Instances;
import weka.core.OptionHandler;
import weka.core.Randomizable;
public class ResultUtils {
public static void setDataInfo(ClassifierResults results, Instances instances) {
results.setDatasetName(instances.relationName());
}
public static void setDataInfo(ClassifierResults results, TimeSeriesInstances instances) {
results.setDatasetName(instances.getProblemName());
}
public static void setClassifierInfo(ClassifierResults results, TSClassifier classifier) {
// unpack wrapped tsclassifiers (e.g. an SMO wrapped as a TSClassifier). The TSClassifier doesn't implement whatever interfaces SMO does, e.g. Randomizable, therefore would not pickup the seed here for embedding in the results. So we unpack it to the raw classifier instance.
// should the actual classifier be a TSClassifier, this will just return itself.
setClassifierInfo(results, classifier.getClassifier());
}
public static void setClassifierInfo(ClassifierResults results, Classifier classifier) {
if(classifier instanceof EnhancedAbstractClassifier) {
results.setEstimatorName(((EnhancedAbstractClassifier) classifier).getClassifierName());
results.setFoldID(((EnhancedAbstractClassifier) classifier).getSeed());
results.setParas(((EnhancedAbstractClassifier) classifier).getParameters());
results.setErrorEstimateMethod(((EnhancedAbstractClassifier) classifier).getEstimatorMethod());
} else {
results.setEstimatorName(classifier.getClass().getSimpleName());
if(classifier instanceof OptionHandler) {
results.setParas(StrUtils.join(",", ((OptionHandler) classifier).getOptions()));
}
}
if(classifier instanceof Randomizable) {
results.setFoldID(((Randomizable) classifier).getSeed());
}
if(classifier instanceof TrainTimeable) {
results.setBuildTime(((TrainTimeable) classifier).getTrainTime());
results.setErrorEstimateTime(0);
results.setBuildPlusEstimateTime(results.getBuildTime());
results.setTimeUnit(TimeUnit.NANOSECONDS);
}
if(classifier instanceof TrainEstimateTimeable) {
results.setErrorEstimateTime(((TrainEstimateTimeable) classifier).getTrainEstimateTime());
results.setBuildPlusEstimateTime(((TrainEstimateTimeable) classifier).getTrainPlusEstimateTime());
results.setTimeUnit(TimeUnit.NANOSECONDS);
}
if(classifier instanceof MemoryWatchable) {
results.setMemory(((MemoryWatchable) classifier).getMaxMemoryUsage());
}
}
public static void setInfo(ClassifierResults results, final Classifier classifier, final Instances data) {
setDataInfo(results, data);
setClassifierInfo(results, classifier);
}
public static void setInfo(ClassifierResults results, TSClassifier classifier, TimeSeriesInstances data) {
setDataInfo(results, data);
setClassifierInfo(results, classifier);
}
}
| 4,443 | 47.835165 | 283 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/CollectionUtils.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.classifiers.distance_based.utils.collections;
import java.util.*;
import java.util.function.*;
import tsml.classifiers.distance_based.utils.collections.pruned.PrunedMap;
import tsml.classifiers.distance_based.utils.system.random.RandomUtils;
import utilities.Utilities;
import static utilities.ArrayUtilities.unique;
public class CollectionUtils {
private CollectionUtils() {}
public static <A> List<A> concat(Iterable<? extends Collection<A>> iterable) {
final List<A> list = new ArrayList<>();
for(Collection<A> collection : iterable) {
list.addAll(collection);
}
return list;
}
public static ArrayList<Integer> complement(int size, List<Integer> indices) {
indices = unique(indices);
Collections.sort(indices);
int i = 0;
ArrayList<Integer> complement = new ArrayList<>(Math.max(0, size - indices.size()));
for(Integer index : indices) {
for(; i < index; i++) {
complement.add(i);
}
i = index + 1;
}
for(; i < size; i++) {
complement.add(i);
}
return complement;
}
public static <A> ArrayList<A> retainAll(List<A> list, List<Integer> indices, boolean allowReordering) {
return removeAll(list, complement(list.size(), indices), allowReordering);
}
public static <A> A remove(List<A> list, int index, boolean allowReordering) {
final int indexToRemove;
if(allowReordering) {
// rather than removing the element at indexOfIndex and shifting all elements after indexOfIndex down 1, it is more efficient to swap the last element in place of the element being removed and remove the last element. I.e. [1,2,3,4,5] and indexOfIndex=2. Swap in the end element, [1,2,5,4,5], and remove the last element, [1,2,5,4].
indexToRemove = list.size() - 1;
Collections.swap(list, index, indexToRemove);
} else {
indexToRemove = index;
}
return list.remove(indexToRemove);
}
public static <A> A removeUnordered(List<A> list, int index) {
return remove(list, index, true);
}
public static <A> A removeOrdered(List<A> list, int index) {
return remove(list, index, false);
}
public static <A> ArrayList<A> removeAll(List<A> list, List<Integer> indices, boolean allowReordering) {
indices = unique(indices);
final ArrayList<A> removedList = new ArrayList<>(indices.size());
Collections.sort(indices);
for(int i = indices.size() - 1; i >= 0; i--) {
A removed = remove(list, indices.get(i), allowReordering);
removedList.add(removed);
}
return removedList;
}
public static <A> ArrayList<A> removeAllUnordered(List<A> list, List<Integer> indices) {
return removeAll(list, indices, true);
}
public static <A> ArrayList<A> removeAllOrdered(List<A> list, List<Integer> indices) {
return removeAll(list, indices, false);
}
public static <A> ArrayList<A> newArrayList(A... elements) {
final ArrayList<A> list = new ArrayList<>(elements.length);
list.addAll(Arrays.asList(elements));
return list;
}
public static <B> void forEachGroup(int groupSize, List<B> list, Consumer<List<B>> consumer) {
List<B> group;
int i = 0;
int limit = groupSize;
while(i < list.size() && i < limit) {
group = new ArrayList<>();
for(; i < list.size() && i < limit; i++) {
group.add(list.get(i));
}
consumer.accept(group);
limit += groupSize;
}
}
public static <B> void forEachPair(List<B> pairs, BiConsumer<B, B> consumer) {
forEachGroup(2, pairs, pair -> {
if(pair.size() != 2) {
throw new IllegalStateException("expected pair");
}
consumer.accept(pair.get(0), pair.get(1));
});
}
public static <B, A> List<A> convertPairs(List<B> pairs, BiFunction<B, B, A> func) {
List<A> objs = new ArrayList<>();
forEachPair(pairs, (a, b) -> {
final A obj = func.apply(a, b);
objs.add(obj);
});
return objs;
}
public static <A> A get(Iterator<A> iterator, int index) {
if(index < 0) {
throw new ArrayIndexOutOfBoundsException();
}
A result = null;
for(int i = 0; i < index; i++) {
if(!iterator.hasNext()) {
throw new ArrayIndexOutOfBoundsException();
}
result = iterator.next();
}
return result;
}
public static <A> void replace(Set<A> set, A item) {
set.remove(item);
set.add(item);
}
public static <A> void replace(Set<A> set, Collection<A> collection) {
for(A item : collection) {
replace(set, item);
}
}
public static <A> A get(Iterable<A> iterable, int index) {
return get(iterable.iterator(), index);
}
public static <A> int size(Iterator<A> iterator) {
int count = 0;
while (iterator.hasNext()) {
count++;
iterator.next();
}
return count;
}
public static <A> int size(Iterable<A> iterable) {
return size(iterable.iterator());
}
public static <A> void put(A item, Set<A> set) {
boolean result = set.add(item);
if(!result) {
throw new IllegalStateException("already contains item " + item.toString());
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static <A extends Comparable<A>> A best(List<A> collection, Random random) {
return best(collection, random, Comparator.reverseOrder());
}
public static <A> A best(List<A> collection, Random random, Comparator<A> comparator) {
return best(collection, 1, comparator).get(0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static <A> List<A> best(List<A> collection, int numChoices, Comparator<A> comparator) {
final List<Integer> indices = bestIndices(collection, numChoices, comparator);
return Utilities.apply(indices, collection::get);
}
public static <A extends Comparable<A>> List<A> best(List<A> collection, int numChoices) {
return best(collection, numChoices, Comparator.reverseOrder());
}
public static <A extends Comparable<A>> List<A> best(List<A> collection) {
return best(collection, 1, Comparator.reverseOrder());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static <A extends Comparable<A>> int bestIndex(List<A> collection, Random random) {
return bestIndex(collection, random, Comparator.reverseOrder());
}
public static <A> int bestIndex(List<A> collection, Random random, Comparator<A> comparator) {
return bestIndices(collection, 1, comparator).get(0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static <A> List<Integer> bestIndices(List<A> collection, int numChoices, Random random, Comparator<A> comparator) {
final List<Integer> indices = bestIndices(collection, numChoices, comparator);
return RandomUtils.choice(indices, random, numChoices);
}
public static <A extends Comparable<A>> List<Integer> bestIndices(List<A> collection, int numChoices, Random random) {
return bestIndices(collection, numChoices, random, Comparator.reverseOrder());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static <A> List<Integer> bestIndices(List<A> collection, int numChoices, Comparator<A> comparator) {
final PrunedMap<A, Integer> map = new PrunedMap<>(comparator);
map.setLimit(numChoices);
int i = 0;
for(A item : collection) {
map.add(item, i++);
}
return map.valuesList();
}
public static <A extends Comparable<A>> List<Integer> bestIndices(List<A> collection, int numChoices) {
return bestIndices(collection, numChoices, Comparator.reverseOrder());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static <A> List<A> filter(final Iterable<A> collection, final Predicate<A> predicate) {
final ArrayList<A> list = new ArrayList<>();
for(A item : collection) {
if(predicate.test(item)) {
list.add(item);
}
}
return list;
}
}
| 9,816 | 36.045283 | 344 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/CollectionUtilsTest.java | package tsml.classifiers.distance_based.utils.collections;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.complement;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class CollectionUtilsTest {
@Test
public void testComplementOutOfOrder() {
ArrayList<Integer> list = newArrayList(7,5,2,1);
Assert.assertEquals(newArrayList(0,3,4,6,8,9), complement(10, list));
}
@Test
public void testComplement() {
ArrayList<Integer> list = newArrayList(1, 2, 5, 7);
Assert.assertEquals(newArrayList(0,3,4,6,8,9), complement(10, list));
}
@Test
public void testComplementEmpty() {
ArrayList<Integer> list = newArrayList();
Assert.assertEquals(newArrayList(0,1,2,3), complement(4, list));
}
@Test
public void testComplementFull() {
ArrayList<Integer> list = newArrayList(0,1,2,3);
Assert.assertEquals(newArrayList(), complement(4, list));
}
@Test
public void testComplementEdge() {
ArrayList<Integer> list = newArrayList(0,3);
Assert.assertEquals(newArrayList(1,2), complement(4, list));
}
}
| 1,298 | 29.209302 | 93 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/DefaultList.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.classifiers.distance_based.utils.collections;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public interface DefaultList<A>
extends List<A> {
@Override default int size() {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default boolean isEmpty() {
int size = size();
return size == 0;
}
@Override default boolean contains(final Object o) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default Iterator<A> iterator() {
return new Iterator<A>() {
private int i = 0;
private int size = size();
@Override public boolean hasNext() {
return i < size;
}
@Override public A next() {
return get(i++);
}
};
}
@Override default Object[] toArray() {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default <T> T[] toArray(final T[] ts) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default boolean add(final A a) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default boolean remove(final Object o) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default boolean containsAll(final Collection<?> collection) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default boolean addAll(final Collection<? extends A> collection) {
for(A item : collection) {
add(item);
}
return true;
}
@Override default boolean addAll(final int i, final Collection<? extends A> collection) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default boolean removeAll(final Collection<?> collection) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default boolean retainAll(final Collection<?> collection) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default void clear() {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default A get(final int i) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default A set(final int i, final A a) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default void add(final int i, final A a) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default A remove(final int i) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default int indexOf(final Object o) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default int lastIndexOf(final Object o) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default ListIterator<A> listIterator() {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default ListIterator<A> listIterator(final int i) {
throw new UnsupportedOperationException("default method not implemented");
}
@Override default List<A> subList(final int i, final int i1) {
throw new UnsupportedOperationException("default method not implemented");
}
}
| 4,592 | 32.282609 | 93 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/DefaultMap.java | package tsml.classifiers.distance_based.utils.collections;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
public interface DefaultMap<A, B> extends Map<A, B> {
@Override default int size() {
throw new UnsupportedOperationException();
}
@Override default boolean isEmpty() {
return size() == 0;
}
@Override default boolean containsKey(Object o) {
throw new UnsupportedOperationException();
}
@Override default boolean containsValue(Object o) {
throw new UnsupportedOperationException();
}
@Override default B get(Object o) {
throw new UnsupportedOperationException();
}
@Override default B put(A a, B b) {
throw new UnsupportedOperationException();
}
@Override default B remove(Object o) {
throw new UnsupportedOperationException();
}
@Override default void putAll(Map<? extends A, ? extends B> map) {
for(Map.Entry<? extends A, ? extends B> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override default void clear() {
throw new UnsupportedOperationException();
}
@Override default Set<A> keySet() {
throw new UnsupportedOperationException();
}
@Override default Collection<B> values() {
throw new UnsupportedOperationException();
}
@Override default Set<Entry<A, B>> entrySet() {
throw new UnsupportedOperationException();
}
}
| 1,617 | 24.68254 | 73 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/IndexedCollection.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.classifiers.distance_based.utils.collections;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public interface IndexedCollection<A> extends java.util.RandomAccess {
A get(int index);
int size();
}
| 1,039 | 32.548387 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/box/Box.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.classifiers.distance_based.utils.collections.box;
public class Box<E> extends ImmutableBox<E> {
public Box() {
super(null);
}
public Box(final E contents) {
super(contents);
}
@Override public void set(final E contents) {
super.set(contents);
}
}
| 1,075 | 29.742857 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/box/DeferredBox.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.classifiers.distance_based.utils.collections.box;
import java.util.function.Supplier;
/**
* Purpose: defer an operation until needed.
* <p>
* Contributors: goastler
*/
public class DeferredBox<A> {
private final Supplier<A> getter;
private A object;
public DeferredBox(final Supplier<A> getter) {
this.getter = getter;
}
public A get() {
if(object == null) {
object = getter.get();
}
return object;
}
}
| 1,256 | 27.568182 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/box/ImmutableBox.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.classifiers.distance_based.utils.collections.box;
public class ImmutableBox<E> {
protected E contents = null;
public ImmutableBox(E contents) {
set(contents);
}
public E get() {
return contents;
}
protected void set(final E contents) {
this.contents = contents;
}
@Override public String toString() {
return contents.toString();
}
}
| 1,182 | 28.575 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/cache/BiCache.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.classifiers.distance_based.utils.collections.cache;
import java.io.Serializable;
import java.util.HashMap;
import java.util.function.BiFunction;
import java.util.function.Supplier;
public class BiCache<A, B, C> extends Cached implements Serializable {
// todo cache state read / write
private final HashMap<A, HashMap<B, C>> cache = new HashMap<>();
public C getAndPut(A firstKey, B secondKey, Supplier<C> supplier) {
C result = get(firstKey, secondKey);
if(result == null) {
result = supplier.get();
}
put(firstKey, secondKey, result);
return result;
}
public C get(A firstKey, B secondKey) {
C result = null;
HashMap<B, C> subCache = cache.get(firstKey);
if(subCache != null) {
result = subCache.get(secondKey);
}
return result;
}
public void put(A firstKey, B secondkey, C value) {
HashMap<B, C> subCache = cache.computeIfAbsent(firstKey, k -> new HashMap<>());
subCache.put(secondkey, value);
}
public boolean contains(A firstKey, B secondKey) {
return get(firstKey, secondKey) != null;
}
public void clear() {
cache.clear();
}
public boolean remove(A firstKey, B secondKey) {
HashMap<B, C> subCache = cache.get(firstKey);
if(subCache != null) {
C removed = subCache.remove(secondKey);
if(subCache.isEmpty()) {
cache.remove(firstKey);
}
return removed != null;
}
return false;
}
public C computeIfAbsent(A firstKey, B secondKey, BiFunction<A, B, C> function) {
C result = get(firstKey, secondKey);
if(result == null) {
result = function.apply(firstKey, secondKey);
put(firstKey, secondKey, result);
}
return result;
}
}
| 2,662 | 31.084337 | 87 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/cache/Cache.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.classifiers.distance_based.utils.collections.cache;
import java.util.HashMap;
import java.util.Map;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class Cache<A, B> extends Cached {
private final Map<A, B> map = new HashMap<>();
public B get(A key) {
if(isRead()) {
return map.get(key);
} else {
return null;
}
}
public void put(A key, B value) {
if(isWrite()) {
map.put(key, value);
}
}
}
| 1,331 | 27.340426 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/cache/Cached.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.classifiers.distance_based.utils.collections.cache;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public abstract class Cached {
private boolean read = true;
private boolean write = true;
public boolean isWrite() {
return write;
}
public Cached setWrite(final boolean write) {
this.write = write;
return this;
}
public boolean isRead() {
return read;
}
public Cached setRead(final boolean read) {
this.read = read;
return this;
}
public boolean isReadOrWrite() {
return isWrite() || isRead();
}
public boolean isReadAndWrite() {
return isWrite() && isRead();
}
public boolean isReadOnly() {
return isRead() && !isWrite();
}
public boolean isWriteOnly() {
return !isRead() && isWrite();
}
public boolean isOff() {
return !isRead() && !isWrite();
}
}
| 1,762 | 24.550725 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/cache/CachedFunction.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.classifiers.distance_based.utils.collections.cache;
import java.io.Serializable;
import java.util.HashMap;
import java.util.function.Function;
/**
* Purpose: class to cache the result of a function.
* @param <I> the input type of the function.
* @param <O> the output type of the function
*
* Contributors: goastler
*/
public class CachedFunction<I, O> implements Function<I, O>,
Serializable {
private final HashMap<I, O> cache = new HashMap<>();
private Function<I, O> function;
public CachedFunction(final Function<I, O> function) {
this.function = function;
}
public O apply(I input) {
return cache.computeIfAbsent(input, function);
}
public void clear() {
cache.clear();
}
public Function<I, O> getFunction() {
return function;
}
public void setFunction(Function<I, O> function) {
if((function instanceof Serializable)) {
function = (Serializable & Function<I, O>) function::apply;
}
this.function = function;
}
}
| 1,830 | 28.532258 | 76 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.