Java Code Examples for org.numenta.nupic.Parameters#set()

The following examples show how to use org.numenta.nupic.Parameters#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TemporalMemoryTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
private Parameters getDefaultParameters() {
    Parameters retVal = Parameters.getTemporalDefaultParameters();
    retVal.set(KEY.COLUMN_DIMENSIONS, new int[] { 32 });
    retVal.set(KEY.CELLS_PER_COLUMN, 4);
    retVal.set(KEY.ACTIVATION_THRESHOLD, 3);
    retVal.set(KEY.INITIAL_PERMANENCE, 0.21);
    retVal.set(KEY.CONNECTED_PERMANENCE, 0.5);
    retVal.set(KEY.MIN_THRESHOLD, 2);
    retVal.set(KEY.MAX_NEW_SYNAPSE_COUNT, 3);
    retVal.set(KEY.PERMANENCE_INCREMENT, 0.10);
    retVal.set(KEY.PERMANENCE_DECREMENT, 0.10);
    retVal.set(KEY.PREDICTED_SEGMENT_DECREMENT, 0.0);
    retVal.set(KEY.RANDOM, new UniversalRandom(42));
    retVal.set(KEY.SEED, 42);
    
    return retVal;
}
 
Example 2
Source File: ConnectionsTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Hit the maxSynapsesPerSegment threshold multiple times. Make sure it
 * works more than once.
 */
@Test
public void testReachSegmentLimitMultipleTimes() {
    Parameters p = Parameters.getTemporalDefaultParameters();
    p.set(KEY.COLUMN_DIMENSIONS, new int[] { 32 });
    p.set(KEY.CELLS_PER_COLUMN, 32);
    p.set(KEY.MAX_SEGMENTS_PER_CELL, 2);
    p.set(KEY.MAX_SYNAPSES_PER_SEGMENT, 2);
    
    Connections connections = new Connections();
    p.apply(connections);
    TemporalMemory.init(connections);
    
    DistalDendrite segment = connections.createSegment(connections.getCell(10));
    connections.createSynapse(segment, connections.getCell(201), .85);
    assertEquals(1, connections.numSynapses());
    connections.createSynapse(segment, connections.getCell(202), .9);
    assertEquals(2, connections.numSynapses());
    connections.createSynapse(segment, connections.getCell(203), .8);
    assertEquals(2, connections.numSynapses());
    connections.createSynapse(segment, connections.getCell(204), .8);
    assertEquals(2, connections.numSynapses());
}
 
Example 3
Source File: HTMSensorTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Tests that a meaningful exception is thrown when no date encoder configuration was provided
 */
@Test(expected = IllegalArgumentException.class)
public void testDateEncoderNotInitialized() {
    Publisher manual = Publisher.builder()
        .addHeader("foo")
        .addHeader("datetime")
        .addHeader("T")
        .build();
    Sensor<File> sensor = Sensor.create(ObservableSensor::create, SensorParams.create(
        Keys::obs, "", manual));
    Map<String, Map<String, Object>> fieldEncodings = setupMap( null, 
        25, 
        3, 
        0, 0, 0, 0.1, null, null, null, 
        "consumption", "float", "RandomDistributedScalarEncoder");
    Parameters params = Parameters.getEncoderDefaultParameters();
    params.set(KEY.FIELD_ENCODING_MAP, fieldEncodings);
    HTMSensor<File> htmSensor = (HTMSensor<File>) sensor;
    htmSensor.initEncoder(params);
}
 
Example 4
Source File: RegionTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testAdd() {
    Parameters p = NetworkTestHarness.getParameters();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));
    
    Network n = Network.create("test network", p)
        .add(Network.createRegion("r1")
            .add(Network.createLayer("4", p)
                .add(MultiEncoder.builder().name("").build())));
    
    Region r1 = n.lookup("r1");
    Layer<?>layer4 = r1.lookup("4");
    assertNotNull(layer4);
    assertEquals("r1:4", layer4.getName());
    
    try {
        r1.add(Network.createLayer("4", p));
        fail();
    }catch(Exception e) {
        assertTrue(e.getClass().isAssignableFrom(IllegalArgumentException.class));
        assertEquals("A Layer with the name: 4 has already been added to this Region.", e.getMessage());
    }
}
 
Example 5
Source File: DistalDendriteTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
private Parameters getDefaultParameters() {
    Parameters retVal = Parameters.getTemporalDefaultParameters();
    retVal.set(KEY.COLUMN_DIMENSIONS, new int[] { 32 });
    retVal.set(KEY.CELLS_PER_COLUMN, 4);
    retVal.set(KEY.ACTIVATION_THRESHOLD, 3);
    retVal.set(KEY.INITIAL_PERMANENCE, 0.21);
    retVal.set(KEY.CONNECTED_PERMANENCE, 0.5);
    retVal.set(KEY.MIN_THRESHOLD, 2);
    retVal.set(KEY.MAX_NEW_SYNAPSE_COUNT, 3);
    retVal.set(KEY.PERMANENCE_INCREMENT, 0.10);
    retVal.set(KEY.PERMANENCE_DECREMENT, 0.10);
    retVal.set(KEY.PREDICTED_SEGMENT_DECREMENT, 0.0);
    retVal.set(KEY.RANDOM, new UniversalRandom(42));
    retVal.set(KEY.SEED, 42);
    
    return retVal;
}
 
Example 6
Source File: HTMSensorTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Tests that a meaningful exception is thrown when no geo encoder configuration was provided
 */
@Test(expected = IllegalArgumentException.class)
public void testGeoEncoderNotInitialized() {
    Publisher manual = Publisher.builder()
        .addHeader("foo")
        .addHeader("geo")
        .addHeader("")
        .build();
    Sensor<File> sensor = Sensor.create(ObservableSensor::create, SensorParams.create(
        Keys::obs, "", manual));
    Map<String, Map<String, Object>> fieldEncodings = setupMap( null,
        0, // n
        0, // w
        0, 0, 0, 0, null, null, null,
        "timestamp", "datetime", "DateEncoder");
    Parameters params = Parameters.getEncoderDefaultParameters();
    params.set(KEY.FIELD_ENCODING_MAP, fieldEncodings);
    HTMSensor<File> htmSensor = (HTMSensor<File>) sensor;
    htmSensor.initEncoder(params);
}
 
Example 7
Source File: PlaygroundTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
private Network getLoadedDayOfWeekNetwork() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new FastRandom(42));
    
    Sensor<ObservableSensor<String[]>> sensor = Sensor.create(
        ObservableSensor::create, SensorParams.create(Keys::obs, new Object[] {"name", 
            PublisherSupplier.builder()
                .addHeader("dayOfWeek")
                .addHeader("number")
                .addHeader("B").build() }));
    
    Network network = Network.create("test network", p).add(Network.createRegion("r1")
        .add(Network.createLayer("1", p)
            .alterParameter(KEY.AUTO_CLASSIFY, true)
            .add(Anomaly.create())
            .add(new TemporalMemory())
            .add(new SpatialPooler())
            .add(sensor)));
    
    return network;
}
 
Example 8
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testBasicSetup_SPandTM() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p.set(KEY.RANDOM, new MersenneTwister(42));

    int[][] inputs = new int[7][8];
    inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
    inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
    inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
    inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
    inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
    inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
    inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };

    Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), new TemporalMemory(), null, null);
    TestObserver<Inference> tester;
    l.subscribe(tester = new TestObserver<Inference>() {
        @Override public void onCompleted() {}
        @Override
        public void onNext(Inference i) {
            assertNotNull(i);
            assertTrue(i.getSDR().length > 0);
        }
    });

    // Now push some fake data through so that "onNext" is called above
    l.compute(inputs[0]);
    l.compute(inputs[1]);
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(tester);
}
 
Example 9
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void isClosedAddMultiEncoderTest() {
    Parameters p = NetworkTestHarness.getParameters();
    p = p.union(NetworkTestHarness.getNetworkDemoTestEncoderParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));

    Layer<?> l = Network.createLayer("l", p);
    l.close();

    l.add(MultiEncoder.builder().name("").build());
}
 
Example 10
Source File: RegionTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Test encoder bubbles up to L1
 */
@Test
public void testEncoderPassesUpToTopLayer() {
    Parameters p = NetworkTestHarness.getParameters();
    p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));
    
    Map<String, Object> params = new HashMap<>();
    params.put(KEY_MODE, Mode.PURE);
    
    Network n = Network.create("test network", p)
        .add(Network.createRegion("r1")
            .add(Network.createLayer("1", p)
                .alterParameter(KEY.AUTO_CLASSIFY, Boolean.TRUE))
            .add(Network.createLayer("2", p)
                .add(Anomaly.create(params)))
            .add(Network.createLayer("3", p)
                .add(new TemporalMemory()))
            .add(Network.createLayer("4", p)
                .add(new SpatialPooler())
                .add(MultiEncoder.builder().name("").build())));
    
    Region r1 = n.lookup("r1");
    r1.connect("1", "2").connect("2", "3").connect("3", "4");
    
    assertNotNull(r1.lookup("1").getEncoder());
}
 
Example 11
Source File: TemporalMemoryTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testRecycleWeakestSynapseToMakeRoomForNewSynapse() {
    TemporalMemory tm = new TemporalMemory();
    Connections cn = new Connections();
    Parameters p = getDefaultParameters(null, KEY.CELLS_PER_COLUMN, 1);
    p.set(KEY.COLUMN_DIMENSIONS, new int[] { 100 });
    p = getDefaultParameters(p, KEY.MIN_THRESHOLD, 1);
    p = getDefaultParameters(p, KEY.PERMANENCE_INCREMENT, 0.02);
    p = getDefaultParameters(p, KEY.PERMANENCE_DECREMENT, 0.02);
    p.set(KEY.MAX_SYNAPSES_PER_SEGMENT, 3);
    p.apply(cn);
    TemporalMemory.init(cn);
    
    assertEquals(3, cn.getMaxSynapsesPerSegment());
    
    int[] prevActiveColumns = { 0, 1, 2 };
    Set<Cell> prevWinnerCells = cn.getCellSet(new int[] { 0, 1, 2 });
    int[] activeColumns = { 4 };
    
    DistalDendrite matchingSegment = cn.createSegment(cn.getCell(4));
    cn.createSynapse(matchingSegment, cn.getCell(81), 0.6);
    // Weakest Synapse
    cn.createSynapse(matchingSegment, cn.getCell(0), 0.11);
    
    ComputeCycle cc = tm.compute(cn, prevActiveColumns, true);
    assertEquals(prevWinnerCells, cc.winnerCells);
    tm.compute(cn, activeColumns, true);
    
    List<Synapse> synapses = cn.getSynapses(matchingSegment);
    assertEquals(3, synapses.size());
    Set<Cell> presynapticCells = synapses.stream().map(s -> s.getPresynapticCell()).collect(Collectors.toSet());
    assertFalse(presynapticCells.stream().mapToInt(cell -> cell.getIndex()).anyMatch(i -> i == 0));
}
 
Example 12
Source File: AbstractAlgorithmBenchmark.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Create and return a {@link Parameters} object.
 * 
 * @return
 */
protected Parameters getParameters() {
    Parameters parameters = Parameters.getAllDefaultParameters();
    parameters.set(KEY.INPUT_DIMENSIONS, new int[] { 8 });
    parameters.set(KEY.COLUMN_DIMENSIONS, new int[] { 2048 });
    parameters.set(KEY.CELLS_PER_COLUMN, 32);

    //SpatialPooler specific
    parameters.set(KEY.POTENTIAL_RADIUS, 12);//3
    parameters.set(KEY.POTENTIAL_PCT, 0.5);//0.5
    parameters.set(KEY.GLOBAL_INHIBITION, false);
    parameters.set(KEY.LOCAL_AREA_DENSITY, -1.0);
    parameters.set(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 5.0);
    parameters.set(KEY.STIMULUS_THRESHOLD, 1.0);
    parameters.set(KEY.SYN_PERM_INACTIVE_DEC, 0.01);
    parameters.set(KEY.SYN_PERM_ACTIVE_INC, 0.1);
    parameters.set(KEY.SYN_PERM_TRIM_THRESHOLD, 0.05);
    parameters.set(KEY.SYN_PERM_CONNECTED, 0.1);
    parameters.set(KEY.MIN_PCT_OVERLAP_DUTY_CYCLES, 0.1);
    parameters.set(KEY.MIN_PCT_ACTIVE_DUTY_CYCLES, 0.1);
    parameters.set(KEY.DUTY_CYCLE_PERIOD, 10);
    parameters.set(KEY.MAX_BOOST, 10.0);
    parameters.set(KEY.SEED, 42);
    
    //Temporal Memory specific
    parameters.set(KEY.INITIAL_PERMANENCE, 0.4);
    parameters.set(KEY.CONNECTED_PERMANENCE, 0.5);
    parameters.set(KEY.MIN_THRESHOLD, 4);
    parameters.set(KEY.MAX_NEW_SYNAPSE_COUNT, 4);
    parameters.set(KEY.PERMANENCE_INCREMENT, 0.05);
    parameters.set(KEY.PERMANENCE_DECREMENT, 0.05);
    parameters.set(KEY.ACTIVATION_THRESHOLD, 4);

    return parameters;
}
 
Example 13
Source File: ConnectionsTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a segment, creates a number of synapses on it, destroys a
 * synapse, and makes sure it got destroyed.
 */
@Test
public void testDestroySynapse() {
    Parameters retVal = Parameters.getTemporalDefaultParameters();
    retVal.set(KEY.COLUMN_DIMENSIONS, new int[] { 32 });
    retVal.set(KEY.CELLS_PER_COLUMN, 4);
    
    Connections connections = new Connections();

    retVal.apply(connections);
    TemporalMemory.init(connections);
    
    Cell cell20 = connections.getCell(20);
    DistalDendrite segment = connections.createSegment(cell20);
    Synapse synapse1 = connections.createSynapse(segment, connections.getCell(80), 0.85);
    Synapse synapse2 = connections.createSynapse(segment, connections.getCell(81), 0.85);
    Synapse synapse3 = connections.createSynapse(segment, connections.getCell(82), 0.15);
    
    assertEquals(3, connections.numSynapses());
    
    connections.destroySynapse(synapse2);
    
    assertEquals(2, connections.numSynapses());
    assertEquals(Arrays.asList(synapse1, synapse3), 
        connections.getSynapses(segment));
    
    Activity activity = connections.computeActivity(
        IntStream.rangeClosed(80, 82).mapToObj(i -> connections.getCell(i)).collect(Collectors.toList()),
            0.5D);
    
    assertEquals(1, activity.numActiveConnected[segment.getIndex()]);
    assertEquals(2, activity.numActivePotential[segment.getIndex()]);
}
 
Example 14
Source File: NetworkDemoHarness.java    From htm.java-examples with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns Encoder parameters for the "dayOfWeek" test encoder.
 * @return
 */
public static Parameters getDayDemoTestEncoderParams() {
    Map<String, Map<String, Object>> fieldEncodings = getDayDemoFieldEncodingMap();

    Parameters p = Parameters.getEncoderDefaultParameters();
    p.set(KEY.FIELD_ENCODING_MAP, fieldEncodings);

    return p;
}
 
Example 15
Source File: NetworkDemoHarness.java    From htm.java-examples with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns Encoder parameters and meta information for the "Hot Gym" encoder
 * @return
 */
public static Parameters getHotGymTestEncoderParams() {
    Map<String, Map<String, Object>> fieldEncodings = getHotGymFieldEncodingMap();

    Parameters p = Parameters.getEncoderDefaultParameters();
    p.set(KEY.FIELD_ENCODING_MAP, fieldEncodings);

    return p;
}
 
Example 16
Source File: ExtensiveTemporalMemoryTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Orphan Decay mechanism reduce predicted inactive cells (extra predictions).
 * Test feeds in noisy sequences (X = 0.05) to TM with and without orphan decay.
 * TM with orphan decay should has many fewer predicted inactive columns.
 * Parameters the same as B11, and sequences like H9.
 */
@Test
public void testH10() {
    // train TM on noisy sequences with orphan decay turned off
    Parameters p = Parameters.empty();
    p.set(KEY.CELLS_PER_COLUMN, 4);
    p.set(KEY.ACTIVATION_THRESHOLD, 8);
    init(p, PATTERN_MACHINE);
    
    assertTrue(tm.getConnections().getPredictedSegmentDecrement() == 0);
    
    // Instead of implementing the Python "shuffle" method, just use the exact output
    Integer[] shuffledNums = new Integer[] { 
        0, 17, 15, 1, 8, 5, 11, 3, 18, 16, 40, 41, 42, 43, 44, 12, 7, 10, 14, 6, -1, 
        39, 36, 35, 25, 24, 32, 34, 27, 23, 26, 40, 41, 42, 43, 44, 28, 37, 31, 20, 21, -1           
    };
    
    List<Integer> numberList = Arrays.asList(shuffledNums);
    List<Set<Integer>> sequence = sequenceMachine.generateFromNumbers(numberList);
     
    List<List<Set<Integer>>> sequenceNoisy = new ArrayList<>();
    for(int i = 0;i < 10;i++) {
        sequenceNoisy.add(sequenceMachine.addSpatialNoise(sequence, 0.05));
        feedTM(sequenceNoisy.get(i), "", true, 1);
    }
    
    testTM(sequence, "");
    
    IndicesTrace predictedInactiveTrace = tm.mmGetTracePredictedInactiveColumns();
    Metric predictedInactiveColumnsMetric = tm.mmGetMetricFromTrace(predictedInactiveTrace);
    double predictedInactiveColumnsMean1 = predictedInactiveColumnsMetric.mean;
    
    p = Parameters.empty();
    p.set(KEY.CELLS_PER_COLUMN, 4);
    p.set(KEY.ACTIVATION_THRESHOLD, 8);
    p.set(KEY.PREDICTED_SEGMENT_DECREMENT, 0.04);
    init(p, PATTERN_MACHINE);
    
    assertTrue(tm.getConnections().getPredictedSegmentDecrement() == 0.04);
    
    for(int i = 0;i < 10;i++) {
        feedTM(sequenceNoisy.get(0), "", true, 1);
    }
    
    testTM(sequence, "");
    
    predictedInactiveTrace = tm.mmGetTracePredictedInactiveColumns();
    predictedInactiveColumnsMetric = tm.mmGetMetricFromTrace(predictedInactiveTrace);
    double predictedInactiveColumnsMean2 = predictedInactiveColumnsMetric.mean;
    
    assertTrue(predictedInactiveColumnsMean1 > 0);
    assertTrue(predictedInactiveColumnsMean1 > predictedInactiveColumnsMean2);
}
 
Example 17
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testMakeClassifiers() {
    // Setup Parameters
    Parameters p = Parameters.getAllDefaultParameters();
    Map<String, Class<? extends Classifier>> inferredFieldsMap = new HashMap<>();
    inferredFieldsMap.put("field1", CLAClassifier.class);
    inferredFieldsMap.put("field2", SDRClassifier.class);
    inferredFieldsMap.put("field3", null);
    p.set(KEY.INFERRED_FIELDS, inferredFieldsMap);

    // Create MultiEncoder and add the fields' encoders to it
    MultiEncoder me = MultiEncoder.builder().name("").build();
    me.addEncoder(
            "field1",
            RandomDistributedScalarEncoder.builder().resolution(1).build()
    );
    me.addEncoder(
            "field2",
            RandomDistributedScalarEncoder.builder().resolution(1).build()
    );
    me.addEncoder(
            "field3",
            RandomDistributedScalarEncoder.builder().resolution(1).build()
    );

    // Create a Layer with Parameters and MultiEncoder
    Layer<Map<String, Object>> l = new Layer<>(
            p,
            me,
            new SpatialPooler(),
            new TemporalMemory(),
            true,
            null
    );

    // Make sure the makeClassifiers() method matches each
    // field to the specified Classifier type
    NamedTuple nt = l.makeClassifiers(l.getEncoder());
    assertEquals(nt.get("field1").getClass(), CLAClassifier.class);
    assertEquals(nt.get("field2").getClass(), SDRClassifier.class);
    assertEquals(nt.get("field3"), null);
}
 
Example 18
Source File: NetworkTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Test that a null {@link Assembly.Mode} results in exception
 */
@Test
public void testFluentBuildSemantics() {
    Parameters p = NetworkTestHarness.getParameters();
    p = p.union(NetworkTestHarness.getNetworkDemoTestEncoderParams());
    p.set(KEY.RANDOM, new MersenneTwister(42));
    
    Map<String, Object> anomalyParams = new HashMap<>();
    anomalyParams.put(KEY_MODE, Mode.LIKELIHOOD);
    
    try {
        // Idea: Build up ResourceLocator paths in fluent style such as:
        // Layer.using(
        //     ResourceLocator.addPath("...") // Adds a search path for later mentioning terminal resources (i.e. files)
        //         .addPath("...")
        //         .addPath("..."))
        //     .add(new SpatialPooler())
        //     ...
        Network.create("test network", p)   // Add Network.add() method for chaining region adds
            .add(Network.createRegion("r1")             // Add version of createRegion(String name) for later connecting by name
                .add(Network.createLayer("2/3", p)      // so that regions can be added and connecting in one long chain.
                    .using(new Connections())           // Test adding connections before elements which use them
                    .add(Sensor.create(FileSensor::create, SensorParams.create(
                        Keys::path, "", ResourceLocator.path("rec-center-hourly.csv"))))
                    .add(new SpatialPooler())
                    .add(new TemporalMemory())
                    .add(Anomaly.create(anomalyParams))
            )
                .add(Network.createLayer("1", p)            // Add another Layer, and the Region internally connects it to the 
                    .add(new SpatialPooler())               // previously added Layer
                    .using(new Connections())               // Test adding connections after one element and before another
                    .add(new TemporalMemory())
                    .add(Anomaly.create(anomalyParams))
            ))            
            .add(Network.createRegion("r2")
                .add(Network.createLayer("2/3", p)
                    .add(new SpatialPooler())
                    .using(new Connections()) // Test adding connections after one element and before another
                    .add(new TemporalMemory())
                    .add(Anomaly.create(anomalyParams))
            ))
            .add(Network.createRegion("r3")
                .add(Network.createLayer("1", p)
                    .add(new SpatialPooler())
                    .add(new TemporalMemory())
                    .add(Anomaly.create(anomalyParams))
                        .using(new Connections()) // Test adding connections after elements which use them.
            ))
            
            .connect("r1", "r2")
            .connect("r2", "r3");
    }catch(Exception e) {
        e.printStackTrace();
    }
    
}
 
Example 19
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Test that the Anomaly Func can compute anomalies when no SpatialPooler
 * is present and the input is an int[] representing pre-processed sparse
 * SP output.
 */
@Test
public void testTM_Only_AnomalyCompute() {
    UniversalRandom random = new UniversalRandom(42);
    // SP and General
    Parameters parameters = NetworkTestHarness.getParameters();
    parameters.set(KEY.INPUT_DIMENSIONS, new int[] { 104 });
    parameters.set(KEY.COLUMN_DIMENSIONS, new int[] { 2048 });
    parameters.set(KEY.CELLS_PER_COLUMN, 32);
    parameters.set(KEY.RANDOM, random);
    parameters.set(KEY.POTENTIAL_PCT, 0.85);//0.5
    parameters.set(KEY.GLOBAL_INHIBITION, true);
    parameters.set(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 40.0);
    parameters.set(KEY.SYN_PERM_INACTIVE_DEC, 0.0005);
    parameters.set(KEY.SYN_PERM_ACTIVE_INC, 0.0015);
    parameters.set(KEY.DUTY_CYCLE_PERIOD, 1000);
    parameters.set(KEY.MAX_BOOST, 2.0);
    // TM
    parameters.set(KEY.PERMANENCE_INCREMENT, 0.1);//0.05
    parameters.set(KEY.PERMANENCE_DECREMENT, 0.1);//0.05
    
    Network network = Network.create("NAB Network", parameters)
        .add(Network.createRegion("NAB Region")
            .add(Network.createLayer("NAB Layer", parameters)
                .add(Anomaly.create())
                .add(new TemporalMemory())));
    
    Object[] testResults = new Object[2];
    
    network.observe().subscribe((inference) -> {
        double score = inference.getAnomalyScore();
        int record = inference.getRecordNum();
        
        if(testResults[0] == null && score < 1.0) {
            testResults[0] = record;
            testResults[1] = score;
        }
    }, (error) -> {
        error.printStackTrace();
    }, () -> {
        // On Complete
    });
    
    int[] input = { 717, 737, 739, 745, 758, 782, 793, 798, 805, 812, 833, 841, 
                    846, 857, 1482, 1515, 1536, 1577, 1578, 1600, 1608, 1612, 1642, 
                    1644, 1645, 1646, 1647, 1648, 1649, 1655, 1661, 1663, 1667, 1669, 
                    1677, 1683, 1688, 1706, 1710, 1720 };
    
    for(int i = 0;i < 100;i++) {
        network.compute(input);
        if(testResults[0] != null) break;
    }
    
    assertEquals(8, testResults[0]);
    assertEquals(0.0, testResults[1]);
}
 
Example 20
Source File: LayerTest.java    From htm.java with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testBasicSetup_TemporalMemory_MANUAL_MODE() {
    Parameters p = NetworkTestHarness.getParameters().copy();
    p.set(KEY.RANDOM, new MersenneTwister(42));

    final int[] input1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
    final int[] input2 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
    final int[] input3 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
    final int[] input4 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 };
    final int[] input5 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 };
    final int[] input6 = new int[] { 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 };
    final int[] input7 = new int[] { 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 };
    final int[][] inputs = { input1, input2, input3, input4, input5, input6, input7 };

    
    Layer<int[]> l = new Layer<>(p, null, null, new TemporalMemory(), null, null);
    
    int timeUntilStable = 600;

    TestObserver<Inference> observer;
    
    l.subscribe(observer = new TestObserver<Inference>() {
        int test = 0;
        @Override
        public void onNext(Inference output) {
            if(seq / 7 >= timeUntilStable) {
                System.out.println("seq: " + (seq) + "  --> " + (test) + "  output = " + Arrays.toString(output.getSDR()) +
                    ", \t\t\t\t cols = " + Arrays.toString(SDR.asColumnIndices(output.getSDR(), l.getConnections().getCellsPerColumn())));
                assertTrue(output.getSDR().length >= 5);
            }
            
            ++seq;
            
            if(test == 6) test = 0;
            else test++;                
        }
    });
    
    // Now push some warm up data through so that "onNext" is called above
    for(int j = 0;j < timeUntilStable;j++) {
        for(int i = 0;i < inputs.length;i++) {
            l.compute(inputs[i]);
        }
    }

    for(int j = 0;j < 2;j++) {
        for(int i = 0;i < inputs.length;i++) {
            l.compute(inputs[i]);
        }
    }
    
    // Check for exception during the TestObserver's onNext() execution.
    checkObserver(observer);
}