Search in sources :

Example 1 with NormalMixtureTestData

use of com.amazon.randomcutforest.testutils.NormalMixtureTestData in project random-cut-forest-by-aws by aws.

the class ThresholdedTime method run.

@Override
public void run() throws Exception {
    // Create and populate a random cut forest
    int shingleSize = 4;
    int numberOfTrees = 50;
    int sampleSize = 256;
    Precision precision = Precision.FLOAT_32;
    int dataSize = 4 * sampleSize;
    // change this to try different number of attributes,
    // this parameter is not expected to be larger than 5 for this example
    int baseDimensions = 1;
    int count = 0;
    int dimensions = baseDimensions * shingleSize;
    ThresholdedRandomCutForest forest = new ThresholdedRandomCutForest.Builder<>().compact(true).dimensions(dimensions).randomSeed(0).numberOfTrees(numberOfTrees).shingleSize(shingleSize).sampleSize(sampleSize).internalShinglingEnabled(true).precision(precision).anomalyRate(0.01).forestMode(ForestMode.TIME_AUGMENTED).normalizeTime(true).build();
    long seed = new Random().nextLong();
    double[] data = new double[] { 1.0 };
    System.out.println("seed = " + seed);
    NormalMixtureTestData normalMixtureTestData = new NormalMixtureTestData(10, 50);
    MultiDimDataWithKey dataWithKeys = normalMixtureTestData.generateTestDataWithKey(dataSize, 1, 0);
    /**
     * the anomalies will move from normal -> anomalous -> normal starts from normal
     */
    boolean anomalyState = false;
    int keyCounter = 0;
    for (double[] point : dataWithKeys.data) {
        long time = (long) (1000L * count + Math.floor(10 * point[0]));
        AnomalyDescriptor result = forest.process(data, time);
        if (keyCounter < dataWithKeys.changeIndices.length && count == dataWithKeys.changeIndices[keyCounter]) {
            System.out.print("Sequence " + count + " stamp " + (result.getInternalTimeStamp()) + " CHANGE ");
            if (!anomalyState) {
                System.out.println(" to Distribution 1 ");
            } else {
                System.out.println(" to Distribution 0 ");
            }
            anomalyState = !anomalyState;
            ++keyCounter;
        }
        if (result.getAnomalyGrade() != 0) {
            System.out.print("Sequence " + count + " stamp " + (result.getInternalTimeStamp()) + " RESULT ");
            System.out.print("score " + result.getRCFScore() + ", grade " + result.getAnomalyGrade() + ", ");
            if (result.isExpectedValuesPresent()) {
                if (result.getRelativeIndex() != 0 && result.isStartOfAnomaly()) {
                    System.out.print(-result.getRelativeIndex() + " steps ago, instead of stamp " + result.getPastTimeStamp());
                    System.out.print(", expected timestamp " + result.getExpectedTimeStamp() + " ( " + (result.getPastTimeStamp() - result.getExpectedTimeStamp() + ")"));
                } else {
                    System.out.print("expected " + result.getExpectedTimeStamp() + " ( " + (result.getInternalTimeStamp() - result.getExpectedTimeStamp() + ")"));
                }
            }
            System.out.println();
        }
        ++count;
    }
}
Also used : Random(java.util.Random) Precision(com.amazon.randomcutforest.config.Precision) AnomalyDescriptor(com.amazon.randomcutforest.parkservices.AnomalyDescriptor) NormalMixtureTestData(com.amazon.randomcutforest.testutils.NormalMixtureTestData) MultiDimDataWithKey(com.amazon.randomcutforest.testutils.MultiDimDataWithKey) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest)

Example 2 with NormalMixtureTestData

use of com.amazon.randomcutforest.testutils.NormalMixtureTestData in project random-cut-forest-by-aws by aws.

the class ProtostuffExampleWithDynamicLambda method run.

@Override
public void run() throws Exception {
    // Create and populate a random cut forest
    int dimensions = 4;
    int numberOfTrees = 50;
    int sampleSize = 256;
    Precision precision = Precision.FLOAT_64;
    RandomCutForest forest = RandomCutForest.builder().compact(true).dimensions(dimensions).numberOfTrees(numberOfTrees).sampleSize(sampleSize).precision(precision).build();
    int dataSize = 4 * sampleSize;
    NormalMixtureTestData testData = new NormalMixtureTestData();
    for (double[] point : testData.generateTestData(dataSize, dimensions)) {
        forest.update(point);
    }
    // Convert to an array of bytes and print the size
    RandomCutForestMapper mapper = new RandomCutForestMapper();
    mapper.setSaveExecutorContextEnabled(true);
    Schema<RandomCutForestState> schema = RuntimeSchema.getSchema(RandomCutForestState.class);
    LinkedBuffer buffer = LinkedBuffer.allocate(512);
    byte[] bytes;
    try {
        RandomCutForestState state = mapper.toState(forest);
        bytes = ProtostuffIOUtil.toByteArray(state, schema, buffer);
    } finally {
        buffer.clear();
    }
    System.out.printf("dimensions = %d, numberOfTrees = %d, sampleSize = %d, precision = %s%n", dimensions, numberOfTrees, sampleSize, precision);
    System.out.printf("protostuff size = %d bytes%n", bytes.length);
    // Restore from protostuff and compare anomaly scores produced by the two
    // forests
    RandomCutForestState state2 = schema.newMessage();
    ProtostuffIOUtil.mergeFrom(bytes, state2, schema);
    RandomCutForest forest2 = mapper.toModel(state2);
    double saveLambda = forest.getTimeDecay();
    forest.setTimeDecay(10 * forest.getTimeDecay());
    forest2.setTimeDecay(10 * forest2.getTimeDecay());
    for (int i = 0; i < numberOfTrees; i++) {
        CompactSampler sampler = (CompactSampler) ((SamplerPlusTree) forest.getComponents().get(i)).getSampler();
        CompactSampler sampler2 = (CompactSampler) ((SamplerPlusTree) forest2.getComponents().get(i)).getSampler();
        if (sampler.getMaxSequenceIndex() != sampler2.getMaxSequenceIndex()) {
            throw new IllegalStateException("Incorrect sampler state");
        }
        if (sampler.getMostRecentTimeDecayUpdate() != sampler2.getMostRecentTimeDecayUpdate()) {
            throw new IllegalStateException("Incorrect sampler state");
        }
        if (sampler2.getMostRecentTimeDecayUpdate() != dataSize - 1) {
            throw new IllegalStateException("Incorrect sampler state");
        }
    }
    int testSize = 100;
    double delta = Math.log(sampleSize) / Math.log(2) * 0.05;
    int differences = 0;
    int anomalies = 0;
    for (double[] point : testData.generateTestData(testSize, dimensions)) {
        double score = forest.getAnomalyScore(point);
        double score2 = forest2.getAnomalyScore(point);
        // also scored as an anomaly by the other forest
        if (score > 1 || score2 > 1) {
            anomalies++;
            if (Math.abs(score - score2) > delta) {
                differences++;
            }
        }
        forest.update(point);
        forest2.update(point);
    }
    // first validate that this was a nontrivial test
    if (anomalies == 0) {
        throw new IllegalStateException("test data did not produce any anomalies");
    }
    // validate that the two forests agree on anomaly scores
    if (differences >= 0.01 * testSize) {
        throw new IllegalStateException("restored forest does not agree with original forest");
    }
    System.out.println("Looks good!");
}
Also used : LinkedBuffer(io.protostuff.LinkedBuffer) CompactSampler(com.amazon.randomcutforest.sampler.CompactSampler) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) RandomCutForestState(com.amazon.randomcutforest.state.RandomCutForestState) Precision(com.amazon.randomcutforest.config.Precision) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) NormalMixtureTestData(com.amazon.randomcutforest.testutils.NormalMixtureTestData)

Example 3 with NormalMixtureTestData

use of com.amazon.randomcutforest.testutils.NormalMixtureTestData in project random-cut-forest-by-aws by aws.

the class JsonExample method run.

@Override
public void run() throws Exception {
    // Create and populate a random cut forest
    int dimensions = 4;
    int numberOfTrees = 50;
    int sampleSize = 256;
    Precision precision = Precision.FLOAT_64;
    RandomCutForest forest = RandomCutForest.builder().compact(true).dimensions(dimensions).numberOfTrees(numberOfTrees).sampleSize(sampleSize).precision(precision).build();
    int dataSize = 4 * sampleSize;
    NormalMixtureTestData testData = new NormalMixtureTestData();
    for (double[] point : testData.generateTestData(dataSize, dimensions)) {
        forest.update(point);
    }
    // Convert to JSON and print the number of bytes
    RandomCutForestMapper mapper = new RandomCutForestMapper();
    mapper.setSaveExecutorContextEnabled(true);
    ObjectMapper jsonMapper = new ObjectMapper();
    String json = jsonMapper.writeValueAsString(mapper.toState(forest));
    System.out.printf("dimensions = %d, numberOfTrees = %d, sampleSize = %d, precision = %s%n", dimensions, numberOfTrees, sampleSize, precision);
    System.out.printf("JSON size = %d bytes%n", json.getBytes().length);
    // Restore from JSON and compare anomaly scores produced by the two forests
    RandomCutForest forest2 = mapper.toModel(jsonMapper.readValue(json, RandomCutForestState.class));
    int testSize = 100;
    double delta = Math.log(sampleSize) / Math.log(2) * 0.05;
    int differences = 0;
    int anomalies = 0;
    for (double[] point : testData.generateTestData(testSize, dimensions)) {
        double score = forest.getAnomalyScore(point);
        double score2 = forest2.getAnomalyScore(point);
        // also scored as an anomaly by the other forest
        if (score > 1 || score2 > 1) {
            anomalies++;
            if (Math.abs(score - score2) > delta) {
                differences++;
            }
        }
        forest.update(point);
        forest2.update(point);
    }
    // first validate that this was a nontrivial test
    if (anomalies == 0) {
        throw new IllegalStateException("test data did not produce any anomalies");
    }
    // validate that the two forests agree on anomaly scores
    if (differences >= 0.01 * testSize) {
        throw new IllegalStateException("restored forest does not agree with original forest");
    }
    System.out.println("Looks good!");
}
Also used : Precision(com.amazon.randomcutforest.config.Precision) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) NormalMixtureTestData(com.amazon.randomcutforest.testutils.NormalMixtureTestData) RandomCutForestState(com.amazon.randomcutforest.state.RandomCutForestState) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 4 with NormalMixtureTestData

use of com.amazon.randomcutforest.testutils.NormalMixtureTestData in project random-cut-forest-by-aws by aws.

the class ProtostuffExample method run.

@Override
public void run() throws Exception {
    // Create and populate a random cut forest
    int dimensions = 10;
    int numberOfTrees = 50;
    int sampleSize = 256;
    Precision precision = Precision.FLOAT_32;
    RandomCutForest forest = RandomCutForest.builder().compact(true).dimensions(dimensions).numberOfTrees(numberOfTrees).sampleSize(sampleSize).precision(precision).build();
    int dataSize = 1000 * sampleSize;
    NormalMixtureTestData testData = new NormalMixtureTestData();
    for (double[] point : testData.generateTestData(dataSize, dimensions)) {
        forest.update(point);
    }
    // Convert to an array of bytes and print the size
    RandomCutForestMapper mapper = new RandomCutForestMapper();
    mapper.setSaveExecutorContextEnabled(true);
    Schema<RandomCutForestState> schema = RuntimeSchema.getSchema(RandomCutForestState.class);
    LinkedBuffer buffer = LinkedBuffer.allocate(512);
    byte[] bytes;
    try {
        RandomCutForestState state = mapper.toState(forest);
        bytes = ProtostuffIOUtil.toByteArray(state, schema, buffer);
    } finally {
        buffer.clear();
    }
    System.out.printf("dimensions = %d, numberOfTrees = %d, sampleSize = %d, precision = %s%n", dimensions, numberOfTrees, sampleSize, precision);
    System.out.printf("protostuff size = %d bytes%n", bytes.length);
    // Restore from protostuff and compare anomaly scores produced by the two
    // forests
    RandomCutForestState state2 = schema.newMessage();
    ProtostuffIOUtil.mergeFrom(bytes, state2, schema);
    RandomCutForest forest2 = mapper.toModel(state2);
    int testSize = 100;
    double delta = Math.log(sampleSize) / Math.log(2) * 0.05;
    int differences = 0;
    int anomalies = 0;
    for (double[] point : testData.generateTestData(testSize, dimensions)) {
        double score = forest.getAnomalyScore(point);
        double score2 = forest2.getAnomalyScore(point);
        // also scored as an anomaly by the other forest
        if (score > 1 || score2 > 1) {
            anomalies++;
            if (Math.abs(score - score2) > delta) {
                differences++;
            }
        }
        forest.update(point);
        forest2.update(point);
    }
    // first validate that this was a nontrivial test
    if (anomalies == 0) {
        throw new IllegalStateException("test data did not produce any anomalies");
    }
    // validate that the two forests agree on anomaly scores
    if (differences >= 0.01 * testSize) {
        throw new IllegalStateException("restored forest does not agree with original forest");
    }
    System.out.println("Looks good!");
}
Also used : LinkedBuffer(io.protostuff.LinkedBuffer) Precision(com.amazon.randomcutforest.config.Precision) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) NormalMixtureTestData(com.amazon.randomcutforest.testutils.NormalMixtureTestData) RandomCutForestState(com.amazon.randomcutforest.state.RandomCutForestState)

Example 5 with NormalMixtureTestData

use of com.amazon.randomcutforest.testutils.NormalMixtureTestData in project random-cut-forest-by-aws by aws.

the class DynamicThroughput method run.

@Override
public void run() throws Exception {
    // Create and populate a random cut forest
    int dimensions = 4;
    int numberOfTrees = 50;
    int sampleSize = 256;
    Precision precision = Precision.FLOAT_64;
    int dataSize = 10 * sampleSize;
    NormalMixtureTestData testData = new NormalMixtureTestData();
    // generate data once to eliminate caching issues
    testData.generateTestData(dataSize, dimensions);
    testData.generateTestData(sampleSize, dimensions);
    for (int i = 0; i < 5; i++) {
        RandomCutForest forest = RandomCutForest.builder().compact(true).dimensions(dimensions).randomSeed(0).numberOfTrees(numberOfTrees).sampleSize(sampleSize).precision(precision).build();
        RandomCutForest forest2 = RandomCutForest.builder().compact(true).dimensions(dimensions).randomSeed(0).numberOfTrees(numberOfTrees).sampleSize(sampleSize).precision(precision).build();
        forest2.setBoundingBoxCacheFraction(i * 0.25);
        int anomalies = 0;
        for (double[] point : testData.generateTestData(dataSize, dimensions)) {
            double score = forest.getAnomalyScore(point);
            double score2 = forest2.getAnomalyScore(point);
            if (Math.abs(score - score2) > 1e-10) {
                anomalies++;
            }
            forest.update(point);
            forest2.update(point);
        }
        Instant start = Instant.now();
        for (double[] point : testData.generateTestData(sampleSize, dimensions)) {
            double score = forest.getAnomalyScore(point);
            double score2 = forest2.getAnomalyScore(point);
            if (Math.abs(score - score2) > 1e-10) {
                anomalies++;
            }
            forest.update(point);
            forest2.update(point);
        }
        Instant finish = Instant.now();
        // first validate that this was a nontrivial test
        if (anomalies > 0) {
            throw new IllegalStateException("score mismatch");
        }
        System.out.println("So far so good! Caching fraction = " + (i * 0.25) + ", Time =" + Duration.between(start, finish).toMillis() + " ms (note only one forest is changing)");
    }
}
Also used : Precision(com.amazon.randomcutforest.config.Precision) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) Instant(java.time.Instant) NormalMixtureTestData(com.amazon.randomcutforest.testutils.NormalMixtureTestData)

Aggregations

NormalMixtureTestData (com.amazon.randomcutforest.testutils.NormalMixtureTestData)20 Precision (com.amazon.randomcutforest.config.Precision)8 RandomCutForest (com.amazon.randomcutforest.RandomCutForest)7 Random (java.util.Random)7 Test (org.junit.jupiter.api.Test)6 RandomCutForestMapper (com.amazon.randomcutforest.state.RandomCutForestMapper)5 DiVector (com.amazon.randomcutforest.returntypes.DiVector)4 RandomCutForestState (com.amazon.randomcutforest.state.RandomCutForestState)4 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)4 BeforeAll (org.junit.jupiter.api.BeforeAll)3 AnomalyDescriptor (com.amazon.randomcutforest.parkservices.AnomalyDescriptor)2 ThresholdedRandomCutForest (com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest)2 MultiDimDataWithKey (com.amazon.randomcutforest.testutils.MultiDimDataWithKey)2 LinkedBuffer (io.protostuff.LinkedBuffer)2 ArgumentsSource (org.junit.jupiter.params.provider.ArgumentsSource)2 ConditionalSampleSummary (com.amazon.randomcutforest.returntypes.ConditionalSampleSummary)1 CompactSampler (com.amazon.randomcutforest.sampler.CompactSampler)1 ShingleBuilder (com.amazon.randomcutforest.util.ShingleBuilder)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Instant (java.time.Instant)1