├── .gitattributes
├── .gitignore
├── .travis.yml
├── LICENSE.txt
├── NOTICE.txt
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── src
└── main
├── assembly
└── release.xml
└── java
└── org
└── encog
└── examples
├── clustering
└── kmeans
│ └── SimpleKMeans.java
├── gui
├── elementary
│ ├── DisplayPanel.java
│ └── ElementaryExample.java
└── life
│ ├── GameOfLife.java
│ └── WorldPanel.java
├── guide
├── classification
│ └── IrisClassification.java
├── regression
│ └── AutoMPGRegression.java
└── timeseries
│ ├── SunSpotTimeseries.java
│ └── package-info.java
├── ml
├── bayesian
│ ├── BayesianSpam.java
│ ├── SimpleBayesian.java
│ ├── SimpleK2.java
│ └── words
│ │ ├── BayesianSpam.java
│ │ └── BayesianWordAnalyzer.java
├── hmm
│ ├── HMMSimpleContinuous.java
│ ├── HMMSimpleDiscrete.java
│ └── HMMSimpleKMeans.java
├── prg
│ ├── Benchmark.java
│ └── SimpleExpression.java
├── sampling
│ └── SimpleSampling.java
├── tsp
│ ├── City.java
│ ├── anneal
│ │ ├── SolveTSP.java
│ │ └── TSPSimulatedAnnealing.java
│ └── genetic
│ │ ├── SolveTSP.java
│ │ └── TSPScore.java
└── world
│ ├── QLearningPanel.java
│ └── QLearningPattern.java
├── neural
├── adaline
│ └── AdalineDigits.java
├── analyst
│ ├── AnalystExample.java
│ └── AnalystNormalize.java
├── art
│ └── art1
│ │ └── NeuralART1.java
├── bam
│ └── BidirectionalAssociativeMemory.java
├── benchmark
│ ├── ActivationFunctions.java
│ ├── Benchmark.java
│ ├── BenchmarkErrorFunctions.java
│ ├── BinaryVsMemory.java
│ ├── ElliottBenchmark.java
│ ├── ErrorMethod.java
│ ├── FahlmanEncoder.java
│ ├── FreeformBenchmark.java
│ ├── MatrixBenchmark.java
│ ├── MultiBench.java
│ ├── PSOBenchmark.java
│ ├── SimpleBenchmark.java
│ ├── TestConverge.java
│ ├── ThreadCount.java
│ └── WeightInitialization.java
├── boltzmann
│ └── BoltzTSP.java
├── cpn
│ └── RocketCPN.java
├── cross
│ └── CrossValidateSunspot.java
├── csv
│ └── XORCSV.java
├── forest
│ ├── Evaluate.java
│ ├── ForestConfig.java
│ ├── ForestCover.java
│ ├── GenerateData.java
│ └── TrainNetwork.java
├── freeform
│ ├── ConvertToFreeform.java
│ ├── ElmanFreeform.java
│ ├── FreeformCompare.java
│ ├── FreeformOnlineXOR.java
│ ├── FreeformXOR.java
│ └── SkipNeuralNetwork.java
├── gui
│ ├── hopfield
│ │ ├── HopfieldPanel.java
│ │ └── HopfieldPattern.java
│ ├── ocr
│ │ ├── Entry.java
│ │ ├── OCR.java
│ │ ├── Sample.java
│ │ └── SampleData.java
│ ├── predict
│ │ ├── GraphPanel.java
│ │ └── PredictSIN.java
│ └── som
│ │ ├── MapPanel.java
│ │ └── SomColors.java
├── hopfield
│ └── HopfieldAssociate.java
├── image
│ └── ImageNeuralNetwork.java
├── lunar
│ ├── LanderSimulator.java
│ ├── LunarLander.java
│ ├── NeuralPilot.java
│ └── PilotScore.java
├── neat
│ ├── XORNEAT.java
│ └── boxes
│ │ ├── BoxTrialCase.java
│ │ ├── BoxesScore.java
│ │ ├── DisplayBoxes.java
│ │ ├── DisplayBoxesPanel.java
│ │ ├── TrialEvaluation.java
│ │ └── VisualizeBoxesMain.java
├── normalize
│ ├── NormalizeFile.java
│ └── SimpleNormalize.java
├── persist
│ ├── EncogPersistence.java
│ └── Serial.java
├── predict
│ ├── market
│ │ ├── Config.java
│ │ ├── MarketBuildTraining.java
│ │ ├── MarketEvaluate.java
│ │ ├── MarketPredict.java
│ │ ├── MarketPrune.java
│ │ └── MarketTrain.java
│ └── sunspot
│ │ ├── MultiSunspot.java
│ │ ├── PredictSunspot.java
│ │ ├── PredictSunspotElman.java
│ │ └── PredictSunspotSVM.java
├── radial
│ └── MultiRadial.java
├── recurrent
│ ├── elman
│ │ └── ElmanXOR.java
│ └── jordan
│ │ └── JordanXOR.java
├── resume
│ └── TrainResume.java
├── som
│ └── SimpleSOM.java
├── util
│ ├── TemporalXOR.java
│ └── XOR.java
├── xor
│ ├── XORConst.java
│ ├── XORFactory.java
│ ├── XORHelloWorld.java
│ ├── XOROnline.java
│ └── XORPSO.java
├── xorpartial
│ ├── XORPartial.java
│ └── XORPartialAuto.java
└── xorsql
│ └── XORSQL.java
└── proben
├── BenchmarkDefinition.java
├── EncogBenchmarkDefinition.java
├── ProBen.java
├── ProBenData.java
├── ProBenError.java
├── ProBenEvaluate.java
├── ProBenResult.java
├── ProBenResultAccumulator.java
└── ProBenRunner.java
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs eol=crlf
6 | *.java eol=lf
7 | *.sln merge=union
8 | *.csproj merge=union
9 | *.vbproj merge=union
10 | *.fsproj merge=union
11 | *.dbproj merge=union
12 |
13 | # Standard to msysgit
14 | *.doc diff=astextplain
15 | *.DOC diff=astextplain
16 | *.docx diff=astextplain
17 | *.DOCX diff=astextplain
18 | *.dot diff=astextplain
19 | *.DOT diff=astextplain
20 | *.pdf diff=astextplain
21 | *.PDF diff=astextplain
22 | *.rtf diff=astextplain
23 | *.RTF diff=astextplain
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | target/
3 | build/
4 |
5 | *.iml
6 | .DS_Store
7 | .gradle
8 | .idea
9 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - oraclejdk8
4 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffheaton/encog-java-examples/c4372d20f9b62a111c78d068ca2b3926b829ad1a/LICENSE.txt
--------------------------------------------------------------------------------
/NOTICE.txt:
--------------------------------------------------------------------------------
1 | Encog 3.2 Machine Learning Framework
2 | Copyright 2008-2013 Heaton Research, Inc.
3 |
4 | This product includes software developed at
5 | Heaton Research, Inc. (http://www.heatonresearch.com/encog/).
6 |
7 | ====================================================================
8 | LibSVM Copyright
9 | Copyright (c) 2000-2011 Chih-Chung Chang and Chih-Jen Lin
10 | All rights reserved.
11 |
12 | Redistribution and use in source and binary forms, with or without
13 | modification, are permitted provided that the following conditions
14 | are met:
15 |
16 | 1. Redistributions of source code must retain the above copyright
17 | notice, this list of conditions and the following disclaimer.
18 |
19 | 2. Redistributions in binary form must reproduce the above copyright
20 | notice, this list of conditions and the following disclaimer in the
21 | documentation and/or other materials provided with the distribution.
22 |
23 | 3. Neither name of copyright holders nor the names of its contributors
24 | may be used to endorse or promote products derived from this software
25 | without specific prior written permission.
26 |
27 |
28 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 | ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
32 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
33 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
34 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
35 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
37 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
38 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 | =======================================================================
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://travis-ci.org/encog/encog-java-examples)
2 |
3 | Encog Examples 3.3
4 |
5 | The following links will be helpful getting started with Encog.
6 |
7 | Getting Started:
8 |
9 | http://www.heatonresearch.com/wiki/Getting_Started
10 |
11 | Important Links:
12 |
13 | http://www.heatonresearch.com/encog
14 | http://www.heatonresearch.com/wiki
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffheaton/encog-java-examples/c4372d20f9b62a111c78d068ca2b3926b829ad1a/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Sep 29 18:40:51 CDT 2014
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.1-bin.zip
7 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/src/main/assembly/release.xml:
--------------------------------------------------------------------------------
1 |
4 | release
5 |
6 | zip
7 |
8 |
9 |
10 |
11 | ${project.basedir}
12 | /
13 | true
14 |
15 | .settings/**
16 | src/**
17 | .classpath
18 | .project
19 | LICENSE.txt
20 | README.txt
21 | NOTICE.txt
22 | pom.xml
23 | build.xml
24 |
25 |
26 |
27 | ${project.build.directory}
28 | /
29 |
30 | apidocs/**
31 |
32 |
33 |
34 | ${project.build.directory}
35 | /lib
36 |
37 | *-jar-with-dependencies*
38 |
39 |
40 |
41 |
42 |
43 |
44 | /lib
45 | true
46 | false
47 | runtime
48 |
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/clustering/kmeans/SimpleKMeans.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.clustering.kmeans;
25 |
26 | import java.util.Arrays;
27 |
28 | import org.encog.ml.MLCluster;
29 | import org.encog.ml.data.MLDataPair;
30 | import org.encog.ml.data.MLDataSet;
31 | import org.encog.ml.data.basic.BasicMLData;
32 | import org.encog.ml.data.basic.BasicMLDataPair;
33 | import org.encog.ml.data.basic.BasicMLDataSet;
34 | import org.encog.ml.kmeans.KMeansClustering;
35 |
36 | /**
37 | * This example performs a simple KMeans cluster. The numbers are clustered
38 | * into two groups.
39 | */
40 | public class SimpleKMeans {
41 |
42 | /**
43 | * The data to be clustered.
44 | */
45 | public static final double[][] DATA = { { 28, 15, 22 }, { 16, 15, 32 },
46 | { 32, 20, 44 }, { 1, 2, 3 }, { 3, 2, 1 } };
47 |
48 | /**
49 | * The main method.
50 | * @param args Arguments are not used.
51 | */
52 | public static void main(final String args[]) {
53 |
54 | final BasicMLDataSet set = new BasicMLDataSet();
55 |
56 | for (final double[] element : SimpleKMeans.DATA) {
57 | set.add(new BasicMLData(element));
58 | }
59 |
60 | final KMeansClustering kmeans = new KMeansClustering(2, set);
61 |
62 | kmeans.iteration(100);
63 | //System.out.println("Final WCSS: " + kmeans.getWCSS());
64 |
65 | // Display the cluster
66 | int i = 1;
67 | for (final MLCluster cluster : kmeans.getClusters()) {
68 | System.out.println("*** Cluster " + (i++) + " ***");
69 | final MLDataSet ds = cluster.createDataSet();
70 | final MLDataPair pair = BasicMLDataPair.createPair(
71 | ds.getInputSize(), ds.getIdealSize());
72 | for (int j = 0; j < ds.getRecordCount(); j++) {
73 | ds.getRecord(j, pair);
74 | System.out.println(Arrays.toString(pair.getInputArray()));
75 |
76 | }
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/gui/elementary/DisplayPanel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.gui.elementary;
25 |
26 | import java.awt.Dimension;
27 | import java.awt.Graphics;
28 | import java.awt.Image;
29 |
30 | import javax.swing.JPanel;
31 |
32 | public class DisplayPanel extends JPanel {
33 | private Image currentImage;
34 |
35 | public Image getCurrentImage() {
36 | return currentImage;
37 | }
38 |
39 | public void setCurrentImage(Image currentImage) {
40 | this.currentImage = currentImage;
41 | setPreferredSize(new Dimension(this.currentImage.getWidth(null), this.currentImage.getHeight(null)));
42 | repaint();
43 | }
44 |
45 | public void paint(Graphics g)
46 | {
47 | super.paint(g);
48 | if( this.currentImage!=null ) {
49 | g.drawImage(this.currentImage, 0, 0, null);
50 | }
51 | }
52 |
53 |
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/gui/life/WorldPanel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.gui.life;
25 |
26 | import java.awt.Dimension;
27 | import java.awt.Graphics;
28 | import java.awt.Image;
29 |
30 | import javax.swing.JPanel;
31 |
32 | public class WorldPanel extends JPanel {
33 | private Image currentImage;
34 |
35 | public Image getCurrentImage() {
36 | return currentImage;
37 | }
38 |
39 | public void setCurrentImage(Image currentImage) {
40 | this.currentImage = currentImage;
41 | setPreferredSize(new Dimension(this.currentImage.getWidth(null), this.currentImage.getHeight(null)));
42 | repaint();
43 | }
44 |
45 | public void paint(Graphics g)
46 | {
47 | super.paint(g);
48 | if( this.currentImage!=null ) {
49 | g.drawImage(this.currentImage, 0, 0, null);
50 | }
51 | }
52 |
53 |
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/guide/timeseries/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.guide.timeseries;
25 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/ml/bayesian/SimpleBayesian.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.ml.bayesian;
25 |
26 | import org.encog.ml.bayesian.BayesianEvent;
27 | import org.encog.ml.bayesian.BayesianNetwork;
28 | import org.encog.ml.bayesian.EventType;
29 | import org.encog.ml.bayesian.query.enumerate.EnumerationQuery;
30 | import org.encog.ml.bayesian.query.sample.SamplingQuery;
31 |
32 | public class SimpleBayesian {
33 | public static void main(String[] args) {
34 |
35 | // build the bayesian network structure
36 | BayesianNetwork network = new BayesianNetwork();
37 | BayesianEvent rained = network.createEvent("rained");
38 | BayesianEvent evenTemperatures = network.createEvent("temperature");
39 | BayesianEvent gardenGrew = network.createEvent("gardenGrew");
40 | BayesianEvent plentyOfCarrots = network.createEvent("carrots");
41 | BayesianEvent plentyOfTomatoes = network.createEvent("Tomatoes");
42 | network.createDependency(rained, gardenGrew);
43 | network.createDependency(evenTemperatures, gardenGrew);
44 | network.createDependency(gardenGrew, plentyOfCarrots);
45 | network.createDependency(gardenGrew, plentyOfTomatoes);
46 | network.finalizeStructure();
47 |
48 | // build the truth tales
49 | rained.getTable().addLine(0.2, true);
50 | evenTemperatures.getTable().addLine(0.5, true);
51 | gardenGrew.getTable().addLine(0.9, true, true, true);
52 | gardenGrew.getTable().addLine(0.7, true, false, true);
53 | gardenGrew.getTable().addLine(0.5, true, true, false);
54 | gardenGrew.getTable().addLine(0.1, true, false, false);
55 | plentyOfCarrots.getTable().addLine(0.8, true, true);
56 | plentyOfCarrots.getTable().addLine(0.2, true, false);
57 | plentyOfTomatoes.getTable().addLine(0.6, true, true);
58 | plentyOfTomatoes.getTable().addLine(0.1, true, false);
59 |
60 | // validate the network
61 | network.validate();
62 |
63 | // display basic stats
64 | System.out.println(network.toString());
65 | System.out.println("Parameter count: " + network.calculateParameterCount());
66 |
67 | EnumerationQuery query = new EnumerationQuery(network);
68 | //SamplingQuery query = new SamplingQuery(network);
69 | query.defineEventType(rained, EventType.Evidence);
70 | query.defineEventType(evenTemperatures, EventType.Evidence);
71 | query.defineEventType(plentyOfCarrots, EventType.Outcome);
72 | query.setEventValue(rained, true);
73 | query.setEventValue(evenTemperatures, true);
74 | query.setEventValue(plentyOfCarrots, true);
75 | query.execute();
76 | System.out.println(query.toString());
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/ml/bayesian/SimpleK2.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.ml.bayesian;
25 |
26 | import org.encog.ml.bayesian.BayesianNetwork;
27 | import org.encog.ml.bayesian.training.BayesianInit;
28 | import org.encog.ml.bayesian.training.TrainBayesian;
29 | import org.encog.ml.bayesian.training.search.k2.SearchK2;
30 | import org.encog.ml.data.MLDataSet;
31 | import org.encog.ml.data.basic.BasicMLDataSet;
32 |
33 | public class SimpleK2 {
34 |
35 | public static final double DATA[][] = {
36 | { 1, 0, 0 }, // case 1
37 | { 1, 1, 1 }, // case 2
38 | { 0, 0, 1 }, // case 3
39 | { 1, 1, 1 }, // case 4
40 | { 0, 0, 0 }, // case 5
41 | { 0, 1, 1 }, // case 6
42 | { 1, 1, 1 }, // case 7
43 | { 0, 0, 0 }, // case 8
44 | { 1, 1, 1 }, // case 9
45 | { 0, 0, 0 }, // case 10
46 | };
47 |
48 | public static void main(String[] args) {
49 | //String[] labels = { "available", "not" };
50 |
51 | MLDataSet data = new BasicMLDataSet(DATA,null);
52 | BayesianNetwork network = new BayesianNetwork();
53 | network.createEvent("x1");
54 | network.createEvent("x2");
55 | network.createEvent("x3");
56 | network.finalizeStructure();
57 |
58 | TrainBayesian train = new TrainBayesian(network,data,10);
59 | train.setInitNetwork(BayesianInit.InitEmpty);
60 | train.iteration();
61 |
62 | double p = network.performQuery("P(+x2|+x1)");// 0.71
63 | System.out.println("x2 probability : " + network.getEvent("x2").getTable().findLine(1, new int[] {1}));
64 | System.out.println("Calculated P(+x2|+x1): " + p);
65 | System.out.println("Final network structure: " + network.toString());
66 |
67 | //EncogDirectoryPersistence.saveObject(new File("d:\\test.eg"), network);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/ml/bayesian/words/BayesianSpam.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.ml.bayesian.words;
25 |
26 | import org.encog.util.Format;
27 |
28 | public class BayesianSpam {
29 |
30 | public final static String[] SPAM_DATA = {
31 | "offer is secret",
32 | "click secret link",
33 | "secret sports link"
34 | };
35 |
36 | public final static String[] HAM_DATA = {
37 | "play sports today",
38 | "went play sports",
39 | "secret sports event",
40 | "sports is today",
41 | "sports costs money"
42 | };
43 |
44 | public static void test(BayesianWordAnalyzer a, String message) {
45 | double d = a.probability(message);
46 | System.out.println("Probability of \"" + message + "\" being " + a.getClassName() + " is " + Format.formatPercent(d) + " ; " + a.getLastProblem());
47 | }
48 |
49 | public static void testWordClass(BayesianWordAnalyzer a, String word) {
50 | double d = a.probabilityWordClass(word);
51 | System.out.println(a.getLastProblem() + " = " + Format.formatPercent(d));
52 | }
53 |
54 | public static void testWordNotClass(BayesianWordAnalyzer a, String word) {
55 | double d = a.probabilityWordNotClass(word);
56 | System.out.println(a.getLastProblem() + " = " + Format.formatPercent(d));
57 |
58 | }
59 |
60 | public static final void main(String[] args) {
61 | BayesianWordAnalyzer a1 = new BayesianWordAnalyzer(0,"spam",SPAM_DATA,"ham",HAM_DATA);
62 | System.out.println("Using Laplace of 0");
63 | System.out.println("P(" + a1.getClassName() + "): " + Format.formatPercent(a1.getClassProbability()));
64 | System.out.println("P(" + a1.getNotClassName() + "): " + Format.formatPercent(a1.getNotClassProbability()));
65 | testWordClass(a1,"secret");
66 | testWordNotClass(a1,"secret");
67 | test(a1,"secret"); // 0.0
68 | test(a1,"today"); // 0.0
69 | test(a1,"sports"); // 16.67
70 | test(a1,"today is secret"); // 0.0
71 | test(a1,"secret is secret"); // 96.15
72 |
73 | BayesianWordAnalyzer a2 = new BayesianWordAnalyzer(1,"spam",SPAM_DATA,"ham",HAM_DATA);
74 | System.out.println("Using Laplace of 1");
75 | System.out.println("P(" + a2.getClassName() + "): " + Format.formatPercent(a2.getClassProbability()));
76 | System.out.println("P(" + a2.getNotClassName() + "): " + Format.formatPercent(a2.getNotClassProbability()));
77 | testWordClass(a2,"today");
78 | testWordNotClass(a2,"today");
79 | test(a2,"secret"); // 0.0
80 | test(a2,"today");
81 | test(a2,"sports");
82 | test(a2,"today is secret"); // 48.58
83 | test(a2,"secret is secret");
84 | }
85 |
86 |
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/ml/hmm/HMMSimpleContinuous.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.ml.hmm;
25 |
26 | import org.encog.ml.data.MLSequenceSet;
27 | import org.encog.ml.hmm.HiddenMarkovModel;
28 | import org.encog.ml.hmm.alog.KullbackLeiblerDistanceCalculator;
29 | import org.encog.ml.hmm.alog.MarkovGenerator;
30 | import org.encog.ml.hmm.distributions.ContinousDistribution;
31 | import org.encog.ml.hmm.train.bw.TrainBaumWelch;
32 |
33 | /**
34 | * This class is a very simple example of a HMM for a continuous input.
35 | * First, a known HMM is created and output is generated from it. We then
36 | * create a second initial HMM, and use the data generated from the first
37 | * HMM to train it to match the first.
38 | */
39 | public class HMMSimpleContinuous {
40 |
41 | static HiddenMarkovModel buildContHMM()
42 | {
43 | double [] mean1 = {0.25, -0.25};
44 | double [][] covariance1 = { {1, 2}, {1, 4} };
45 |
46 | double [] mean2 = {0.5, 0.25};
47 | double [][] covariance2 = { {4, 2}, {3, 4} };
48 |
49 | HiddenMarkovModel hmm = new HiddenMarkovModel(2);
50 |
51 | hmm.setPi(0, 0.8);
52 | hmm.setPi(1, 0.2);
53 |
54 | hmm.setStateDistribution(0, new ContinousDistribution(mean1,covariance1));
55 | hmm.setStateDistribution(1, new ContinousDistribution(mean2,covariance2));
56 |
57 | hmm.setTransitionProbability(0, 1, 0.05);
58 | hmm.setTransitionProbability(0, 0, 0.95);
59 | hmm.setTransitionProbability(1, 0, 0.10);
60 | hmm.setTransitionProbability(1, 1, 0.90);
61 |
62 | return hmm;
63 | }
64 |
65 | static HiddenMarkovModel buildContInitHMM()
66 | {
67 | double [] mean1 = {0.20, -0.20};
68 | double [][] covariance1 = { {1.3, 2.2}, {1.3, 4.3} };
69 |
70 | double [] mean2 = {0.5, 0.25};
71 | double [][] covariance2 = { {4.1, 2.1}, {3.2, 4.4} };
72 |
73 | HiddenMarkovModel hmm = new HiddenMarkovModel(2);
74 |
75 | hmm.setPi(0, 0.9);
76 | hmm.setPi(1, 0.1);
77 |
78 | hmm.setStateDistribution(0, new ContinousDistribution(mean1,covariance1));
79 | hmm.setStateDistribution(1, new ContinousDistribution(mean2,covariance2));
80 |
81 | hmm.setTransitionProbability(0, 1, 0.10);
82 | hmm.setTransitionProbability(0, 0, 0.90);
83 | hmm.setTransitionProbability(1, 0, 0.15);
84 | hmm.setTransitionProbability(1, 1, 0.85);
85 |
86 | return hmm;
87 | }
88 |
89 | public static void main(String[] args) {
90 |
91 | HiddenMarkovModel hmm = buildContHMM();
92 | HiddenMarkovModel learntHmm = buildContInitHMM();
93 |
94 | MarkovGenerator mg = new MarkovGenerator(hmm);
95 | MLSequenceSet training = mg.generateSequences(200,100);
96 |
97 | TrainBaumWelch bwl = new TrainBaumWelch(learntHmm,training);
98 |
99 | KullbackLeiblerDistanceCalculator klc =
100 | new KullbackLeiblerDistanceCalculator();
101 |
102 | System.out.println("Training Continuous Hidden Markov Model with Baum Welch");
103 |
104 | for(int i=1;i<=10;i++) {
105 | double e = klc.distance(learntHmm, hmm);
106 | System.out.println("Iteration #"+i+": Difference: " + e);
107 | bwl.iteration();
108 | learntHmm = (HiddenMarkovModel)bwl.getMethod();
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/ml/hmm/HMMSimpleDiscrete.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.ml.hmm;
25 |
26 | import org.encog.ml.data.MLSequenceSet;
27 | import org.encog.ml.hmm.HiddenMarkovModel;
28 | import org.encog.ml.hmm.alog.KullbackLeiblerDistanceCalculator;
29 | import org.encog.ml.hmm.alog.MarkovGenerator;
30 | import org.encog.ml.hmm.distributions.DiscreteDistribution;
31 | import org.encog.ml.hmm.train.bw.TrainBaumWelch;
32 |
33 | /**
34 | * This class is a very simple example of a HMM for a discrete input.
35 | * First, a known HMM is created and output is generated from it. We then
36 | * create a second initial HMM, and use the data generated from the first
37 | * HMM to train it to match the first.
38 | */
39 | public class HMMSimpleDiscrete {
40 | static HiddenMarkovModel buildDiscHMM()
41 | {
42 | HiddenMarkovModel hmm =
43 | new HiddenMarkovModel(2, 2);
44 |
45 | hmm.setPi(0, 0.95);
46 | hmm.setPi(1, 0.05);
47 |
48 | hmm.setStateDistribution(0, new DiscreteDistribution(new double[][] { { 0.95, 0.05 } }));
49 | hmm.setStateDistribution(1, new DiscreteDistribution(new double[][] { { 0.20, 0.80 } }));
50 |
51 | hmm.setTransitionProbability(0, 1, 0.05);
52 | hmm.setTransitionProbability(0, 0, 0.95);
53 | hmm.setTransitionProbability(1, 0, 0.10);
54 | hmm.setTransitionProbability(1, 1, 0.90);
55 |
56 | return hmm;
57 | }
58 |
59 | static HiddenMarkovModel buildDiscInitHMM()
60 | {
61 | HiddenMarkovModel hmm = new HiddenMarkovModel(2,2);
62 |
63 | hmm.setPi(0, 0.50);
64 | hmm.setPi(1, 0.50);
65 |
66 | hmm.setStateDistribution(0, new DiscreteDistribution(new double[][] { { 0.8, 0.2 } }));
67 | hmm.setStateDistribution(1, new DiscreteDistribution(new double[][] { { 0.1, 0.9 } }));
68 |
69 | hmm.setTransitionProbability(0, 1, 0.2);
70 | hmm.setTransitionProbability(0, 0, 0.8);
71 | hmm.setTransitionProbability(1, 0, 0.2);
72 | hmm.setTransitionProbability(1, 1, 0.8);
73 |
74 | return hmm;
75 | }
76 |
77 | public static void main(String[] args) {
78 | HiddenMarkovModel hmm = buildDiscHMM();
79 | HiddenMarkovModel learntHmm = buildDiscInitHMM();
80 |
81 | MarkovGenerator mg = new MarkovGenerator(hmm);
82 | MLSequenceSet training = mg.generateSequences(200,100);
83 |
84 | TrainBaumWelch bwl = new TrainBaumWelch(learntHmm,training);
85 |
86 | KullbackLeiblerDistanceCalculator klc =
87 | new KullbackLeiblerDistanceCalculator();
88 |
89 | System.out.println("Training Discrete Hidden Markov Model with Baum Welch");
90 |
91 | for(int i=1;i<=10;i++) {
92 | double e = klc.distance(learntHmm, hmm);
93 | System.out.println("Iteration #"+i+": Difference: " + e);
94 | bwl.iteration();
95 | learntHmm = (HiddenMarkovModel)bwl.getMethod();
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/ml/hmm/HMMSimpleKMeans.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.ml.hmm;
25 |
26 | import org.encog.ml.data.MLSequenceSet;
27 | import org.encog.ml.hmm.HiddenMarkovModel;
28 | import org.encog.ml.hmm.alog.KullbackLeiblerDistanceCalculator;
29 | import org.encog.ml.hmm.alog.MarkovGenerator;
30 | import org.encog.ml.hmm.distributions.DiscreteDistribution;
31 | import org.encog.ml.hmm.train.kmeans.TrainKMeans;
32 |
33 | /**
34 | * This is a simple example of KMeans training for a Hidden Markov Model (HMM).
35 | * First, a known HMM is created and output generated for it. Using this output
36 | * and KMeans we can generate a 2nd hiddem markov model that is very similar to the
37 | * first.
38 | */
39 | public class HMMSimpleKMeans {
40 |
41 | static HiddenMarkovModel buildDiscHMM()
42 | {
43 | HiddenMarkovModel hmm =
44 | new HiddenMarkovModel(2, 2);
45 |
46 | hmm.setPi(0, 0.95);
47 | hmm.setPi(1, 0.05);
48 |
49 | hmm.setStateDistribution(0, new DiscreteDistribution(new double[][] { { 0.95, 0.05 } }));
50 | hmm.setStateDistribution(1, new DiscreteDistribution(new double[][] { { 0.20, 0.80 } }));
51 |
52 | hmm.setTransitionProbability(0, 1, 0.05);
53 | hmm.setTransitionProbability(0, 0, 0.95);
54 | hmm.setTransitionProbability(1, 0, 0.10);
55 | hmm.setTransitionProbability(1, 1, 0.90);
56 |
57 | return hmm;
58 | }
59 |
60 |
61 | public static void main(String[] args) {
62 | HiddenMarkovModel hmm = buildDiscHMM();
63 | HiddenMarkovModel learntHmm = null;
64 |
65 | MarkovGenerator mg = new MarkovGenerator(hmm);
66 | MLSequenceSet training = mg.generateSequences(200,100);
67 |
68 | TrainKMeans trainer = new TrainKMeans(hmm,training);
69 |
70 | KullbackLeiblerDistanceCalculator klc =
71 | new KullbackLeiblerDistanceCalculator();
72 |
73 | System.out.println("Training Hidden Markov Model with KMeans");
74 |
75 | for(int i=1;i<=10;i++) {
76 | trainer.iteration();
77 | learntHmm = (HiddenMarkovModel)trainer.getMethod();
78 | double e = klc.distance(learntHmm, hmm);
79 | System.out.println("Iteration #"+i+": Difference: " + e);
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/ml/prg/Benchmark.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.ml.prg;
25 |
26 | import org.encog.ml.prg.EncogProgram;
27 | import org.encog.util.Stopwatch;
28 |
29 | public class Benchmark {
30 | public static final int MILLION = 1000000;
31 | public static final int COUNT = 10 * MILLION;
32 |
33 | public static void testDirect() {
34 | Stopwatch sw = new Stopwatch();
35 | sw.start();
36 | double d = 0;
37 |
38 | for(double a = 0;a speciesClasses = new ArrayList();
47 | speciesClasses.add(new ClassItem("Iris-setosa",0));
48 | speciesClasses.add(new ClassItem("Iris-versicolor",1));
49 | speciesClasses.add(new ClassItem("Iris-virginica",2));
50 |
51 | analyst.getScript().getProperties().setProperty(ScriptProperties.SETUP_CONFIG_INPUT_HEADERS, true);
52 | analyst.getScript().getProperties().setProperty(ScriptProperties.SETUP_CONFIG_CSV_FORMAT, AnalystFileFormat.DECPNT_COMMA);
53 |
54 | analyst.getScript().setDefaultNormalizedRange(0,1);
55 | analyst.getScript().defineField("sepal_l", FieldDirection.Input, NormalizationAction.Normalize, 0, 100);
56 | analyst.getScript().defineField("sepal_w", FieldDirection.Input, NormalizationAction.Normalize, 0, 100);
57 | analyst.getScript().defineField("petal_l", FieldDirection.Input, NormalizationAction.Normalize, 0, 100);
58 | analyst.getScript().defineField("petal_w", FieldDirection.Input, NormalizationAction.Normalize, 0, 100);
59 | analyst.getScript().defineClass("species", FieldDirection.Output, NormalizationAction.Equilateral, speciesClasses);
60 |
61 | MLDataSet training = analyst.getUtility().loadCSV("/Users/jheaton/iris.csv");
62 | /*for(MLDataPair pair: training) {
63 | System.out.println(pair.toString());
64 | }*/
65 | System.out.println(training.size());
66 |
67 | analyst.save("/Users/jheaton/test.ega");
68 |
69 | ReadCSV csv = new ReadCSV("/Users/jheaton/iris.csv",true,CSVFormat.ENGLISH);
70 | MLData input = new BasicMLData(analyst.determineInputCount());
71 | double[] rawInput = new double[analyst.determineInputFieldCount()];
72 |
73 | while(csv.next()) {
74 | rawInput[0] = csv.getDouble(0);
75 | rawInput[1] = csv.getDouble(1);
76 | rawInput[2] = csv.getDouble(2);
77 | rawInput[3] = csv.getDouble(3);
78 | //analyst.getUtility().prepareInput(rawInput, input);
79 | System.out.println(input.toString());
80 | }
81 |
82 |
83 | } catch(Exception ex) {
84 | ex.printStackTrace();
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/art/art1/NeuralART1.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.art.art1;
25 |
26 | import org.encog.Encog;
27 | import org.encog.ml.data.specific.BiPolarNeuralData;
28 | import org.encog.neural.art.ART1;
29 |
30 | /**
31 | * This example presents a series of 5-value images to an ART1 network.
32 | * ART1 learns new patterns as it goes, and classifies them into groups.
33 | *
34 | * This is based on a an example by Karsten Kutza,
35 | * written in C on 1996-01-24.
36 | * http://www.neural-networks-at-your-fingertips.com
37 | */
38 | public class NeuralART1 {
39 |
40 | public static final int INPUT_NEURONS = 5;
41 | public static final int OUTPUT_NEURONS = 10;
42 |
43 | public static final String[] PATTERN = {
44 | " O ",
45 | " O O",
46 | " O",
47 | " O O",
48 | " O",
49 | " O O",
50 | " O",
51 | " OO O",
52 | " OO ",
53 | " OO O",
54 | " OO ",
55 | "OOO ",
56 | "OO ",
57 | "O ",
58 | "OO ",
59 | "OOO ",
60 | "OOOO ",
61 | "OOOOO",
62 | "O ",
63 | " O ",
64 | " O ",
65 | " O ",
66 | " O",
67 | " O O",
68 | " OO O",
69 | " OO ",
70 | "OOO ",
71 | "OO ",
72 | "OOOO ",
73 | "OOOOO" };
74 |
75 | private boolean[][] input;
76 |
77 | public void setupInput() {
78 | this.input = new boolean[PATTERN.length][INPUT_NEURONS];
79 | for (int n = 0; n < PATTERN.length; n++) {
80 | for (int i = 0; i < INPUT_NEURONS; i++) {
81 | this.input[n][i] = (PATTERN[n].charAt(i) == 'O');
82 | }
83 | }
84 | }
85 |
86 | public void run() {
87 | this.setupInput();
88 | ART1 logic = new ART1(INPUT_NEURONS,OUTPUT_NEURONS);
89 |
90 | for (int i = 0; i < PATTERN.length; i++) {
91 | BiPolarNeuralData in = new BiPolarNeuralData(this.input[i]);
92 | BiPolarNeuralData out = new BiPolarNeuralData(OUTPUT_NEURONS);
93 | logic.compute(in, out);
94 | if (logic.hasWinner()) {
95 | System.out.println(PATTERN[i] + " - " + logic.getWinner());
96 | } else {
97 | System.out.println(PATTERN[i]
98 | + " - new Input and all Classes exhausted");
99 | }
100 | }
101 | }
102 |
103 | public static void main(String[] args) {
104 | NeuralART1 art = new NeuralART1();
105 | art.run();
106 | Encog.getInstance().shutdown();
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/benchmark/Benchmark.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.benchmark;
25 |
26 | import org.encog.ConsoleStatusReportable;
27 | import org.encog.Encog;
28 | import org.encog.util.benchmark.EncogBenchmark;
29 |
30 | /**
31 | * Simple console app that uses the Encog benchmarking class.
32 | * This will print out a number that shows how fast your computer is
33 | * with Encog. The lower the better.
34 | * @author jeff
35 | *
36 | */
37 | public class Benchmark {
38 |
39 | public static void main(final String args[]) {
40 |
41 | final Benchmark b = new Benchmark();
42 | System.out.println("Benchmark result: " + b.run());
43 |
44 | Encog.getInstance().shutdown();
45 | }
46 |
47 | public String run() {
48 | final EncogBenchmark mark = new EncogBenchmark(new ConsoleStatusReportable());
49 | String result = mark.process();
50 |
51 | return result;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/benchmark/BinaryVsMemory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.benchmark;
25 |
26 | import java.io.File;
27 |
28 | import org.encog.Encog;
29 | import org.encog.ml.data.MLDataPair;
30 | import org.encog.ml.data.basic.BasicMLDataPair;
31 | import org.encog.ml.data.basic.BasicMLDataSet;
32 | import org.encog.ml.data.buffer.BufferedMLDataSet;
33 | import org.encog.util.Format;
34 | import org.encog.util.benchmark.Evaluate;
35 | import org.encog.util.benchmark.RandomTrainingFactory;
36 |
37 | public class BinaryVsMemory {
38 | private static int evalMemory()
39 | {
40 | final BasicMLDataSet training = RandomTrainingFactory.generate(1000,
41 | 10000, 10, 10, -1, 1);
42 |
43 | final long start = System.currentTimeMillis();
44 | final long stop = start + (10*Evaluate.MILIS);
45 | int record = 0;
46 |
47 | MLDataPair pair = BasicMLDataPair.createPair(10, 10);
48 |
49 | int iterations = 0;
50 | while( System.currentTimeMillis()=training.getRecordCount() )
54 | record = 0;
55 | }
56 |
57 | System.out.println("In 10 seconds, the memory dataset read " +
58 | Format.formatInteger( iterations) + " records.");
59 |
60 | return iterations;
61 | }
62 |
63 | private static int evalBinary()
64 | {
65 | File file = new File("temp.egb");
66 |
67 | final BasicMLDataSet training = RandomTrainingFactory.generate(1000,
68 | 10000, 10, 10, -1, 1);
69 |
70 | // create the binary file
71 |
72 | file.delete();
73 | BufferedMLDataSet training2 = new BufferedMLDataSet(file);
74 | training2.load(training);
75 |
76 | final long start = System.currentTimeMillis();
77 | final long stop = start + (10*Evaluate.MILIS);
78 | int record = 0;
79 |
80 | MLDataPair pair = BasicMLDataPair.createPair(10, 10);
81 |
82 | int iterations = 0;
83 | while( System.currentTimeMillis()=training2.getRecordCount() )
87 | record = 0;
88 | }
89 |
90 | System.out.println("In 10 seconds, the disk(binary) dataset read " +
91 | Format.formatInteger( iterations) + " records.");
92 | file.delete();
93 | return iterations;
94 | }
95 |
96 | public static void main(String[] args)
97 | {
98 | int memory = evalMemory();
99 | int binary = evalBinary();
100 | System.out.println( "Memory is " + Format.formatInteger(memory/binary) + " times the speed of disk.");
101 | Encog.getInstance().shutdown();
102 | }
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/benchmark/ErrorMethod.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.benchmark;
25 |
26 | import java.util.Arrays;
27 |
28 | import org.encog.mathutil.error.ErrorCalculation;
29 | import org.encog.mathutil.error.ErrorCalculationMode;
30 | import org.encog.mathutil.randomize.RangeRandomizer;
31 | import org.encog.util.Format;
32 |
33 | public class ErrorMethod {
34 |
35 | public static double[] generate(int size, double low, double high) {
36 | double[] result = new double[size];
37 | for(int i=0;i 0.01 && epoch900 ) {
84 | failureCount++;
85 | }
86 | }
87 |
88 | System.out.println("Failed to converge: " + failureCount + "/" + COUNT);
89 | Encog.getInstance().shutdown();
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/benchmark/ThreadCount.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.benchmark;
25 |
26 | import org.encog.Encog;
27 | import org.encog.ml.data.MLDataSet;
28 | import org.encog.neural.networks.BasicNetwork;
29 | import org.encog.neural.networks.layers.BasicLayer;
30 | import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
31 | import org.encog.util.benchmark.RandomTrainingFactory;
32 |
33 | public class ThreadCount {
34 |
35 | public static final int INPUT_COUNT = 40;
36 | public static final int HIDDEN_COUNT = 60;
37 | public static final int OUTPUT_COUNT = 20;
38 |
39 | public static void perform(int thread)
40 | {
41 | long start = System.currentTimeMillis();
42 | final BasicNetwork network = new BasicNetwork();
43 | network.addLayer(new BasicLayer(MultiBench.INPUT_COUNT));
44 | network.addLayer(new BasicLayer(MultiBench.HIDDEN_COUNT));
45 | network.addLayer(new BasicLayer(MultiBench.OUTPUT_COUNT));
46 | network.getStructure().finalizeStructure();
47 | network.reset();
48 |
49 | final MLDataSet training = RandomTrainingFactory.generate(1000,50000,
50 | INPUT_COUNT, OUTPUT_COUNT, -1, 1);
51 |
52 | ResilientPropagation rprop = new ResilientPropagation(network,training);
53 | rprop.setThreadCount(thread);
54 | for(int i=0;i<5;i++)
55 | {
56 | rprop.iteration();
57 | }
58 | long stop = System.currentTimeMillis();
59 | System.out.println("Result with " + thread + " was " + (stop-start));
60 | }
61 |
62 |
63 |
64 | public static void main(String[] args)
65 | {
66 | for(int i=1;i<16;i++)
67 | {
68 | perform(i);
69 | }
70 |
71 | Encog.getInstance().shutdown();
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/csv/XORCSV.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.csv;
25 |
26 | import org.encog.Encog;
27 | import org.encog.ml.data.MLDataSet;
28 | import org.encog.neural.networks.BasicNetwork;
29 | import org.encog.util.csv.CSVFormat;
30 | import org.encog.util.simple.EncogUtility;
31 | import org.encog.util.simple.TrainingSetUtil;
32 |
33 | /**
34 | * XOR: This example is essentially the "Hello World" of neural network
35 | * programming. This example shows how to construct an Encog neural network to
36 | * predict the output from the XOR operator. This example uses resilient
37 | * propagation (RPROP) to train the neural network. RPROP is the best general
38 | * purpose supervised training method provided by Encog.
39 | *
40 | * For the XOR example with RPROP I use 4 hidden neurons. XOR can get by on just
41 | * 2, but often the random numbers generated for the weights are not enough for
42 | * RPROP to actually find a solution. RPROP can have issues on really small
43 | * neural networks, but 4 neurons seems to work just fine.
44 | *
45 | * This example reads the XOR data from a CSV file. This file should be
46 | * something like:
47 | *
48 | * 0,0,0
49 | * 1,0,1
50 | * 0,1,1
51 | * 1,1,0
52 | */
53 | public class XORCSV {
54 |
55 | public static void main(final String args[]) {
56 |
57 | if (args.length == 0) {
58 | System.out.println("Usage:\n\nXORCSV [xor.csv]");
59 | } else {
60 | final MLDataSet trainingSet = TrainingSetUtil.loadCSVTOMemory(
61 | CSVFormat.ENGLISH, args[0], false, 2, 1);
62 | final BasicNetwork network = EncogUtility.simpleFeedForward(2, 4,
63 | 0, 1, true);
64 |
65 | System.out.println();
66 | System.out.println("Training Network");
67 | EncogUtility.trainToError(network, trainingSet, 0.01);
68 |
69 | System.out.println();
70 | System.out.println("Evaluating Network");
71 | EncogUtility.evaluate(network, trainingSet);
72 | }
73 | Encog.getInstance().shutdown();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/forest/TrainNetwork.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.forest;
25 |
26 | import org.encog.EncogError;
27 | import org.encog.ml.data.buffer.BufferedMLDataSet;
28 | import org.encog.neural.networks.BasicNetwork;
29 | import org.encog.persist.EncogDirectoryPersistence;
30 | import org.encog.platformspecific.j2se.TrainingDialog;
31 | import org.encog.util.simple.EncogUtility;
32 |
33 | public class TrainNetwork {
34 |
35 | private ForestConfig config;
36 |
37 | public TrainNetwork(ForestConfig config) {
38 | this.config = config;
39 | }
40 |
41 | public void train(boolean useGUI) {
42 | // load, or create the neural network
43 | BasicNetwork network = null;
44 |
45 | if( !config.getTrainedNetworkFile().exists() ) {
46 | throw new EncogError("Can't find neural network file, please generate data");
47 | }
48 |
49 | network = (BasicNetwork)EncogDirectoryPersistence.loadObject(config.getTrainedNetworkFile());
50 |
51 | // convert training data
52 | System.out.println("Converting training file to binary");
53 |
54 | EncogUtility.convertCSV2Binary(config.getNormalizedDataFile(),
55 | config.getBinaryFile(), network.getInputCount(),
56 | network.getOutputCount(), false);
57 | BufferedMLDataSet trainingSet = new BufferedMLDataSet(
58 | config.getBinaryFile());
59 |
60 |
61 | if (useGUI) {
62 | TrainingDialog.trainDialog(network, trainingSet);
63 | } else {
64 | EncogUtility.trainConsole(network, trainingSet,
65 | config.getTrainingMinutes());
66 | }
67 |
68 | System.out.println("Training complete, saving network...");
69 | EncogDirectoryPersistence.saveObject(config.getTrainedNetworkFile(), network);
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/freeform/ConvertToFreeform.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.freeform;
25 |
26 | import org.encog.Encog;
27 | import org.encog.engine.network.activation.ActivationSigmoid;
28 | import org.encog.ml.data.MLDataSet;
29 | import org.encog.ml.data.basic.BasicMLDataSet;
30 | import org.encog.neural.freeform.FreeformNetwork;
31 | import org.encog.neural.networks.BasicNetwork;
32 | import org.encog.neural.networks.layers.BasicLayer;
33 | import org.encog.util.simple.EncogUtility;
34 |
35 |
36 | public class ConvertToFreeform {
37 |
38 | /**
39 | * The input necessary for XOR.
40 | */
41 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
42 | { 0.0, 1.0 }, { 1.0, 1.0 } };
43 |
44 | /**
45 | * The ideal data necessary for XOR.
46 | */
47 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
48 |
49 | /**
50 | * The main method.
51 | * @param args No arguments are used.
52 | */
53 | public static void main(final String args[]) {
54 |
55 | // create a neural network, without using a factory
56 | BasicNetwork network = new BasicNetwork();
57 | network.addLayer(new BasicLayer(null,true,2));
58 | network.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
59 | network.addLayer(new BasicLayer(new ActivationSigmoid(),false,1));
60 | network.getStructure().finalizeStructure();
61 | network.reset();
62 |
63 | // create training data
64 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
65 | EncogUtility.trainToError(network, trainingSet, 0.01);
66 | EncogUtility.evaluate(network, trainingSet);
67 |
68 | FreeformNetwork ff = new FreeformNetwork(network);
69 | EncogUtility.evaluate(ff, trainingSet);
70 |
71 | Encog.getInstance().shutdown();
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/freeform/ElmanFreeform.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.freeform;
25 |
26 | import org.encog.Encog;
27 | import org.encog.engine.network.activation.ActivationSigmoid;
28 | import org.encog.examples.neural.util.TemporalXOR;
29 | import org.encog.ml.CalculateScore;
30 | import org.encog.ml.data.MLDataSet;
31 | import org.encog.ml.train.MLTrain;
32 | import org.encog.ml.train.strategy.Greedy;
33 | import org.encog.ml.train.strategy.HybridStrategy;
34 | import org.encog.ml.train.strategy.StopTrainingStrategy;
35 | import org.encog.neural.freeform.FreeformNetwork;
36 | import org.encog.neural.freeform.training.FreeformBackPropagation;
37 | import org.encog.neural.networks.BasicNetwork;
38 | import org.encog.neural.networks.training.TrainingSetScore;
39 | import org.encog.neural.networks.training.anneal.NeuralSimulatedAnnealing;
40 | import org.encog.neural.pattern.FeedForwardPattern;
41 | import org.encog.util.simple.EncogUtility;
42 |
43 | public class ElmanFreeform {
44 |
45 | public static void main(final String args[]) {
46 |
47 | final TemporalXOR temp = new TemporalXOR();
48 | final MLDataSet trainingSet = temp.generate(120);
49 |
50 | final FreeformNetwork elmanNetwork = FreeformNetwork.createElman(1, 6, 1, new ActivationSigmoid());
51 | final FreeformNetwork feedforwardNetwork = FreeformNetwork.createFeedforward(1, 6, 0, 1, new ActivationSigmoid());
52 |
53 | double feedforwardError = trainNetwork("feedforward",feedforwardNetwork,trainingSet);
54 | double elmanError = trainNetwork("elman",elmanNetwork,trainingSet);
55 |
56 | System.out.println("Best error rate with Elman Network: " + elmanError);
57 | System.out.println("Best error rate with Feedforward Network: "
58 | + feedforwardError);
59 | System.out
60 | .println("Elman should be able to get into the 10% range,\nfeedforward should not go below 25%.\nThe recurrent Elment net can learn better in this case.");
61 | System.out
62 | .println("If your results are not as good, try rerunning, or perhaps training longer.");
63 |
64 | Encog.getInstance().shutdown();
65 | }
66 |
67 | public static double trainNetwork(final String what,
68 | final FreeformNetwork network, final MLDataSet trainingSet) {
69 | CalculateScore score = new TrainingSetScore(trainingSet);
70 |
71 | final MLTrain trainAlt = new NeuralSimulatedAnnealing(
72 | network, score, 10, 2, 100);
73 |
74 | final MLTrain trainMain = new FreeformBackPropagation(network, trainingSet,0.00001, 0.0);
75 |
76 | final StopTrainingStrategy stop = new StopTrainingStrategy();
77 | trainMain.addStrategy(new Greedy());
78 | trainMain.addStrategy(new HybridStrategy(trainAlt));
79 | trainMain.addStrategy(stop);
80 |
81 | EncogUtility.trainToError(trainMain, 0.01);
82 |
83 | return trainMain.getError();
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/freeform/FreeformCompare.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.freeform;
25 |
26 | import org.encog.engine.network.activation.ActivationSigmoid;
27 | import org.encog.ml.data.MLDataSet;
28 | import org.encog.ml.data.basic.BasicMLDataSet;
29 | import org.encog.ml.train.MLTrain;
30 | import org.encog.neural.freeform.FreeformNetwork;
31 | import org.encog.neural.freeform.training.FreeformBackPropagation;
32 | import org.encog.neural.freeform.training.FreeformResilientPropagation;
33 | import org.encog.neural.networks.BasicNetwork;
34 | import org.encog.neural.networks.layers.BasicLayer;
35 | import org.encog.neural.networks.training.propagation.back.Backpropagation;
36 | import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
37 | import org.encog.util.Format;
38 |
39 | public class FreeformCompare {
40 |
41 | public static final boolean useRPROP = false;
42 | public static final boolean dualHidden = true;
43 | public static final int ITERATIONS = 2;
44 |
45 |
46 | public static BasicNetwork basicNetwork;
47 | public static FreeformNetwork freeformNetwork;
48 |
49 | /**
50 | * The input necessary for XOR.
51 | */
52 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
53 | { 0.0, 1.0 }, { 1.0, 1.0 } };
54 |
55 | /**
56 | * The ideal data necessary for XOR.
57 | */
58 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
59 |
60 | public static void main(String[] args) {
61 |
62 | // create the basic network
63 | basicNetwork = new BasicNetwork();
64 | basicNetwork.addLayer(new BasicLayer(null,true,2));
65 | basicNetwork.addLayer(new BasicLayer(new ActivationSigmoid(),true,2));
66 | if( dualHidden ) {
67 | basicNetwork.addLayer(new BasicLayer(new ActivationSigmoid(),true,3));
68 | }
69 | basicNetwork.addLayer(new BasicLayer(new ActivationSigmoid(),false,1));
70 | basicNetwork.getStructure().finalizeStructure();
71 | basicNetwork.reset();
72 | basicNetwork.reset(1000);
73 |
74 | // create the freeform network
75 | freeformNetwork = new FreeformNetwork(basicNetwork);
76 |
77 | // create training data
78 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
79 |
80 | // create two trainers
81 |
82 | MLTrain freeformTrain;
83 |
84 | if( useRPROP ) {
85 | freeformTrain = new FreeformResilientPropagation(freeformNetwork,trainingSet);
86 | } else {
87 | freeformTrain = new FreeformBackPropagation(freeformNetwork,trainingSet, 0.7, 0.3);
88 | }
89 |
90 | MLTrain basicTrain;
91 |
92 | if( useRPROP ) {
93 | basicTrain = new ResilientPropagation(basicNetwork,trainingSet);
94 | } else {
95 | basicTrain = new Backpropagation(basicNetwork,trainingSet, 0.7, 0.3);
96 | }
97 |
98 | // perform both
99 | for(int i=1;i<=ITERATIONS;i++) {
100 | freeformTrain.iteration();
101 | basicTrain.iteration();
102 | System.out.println("Iteration #" + i + " : "
103 | + "Freeform: " + Format.formatPercent(freeformTrain.getError())
104 | + ", Basic: " + Format.formatPercent(basicTrain.getError()));
105 | }
106 |
107 |
108 |
109 |
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/freeform/FreeformOnlineXOR.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.freeform;
25 |
26 | import org.encog.Encog;
27 | import org.encog.engine.network.activation.ActivationSigmoid;
28 | import org.encog.ml.data.MLDataSet;
29 | import org.encog.ml.data.basic.BasicMLDataSet;
30 | import org.encog.neural.freeform.FreeformLayer;
31 | import org.encog.neural.freeform.FreeformNetwork;
32 | import org.encog.neural.freeform.training.FreeformBackPropagation;
33 | import org.encog.neural.freeform.training.FreeformResilientPropagation;
34 | import org.encog.util.simple.EncogUtility;
35 |
36 |
37 | public class FreeformOnlineXOR {
38 |
39 | /**
40 | * The input necessary for XOR.
41 | */
42 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
43 | { 0.0, 1.0 }, { 1.0, 1.0 } };
44 |
45 | /**
46 | * The ideal data necessary for XOR.
47 | */
48 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
49 |
50 | /**
51 | * The main method.
52 | * @param args No arguments are used.
53 | */
54 | public static void main(final String args[]) {
55 |
56 | // create a neural network, without using a factory
57 | FreeformNetwork network = new FreeformNetwork();
58 | FreeformLayer inputLayer = network.createInputLayer(2);
59 | FreeformLayer hiddenLayer1 = network.createLayer(3);
60 | FreeformLayer outputLayer = network.createOutputLayer(1);
61 |
62 | network.connectLayers(inputLayer, hiddenLayer1, new ActivationSigmoid(), 1.0, false);
63 | network.connectLayers(hiddenLayer1, outputLayer, new ActivationSigmoid(), 1.0, false);
64 | network.reset();
65 |
66 | // create training data
67 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
68 | FreeformBackPropagation train = new FreeformBackPropagation(network,trainingSet, 0.7, 0.2);
69 | train.setBatchSize(1);
70 | EncogUtility.trainToError(train, 0.01);
71 | EncogUtility.evaluate(network, trainingSet);
72 |
73 | Encog.getInstance().shutdown();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/freeform/FreeformXOR.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.freeform;
25 |
26 | import org.encog.Encog;
27 | import org.encog.engine.network.activation.ActivationSigmoid;
28 | import org.encog.ml.data.MLDataSet;
29 | import org.encog.ml.data.basic.BasicMLDataSet;
30 | import org.encog.neural.freeform.FreeformLayer;
31 | import org.encog.neural.freeform.FreeformNetwork;
32 | import org.encog.util.simple.EncogUtility;
33 |
34 |
35 | public class FreeformXOR {
36 |
37 | /**
38 | * The input necessary for XOR.
39 | */
40 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
41 | { 0.0, 1.0 }, { 1.0, 1.0 } };
42 |
43 | /**
44 | * The ideal data necessary for XOR.
45 | */
46 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
47 |
48 | /**
49 | * The main method.
50 | * @param args No arguments are used.
51 | */
52 | public static void main(final String args[]) {
53 |
54 | // create a neural network, without using a factory
55 | FreeformNetwork network = new FreeformNetwork();
56 | FreeformLayer inputLayer = network.createInputLayer(2);
57 | FreeformLayer hiddenLayer1 = network.createLayer(3);
58 | FreeformLayer outputLayer = network.createOutputLayer(1);
59 |
60 | network.connectLayers(inputLayer, hiddenLayer1, new ActivationSigmoid(), 1.0, false);
61 | network.connectLayers(hiddenLayer1, outputLayer, new ActivationSigmoid(), 1.0, false);
62 |
63 | network.reset();
64 |
65 | // create training data
66 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
67 | EncogUtility.trainToError(network, trainingSet, 0.01);
68 | EncogUtility.evaluate(network, trainingSet);
69 |
70 | Encog.getInstance().shutdown();
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/freeform/SkipNeuralNetwork.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.freeform;
25 |
26 | import org.encog.Encog;
27 | import org.encog.engine.network.activation.ActivationSigmoid;
28 | import org.encog.ml.data.MLDataSet;
29 | import org.encog.ml.data.basic.BasicMLDataSet;
30 | import org.encog.neural.freeform.FreeformLayer;
31 | import org.encog.neural.freeform.FreeformNetwork;
32 | import org.encog.util.simple.EncogUtility;
33 |
34 |
35 | public class SkipNeuralNetwork {
36 |
37 | /**
38 | * The input necessary for XOR.
39 | */
40 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
41 | { 0.0, 1.0 }, { 1.0, 1.0 } };
42 |
43 | /**
44 | * The ideal data necessary for XOR.
45 | */
46 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
47 |
48 | /**
49 | * The main method.
50 | * @param args No arguments are used.
51 | */
52 | public static void main(final String args[]) {
53 |
54 | // create a neural network, without using a factory
55 | FreeformNetwork network = new FreeformNetwork();
56 | FreeformLayer inputLayer = network.createInputLayer(2);
57 | FreeformLayer hiddenLayer1 = network.createLayer(3);
58 | FreeformLayer outputLayer = network.createOutputLayer(1);
59 |
60 | network.connectLayers(inputLayer, hiddenLayer1, new ActivationSigmoid(), 1.0, false);
61 | network.connectLayers(hiddenLayer1, outputLayer, new ActivationSigmoid(), 1.0, false);
62 | network.connectLayers(inputLayer, outputLayer, new ActivationSigmoid(), 0.0, false);
63 |
64 | network.reset();
65 |
66 | // create training data
67 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
68 | //MLTrain train = new FreeformBackPropagation(network, trainingSet, 0.7, 0.3);
69 | //EncogUtility.trainToError(train, 0.01);
70 | EncogUtility.trainToError(network, trainingSet, 0.01);
71 | EncogUtility.evaluate(network, trainingSet);
72 |
73 | Encog.getInstance().shutdown();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/gui/hopfield/HopfieldPattern.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.gui.hopfield;
25 |
26 | import java.awt.BorderLayout;
27 | import java.awt.Container;
28 | import java.awt.event.ActionEvent;
29 | import java.awt.event.ActionListener;
30 |
31 | import javax.swing.JButton;
32 | import javax.swing.JFrame;
33 | import javax.swing.JPanel;
34 |
35 | /**
36 | * This GUI application displays a grid that is used to train a Hopfield
37 | * neural network. To make use of this application draw small localized
38 | * patterns on the grid and click train once each pattern has been drawn.
39 | * The grid can be cleared between patterns. Each pattern should be
40 | * trained. TO test, draw part of one of the patterns and select "GO".
41 | *
42 | */
43 | public class HopfieldPattern extends JFrame implements ActionListener {
44 |
45 | private HopfieldPanel panel;
46 |
47 | public HopfieldPattern()
48 | {
49 | this.setTitle("Hopfield Pattern");
50 | this.setSize(640, 480);
51 | Container content = this.getContentPane();
52 | content.setLayout(new BorderLayout());
53 |
54 | this.buttonTrain = new JButton("Train");
55 | this.buttonGo = new JButton("Go");
56 | this.buttonClear = new JButton("Clear");
57 | this.buttonClearMatrix = new JButton("Clear Matrix");
58 | this.buttonPanel = new JPanel();
59 | this.buttonPanel.add(this.buttonTrain);
60 | this.buttonPanel.add(this.buttonGo);
61 | this.buttonPanel.add(this.buttonClear);
62 | this.buttonPanel.add(this.buttonClearMatrix);
63 | content.add(this.buttonPanel, BorderLayout.SOUTH);
64 |
65 | this.buttonTrain.addActionListener(this);
66 | this.buttonGo.addActionListener(this);
67 | this.buttonClear.addActionListener(this);
68 | this.buttonClearMatrix.addActionListener(this);
69 |
70 | this.panel = new HopfieldPanel(20,20);
71 | content.add(this.panel, BorderLayout.CENTER);
72 | }
73 |
74 |
75 | private JPanel buttonPanel;
76 | private JButton buttonTrain;
77 | private JButton buttonGo;
78 | private JButton buttonClear;
79 | private JButton buttonClearMatrix;
80 |
81 | public void actionPerformed(final ActionEvent e) {
82 | if (e.getSource() == this.buttonClear) {
83 | this.panel.clear();
84 | } else if (e.getSource() == this.buttonClearMatrix) {
85 | this.panel.clearMatrix();
86 | } else if (e.getSource() == this.buttonGo) {
87 | this.panel.go();
88 | } else if (e.getSource() == this.buttonTrain) {
89 | this.panel.train();
90 | }
91 | }
92 |
93 |
94 |
95 | public static void main(String[] args)
96 | {
97 | HopfieldPattern program = new HopfieldPattern();
98 | program.setVisible(true);
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/gui/ocr/Sample.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.gui.ocr;
25 |
26 | import java.awt.Color;
27 | import java.awt.Graphics;
28 |
29 | import javax.swing.JPanel;
30 |
31 | /**
32 | * Sample: GUI element that displays sampled data.
33 | */
34 | public class Sample extends JPanel {
35 |
36 | /**
37 | * Serial id for this class.
38 | */
39 | private static final long serialVersionUID = 2250441617163548592L;
40 | /**
41 | * The image data.
42 | */
43 | SampleData data;
44 |
45 | /**
46 | * The constructor.
47 | *
48 | * @param width
49 | * The width of the downsampled image
50 | * @param height
51 | * The height of the downsampled image
52 | */
53 | Sample(final int width, final int height) {
54 | this.data = new SampleData(' ', width, height);
55 | }
56 |
57 | /**
58 | * The image data object.
59 | *
60 | * @return The image data object.
61 | */
62 | SampleData getData() {
63 | return this.data;
64 | }
65 |
66 | /**
67 | * @param g
68 | * Display the downsampled image.
69 | */
70 | @Override
71 | public void paint(final Graphics g) {
72 | if (this.data == null) {
73 | return;
74 | }
75 |
76 | int x, y;
77 | final int vcell = getHeight() / this.data.getHeight();
78 | final int hcell = getWidth() / this.data.getWidth();
79 |
80 | g.setColor(Color.white);
81 | g.fillRect(0, 0, getWidth(), getHeight());
82 |
83 | g.setColor(Color.black);
84 | for (y = 0; y < this.data.getHeight(); y++) {
85 | g.drawLine(0, y * vcell, getWidth(), y * vcell);
86 | }
87 | for (x = 0; x < this.data.getWidth(); x++) {
88 | g.drawLine(x * hcell, 0, x * hcell, getHeight());
89 | }
90 |
91 | for (y = 0; y < this.data.getHeight(); y++) {
92 | for (x = 0; x < this.data.getWidth(); x++) {
93 | if (this.data.getData(x, y)) {
94 | g.fillRect(x * hcell, y * vcell, hcell, vcell);
95 | }
96 | }
97 | }
98 |
99 | g.setColor(Color.black);
100 | g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
101 |
102 | }
103 |
104 | /**
105 | * Assign a new image data object.
106 | *
107 | * @param data
108 | * The image data object.
109 | */
110 |
111 | void setData(final SampleData data) {
112 | this.data = data;
113 | }
114 |
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/gui/predict/PredictSIN.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.gui.predict;
25 |
26 | import java.awt.BorderLayout;
27 | import java.awt.Container;
28 | import java.awt.event.ActionEvent;
29 | import java.awt.event.ActionListener;
30 |
31 | import javax.swing.JButton;
32 | import javax.swing.JFrame;
33 |
34 | import org.encog.ml.data.MLDataSet;
35 | import org.encog.ml.train.MLTrain;
36 | import org.encog.neural.networks.BasicNetwork;
37 | import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
38 | import org.encog.util.arrayutil.TemporalWindowArray;
39 | import org.encog.util.simple.EncogUtility;
40 |
41 | /**
42 | * Really simple GUI application that is used to predict the SIN wave.
43 | */
44 | public class PredictSIN extends JFrame implements ActionListener {
45 |
46 | public final static int INPUT_WINDOW = 5;
47 | public final static int PREDICT_WINDOW = 1;
48 | private BasicNetwork network;
49 | private GraphPanel graph;
50 | private MLDataSet trainingData;
51 | private MLTrain train;
52 | private JButton btnTrain;
53 |
54 | public PredictSIN()
55 | {
56 | this.setTitle("SIN Wave Predict");
57 | this.setSize(640, 480);
58 | Container content = this.getContentPane();
59 | content.setLayout(new BorderLayout());
60 | content.add(graph = new GraphPanel(), BorderLayout.CENTER);
61 |
62 | network = EncogUtility.simpleFeedForward(INPUT_WINDOW, PREDICT_WINDOW*2, 0, 1, true);
63 | network.reset();
64 | graph.setNetwork(network);
65 |
66 | this.trainingData = generateTraining();
67 | this.train = new ResilientPropagation(this.network,this.trainingData);
68 | btnTrain = new JButton("Train");
69 | this.btnTrain.addActionListener(this);
70 | content.add(btnTrain,BorderLayout.SOUTH);
71 | graph.setError(network.calculateError(this.trainingData));
72 | }
73 |
74 | public void performTraining()
75 | {
76 | for(int i=0;i<10;i++) {
77 | this.train.iteration();
78 | }
79 | graph.setError(train.getError());
80 |
81 | }
82 |
83 | public MLDataSet generateTraining()
84 | {
85 | TemporalWindowArray temp = new TemporalWindowArray(INPUT_WINDOW,PREDICT_WINDOW);
86 |
87 | double[] a = new double[360];
88 |
89 | for(int i = 0;i<360;i++)
90 | {
91 | a[i] = GraphPanel.obtainActual(i);
92 | }
93 |
94 | temp.analyze(a);
95 | return temp.process(a);
96 | }
97 |
98 |
99 |
100 | public static void main(String[] args)
101 | {
102 | PredictSIN program = new PredictSIN();
103 | program.setVisible(true);
104 | }
105 |
106 | public void actionPerformed(ActionEvent e) {
107 | performTraining();
108 | this.graph.refresh();
109 | }
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/gui/som/MapPanel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.gui.som;
25 |
26 | import java.awt.Color;
27 | import java.awt.Graphics;
28 |
29 | import javax.swing.JPanel;
30 |
31 | import org.encog.mathutil.matrices.Matrix;
32 |
33 | public class MapPanel extends JPanel {
34 |
35 | /**
36 | *
37 | */
38 | private static final long serialVersionUID = 7528474872067939033L;
39 | public static final int CELL_SIZE = 8;
40 | public static final int WIDTH = 50;
41 | public static final int HEIGHT = 50;
42 |
43 | private Matrix weights;
44 |
45 | public MapPanel(SomColors som)
46 | {
47 | this.weights = som.getNetwork().getWeights();
48 | }
49 |
50 | private int convertColor(double d)
51 | {
52 | //System.out.println(d);
53 | double result = 128*d;
54 | result+=128;
55 | result = Math.min(result, 255);
56 | result = Math.max(result, 0);
57 | return (int)result;
58 | }
59 |
60 | @Override
61 | public void paint(Graphics g)
62 | {
63 | for(int y = 0; y< HEIGHT; y++)
64 | {
65 | for(int x = 0; x< WIDTH; x++)
66 | {
67 | int index = (y*WIDTH)+x;
68 | int red = convertColor(weights.get(index,0));
69 | int green = convertColor(weights.get(index,1));
70 | int blue = convertColor(weights.get(index,2));
71 | g.setColor(new Color(red,green,blue));
72 | g.fillRect(x*CELL_SIZE, y*CELL_SIZE, CELL_SIZE, CELL_SIZE);
73 | }
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/gui/som/SomColors.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.gui.som;
25 |
26 | import java.util.ArrayList;
27 | import java.util.List;
28 |
29 | import javax.swing.JFrame;
30 |
31 | import org.encog.mathutil.randomize.RangeRandomizer;
32 | import org.encog.mathutil.rbf.RBFEnum;
33 | import org.encog.ml.data.MLData;
34 | import org.encog.ml.data.basic.BasicMLData;
35 | import org.encog.neural.som.SOM;
36 | import org.encog.neural.som.training.basic.BasicTrainSOM;
37 | import org.encog.neural.som.training.basic.neighborhood.NeighborhoodRBF;
38 |
39 | /**
40 | * A classic SOM example that shows how the SOM groups similar color shades.
41 | *
42 | */
43 | public class SomColors extends JFrame implements Runnable {
44 |
45 | /**
46 | *
47 | */
48 | private static final long serialVersionUID = -6762179069967224817L;
49 | private MapPanel map;
50 | private SOM network;
51 | private Thread thread;
52 | private BasicTrainSOM train;
53 | private NeighborhoodRBF gaussian;
54 |
55 | public SomColors() {
56 | this.setSize(640, 480);
57 | this.setDefaultCloseOperation(EXIT_ON_CLOSE);
58 | this.network = createNetwork();
59 | this.getContentPane().add(map = new MapPanel(this));
60 | this.gaussian = new NeighborhoodRBF(RBFEnum.Gaussian,MapPanel.WIDTH,
61 | MapPanel.HEIGHT);
62 | this.train = new BasicTrainSOM(this.network, 0.01, null, gaussian);
63 | train.setForceWinner(false);
64 | this.thread = new Thread(this);
65 | thread.start();
66 | }
67 |
68 | public SOM getNetwork() {
69 | return this.network;
70 | }
71 |
72 | private SOM createNetwork() {
73 | SOM result = new SOM(3,MapPanel.WIDTH * MapPanel.HEIGHT);
74 | result.reset();
75 | return result;
76 | }
77 |
78 | public static void main(String[] args) {
79 | SomColors frame = new SomColors();
80 | frame.setVisible(true);
81 | }
82 |
83 | public void run() {
84 |
85 | List samples = new ArrayList();
86 | for (int i = 0; i < 15; i++) {
87 | MLData data = new BasicMLData(3);
88 | data.setData(0, RangeRandomizer.randomize(-1, 1));
89 | data.setData(1, RangeRandomizer.randomize(-1, 1));
90 | data.setData(2, RangeRandomizer.randomize(-1, 1));
91 | samples.add(data);
92 | }
93 |
94 | this.train.setAutoDecay(1000, 0.8, 0.003, 30, 5);
95 |
96 | for (int i = 0; i < 1000; i++) {
97 | int idx = (int) (Math.random() * samples.size());
98 | MLData c = samples.get(idx);
99 |
100 | this.train.trainPattern(c);
101 | this.train.autoDecay();
102 | this.map.repaint();
103 | System.out.println("Iteration " + i + "," + this.train.toString());
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/lunar/LanderSimulator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.lunar;
25 |
26 | import java.text.NumberFormat;
27 |
28 | public class LanderSimulator {
29 |
30 | public static final double GRAVITY = 1.62;
31 | public static final double THRUST = 10;
32 | public static final double TERMINAL_VELOCITY = 40;
33 |
34 | private int fuel;
35 | private int seconds;
36 | private double altitude;
37 | private double velocity;
38 |
39 | public LanderSimulator() {
40 | this.fuel = 200;
41 | this.seconds = 0;
42 | this.altitude = 10000;
43 | this.velocity = 0;
44 | }
45 |
46 | public void turn(boolean thrust) {
47 | this.seconds++;
48 | this.velocity -= GRAVITY;
49 | this.altitude += this.velocity;
50 |
51 | if (thrust && this.fuel > 0) {
52 | this.fuel--;
53 | this.velocity += THRUST;
54 | }
55 |
56 | this.velocity = Math.max(-TERMINAL_VELOCITY, this.velocity);
57 | this.velocity = Math.min(TERMINAL_VELOCITY, this.velocity);
58 |
59 | if (this.altitude < 0)
60 | this.altitude = 0;
61 | }
62 |
63 | public String telemetry() {
64 | NumberFormat nf = NumberFormat.getNumberInstance();
65 | nf.setMinimumFractionDigits(4);
66 | nf.setMaximumFractionDigits(4);
67 | StringBuilder result = new StringBuilder();
68 | result.append("Elapsed: ");
69 | result.append(seconds);
70 | result.append(" s, Fuel: ");
71 | result.append(this.fuel);
72 | result.append(" l, Velocity: ");
73 | result.append(nf.format(velocity));
74 | result.append(" m/s, ");
75 | result.append((int) altitude);
76 | result.append(" m");
77 | return result.toString();
78 | }
79 |
80 | public int score() {
81 | return (int) ((this.fuel * 10) + this.seconds + (this.velocity * 1000));
82 | }
83 |
84 | public int getFuel() {
85 | return fuel;
86 | }
87 |
88 | public int getSeconds() {
89 | return seconds;
90 | }
91 |
92 | public double getAltitude() {
93 | return altitude;
94 | }
95 |
96 | public double getVelocity() {
97 | return velocity;
98 | }
99 |
100 | public boolean flying() {
101 | return (this.altitude > 0);
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/lunar/LunarLander.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.lunar;
25 |
26 | import org.encog.Encog;
27 | import org.encog.engine.network.activation.ActivationTANH;
28 | import org.encog.ml.MLMethod;
29 | import org.encog.ml.MLResettable;
30 | import org.encog.ml.MethodFactory;
31 | import org.encog.ml.genetic.MLMethodGeneticAlgorithm;
32 | import org.encog.ml.train.MLTrain;
33 | import org.encog.neural.networks.BasicNetwork;
34 | import org.encog.neural.networks.training.anneal.NeuralSimulatedAnnealing;
35 | import org.encog.neural.pattern.FeedForwardPattern;
36 |
37 | /**
38 | * A lunar lander game where the neural network learns to land a space craft.
39 | * The neural network learns the proper amount of thrust to land softly
40 | * and conserve fuel.
41 | *
42 | * This example is unique because it uses supervised training, yet does not
43 | * have expected values. For this it can use genetic algorithms or
44 | * simulated annealing.
45 | */
46 | public class LunarLander {
47 |
48 | public static BasicNetwork createNetwork()
49 | {
50 | FeedForwardPattern pattern = new FeedForwardPattern();
51 | pattern.setInputNeurons(3);
52 | pattern.addHiddenLayer(50);
53 | pattern.setOutputNeurons(1);
54 | pattern.setActivationFunction(new ActivationTANH());
55 | BasicNetwork network = (BasicNetwork)pattern.generate();
56 | network.reset();
57 | return network;
58 | }
59 |
60 | public static void main(String args[])
61 | {
62 | BasicNetwork network = createNetwork();
63 |
64 | MLTrain train;
65 |
66 | if( args.length>0 && args[0].equalsIgnoreCase("anneal"))
67 | {
68 | train = new NeuralSimulatedAnnealing(
69 | network, new PilotScore(), 10, 2, 100);
70 | }
71 | else
72 | {
73 | train = new MLMethodGeneticAlgorithm(new MethodFactory(){
74 | @Override
75 | public MLMethod factor() {
76 | final BasicNetwork result = createNetwork();
77 | ((MLResettable)result).reset();
78 | return result;
79 | }},new PilotScore(),500);
80 | }
81 |
82 | int epoch = 1;
83 |
84 | for(int i=0;i<50;i++) {
85 | train.iteration();
86 | System.out
87 | .println("Epoch #" + epoch + " Score:" + train.getError());
88 | epoch++;
89 | }
90 | train.finishTraining();
91 |
92 | System.out.println("\nHow the winning network landed:");
93 | network = (BasicNetwork)train.getMethod();
94 | NeuralPilot pilot = new NeuralPilot(network,true);
95 | System.out.println(pilot.scorePilot());
96 | Encog.getInstance().shutdown();
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/lunar/NeuralPilot.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.lunar;
25 |
26 | import org.encog.ml.data.MLData;
27 | import org.encog.ml.data.basic.BasicMLData;
28 | import org.encog.neural.networks.BasicNetwork;
29 | import org.encog.util.arrayutil.NormalizationAction;
30 | import org.encog.util.arrayutil.NormalizedField;
31 |
32 | public class NeuralPilot {
33 |
34 | private BasicNetwork network;
35 | private boolean track;
36 | private NormalizedField fuelStats;
37 | private NormalizedField altitudeStats;
38 | private NormalizedField velocityStats;
39 |
40 | public NeuralPilot(BasicNetwork network, boolean track)
41 | {
42 | fuelStats = new NormalizedField(NormalizationAction.Normalize, "fuel", 200, 0, -0.9, 0.9);
43 | altitudeStats = new NormalizedField(NormalizationAction.Normalize, "altitude", 10000, 0, -0.9, 0.9);
44 | velocityStats = new NormalizedField(NormalizationAction.Normalize, "velocity", LanderSimulator.TERMINAL_VELOCITY, -LanderSimulator.TERMINAL_VELOCITY, -0.9, 0.9);
45 |
46 | this.track = track;
47 | this.network = network;
48 | }
49 |
50 | public int scorePilot()
51 | {
52 | LanderSimulator sim = new LanderSimulator();
53 | while(sim.flying())
54 | {
55 | MLData input = new BasicMLData(3);
56 | input.setData(0, this.fuelStats.normalize(sim.getFuel()));
57 | input.setData(1, this.altitudeStats.normalize(sim.getAltitude()));
58 | input.setData(2, this.velocityStats.normalize(sim.getVelocity()));
59 | MLData output = this.network.compute(input);
60 | double value = output.getData(0);
61 |
62 | boolean thrust;
63 |
64 | if( value > 0 )
65 | {
66 | thrust = true;
67 | if( track )
68 | System.out.println("THRUST");
69 | }
70 | else
71 | thrust = false;
72 |
73 | sim.turn(thrust);
74 | if( track )
75 | System.out.println(sim.telemetry());
76 | }
77 | return(sim.score());
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/lunar/PilotScore.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.lunar;
25 |
26 | import org.encog.ml.CalculateScore;
27 | import org.encog.ml.MLMethod;
28 | import org.encog.neural.networks.BasicNetwork;
29 |
30 | public class PilotScore implements CalculateScore {
31 |
32 | @Override
33 | public double calculateScore(MLMethod network) {
34 | NeuralPilot pilot = new NeuralPilot((BasicNetwork)network, false);
35 | return pilot.scorePilot();
36 | }
37 |
38 |
39 | public boolean shouldMinimize() {
40 | return false;
41 | }
42 |
43 |
44 | @Override
45 | public boolean requireSingleThreaded() {
46 | return false;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/neat/XORNEAT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.neat;
25 |
26 | import org.encog.Encog;
27 | import org.encog.ml.CalculateScore;
28 | import org.encog.ml.data.MLDataSet;
29 | import org.encog.ml.data.basic.BasicMLDataSet;
30 | import org.encog.ml.ea.train.EvolutionaryAlgorithm;
31 | import org.encog.neural.neat.NEATNetwork;
32 | import org.encog.neural.neat.NEATPopulation;
33 | import org.encog.neural.neat.NEATUtil;
34 | import org.encog.neural.networks.training.TrainingSetScore;
35 | import org.encog.util.simple.EncogUtility;
36 |
37 | /**
38 | * XOR-NEAT: This example solves the classic XOR operator neural
39 | * network problem. However, it uses a NEAT evolving network.
40 | *
41 | * @author $Author$
42 | * @version $Revision$
43 | */
44 | public class XORNEAT {
45 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
46 | { 0.0, 1.0 }, { 1.0, 1.0 } };
47 |
48 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
49 |
50 | public static void main(final String args[]) {
51 |
52 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
53 | NEATPopulation pop = new NEATPopulation(2,1,1000);
54 | pop.setInitialConnectionDensity(1.0);// not required, but speeds training
55 | pop.reset();
56 |
57 | CalculateScore score = new TrainingSetScore(trainingSet);
58 | // train the neural network
59 |
60 | final EvolutionaryAlgorithm train = NEATUtil.constructNEATTrainer(pop,score);
61 |
62 | do {
63 | train.iteration();
64 | System.out.println("Epoch #" + train.getIteration() + " Error:" + train.getError()+ ", Species:" + pop.getSpecies().size());
65 | } while(train.getError() > 0.01);
66 |
67 | NEATNetwork network = (NEATNetwork)train.getCODEC().decode(train.getBestGenome());
68 |
69 | // test the neural network
70 | System.out.println("Neural Network Results:");
71 | EncogUtility.evaluate(network, trainingSet);
72 |
73 | Encog.getInstance().shutdown();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/neat/boxes/BoxTrialCase.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.neat.boxes;
25 |
26 | import java.util.Random;
27 |
28 | import org.encog.mathutil.IntPair;
29 |
30 | /**
31 | * One case in the boxes score. Position the boxes at random locations.
32 | */
33 | public class BoxTrialCase {
34 |
35 | public static final int BASE_RESOLUTION = 11;
36 | public static final int BOUNDS = BASE_RESOLUTION - 1;
37 |
38 | private IntPair smallBoxTopLeft;
39 | private IntPair largeBoxTopLeft;
40 |
41 | private Random rnd;
42 |
43 | public BoxTrialCase(Random theRnd) {
44 | this.rnd = theRnd;
45 | }
46 |
47 | public IntPair initTestCase(int largeBoxRelativePos) {
48 | IntPair[] loc = generateRandomTestCase(largeBoxRelativePos);
49 | smallBoxTopLeft = loc[0];
50 | largeBoxTopLeft = (IntPair)loc[1].clone();
51 | largeBoxTopLeft.add(-1);
52 | return loc[1];
53 | }
54 |
55 | public double getPixel(double x, double y) {
56 | int pixelX = (int) (((x + 1.0) * BoxTrialCase.BASE_RESOLUTION) / 2.0);
57 | int pixelY = (int) (((y + 1.0) * BoxTrialCase.BASE_RESOLUTION) / 2.0);
58 |
59 | if (smallBoxTopLeft.getX() == pixelX
60 | && smallBoxTopLeft.getY() == pixelY) {
61 | return 1.0;
62 | }
63 |
64 | int deltaX = pixelX - largeBoxTopLeft.getX();
65 | int deltaY = pixelY - largeBoxTopLeft.getY();
66 | return (deltaX > -1 && deltaX < 3 && deltaY > -1 && deltaY < 3) ? 1.0
67 | : 0.0;
68 | }
69 |
70 | private IntPair[] generateRandomTestCase(int largeBoxRelativePos) {
71 | IntPair smallBoxPos = new IntPair(rnd.nextInt(BoxTrialCase.BASE_RESOLUTION),
72 | rnd.nextInt(BoxTrialCase.BASE_RESOLUTION));
73 |
74 | IntPair largeBoxPos = (IntPair) smallBoxPos.clone();
75 | switch (largeBoxRelativePos) {
76 | case 0:
77 | largeBoxPos.addX(5);
78 | break;
79 | case 1:
80 | largeBoxPos.addY(5);
81 | break;
82 | case 2:
83 | if (rnd.nextBoolean()) {
84 | largeBoxPos.add(3, 4);
85 | } else {
86 | largeBoxPos.add(4, 3);
87 | }
88 | break;
89 | }
90 |
91 | if (largeBoxPos.getX() > BoxTrialCase.BOUNDS) {
92 | largeBoxPos.addX(-BoxTrialCase.BASE_RESOLUTION);
93 |
94 | if (0 == largeBoxPos.getX()) {
95 | largeBoxPos.add(1);
96 | }
97 | } else if (BoxTrialCase.BOUNDS == largeBoxPos.getX()) {
98 | largeBoxPos.addX(-1);
99 | } else if (largeBoxPos.getX() == 0) {
100 | largeBoxPos.addX(1);
101 | }
102 |
103 | if (largeBoxPos.getY() > BoxTrialCase.BOUNDS) {
104 | largeBoxPos.addY(-BoxTrialCase.BASE_RESOLUTION);
105 |
106 | if (0 == largeBoxPos.getY()) {
107 | largeBoxPos.addY(1);
108 | }
109 | } else if (BoxTrialCase.BOUNDS == largeBoxPos.getY()) {
110 | largeBoxPos.addY(-1);
111 | } else if (0 == largeBoxPos.getY()) {
112 | largeBoxPos.addY(1);
113 | }
114 | return new IntPair[] { smallBoxPos, largeBoxPos };
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/neat/boxes/DisplayBoxes.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.neat.boxes;
25 |
26 | import java.awt.BorderLayout;
27 | import java.awt.event.ActionEvent;
28 | import java.awt.event.ActionListener;
29 |
30 | import javax.swing.JButton;
31 | import javax.swing.JComboBox;
32 | import javax.swing.JFrame;
33 | import javax.swing.JPanel;
34 |
35 | import org.encog.neural.neat.NEATPopulation;
36 |
37 | /**
38 | * Display the boxes on the screen using Swing.
39 | *
40 | */
41 | public class DisplayBoxes extends JFrame implements ActionListener {
42 | /**
43 | * The serial id.
44 | */
45 | private static final long serialVersionUID = 1L;
46 | public static final String[] RESOLUTIONS = { "11", "22", "33", "44", "55" };
47 | private JComboBox resolution;
48 | private DisplayBoxesPanel display;
49 | private JButton newCase;
50 |
51 | public DisplayBoxes(NEATPopulation thePopulation) {
52 | setSize(400,400);
53 | setLayout(new BorderLayout());
54 | JPanel buttonPanel = new JPanel();
55 | buttonPanel.add(this.resolution=new JComboBox(RESOLUTIONS));
56 | buttonPanel.add(newCase=new JButton("New Case"));
57 | this.add(buttonPanel,BorderLayout.NORTH);
58 | this.display = new DisplayBoxesPanel(thePopulation);
59 | this.add(this.display, BorderLayout.CENTER);
60 |
61 | this.newCase.addActionListener(this);
62 | }
63 |
64 | @Override
65 | public void actionPerformed(ActionEvent evt) {
66 | if( evt.getSource()==this.newCase ) {
67 | this.display.createNewCase(Integer.parseInt(this.resolution.getSelectedItem().toString()));
68 | }
69 | }
70 |
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/neat/boxes/DisplayBoxesPanel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.neat.boxes;
25 |
26 | import java.awt.Color;
27 | import java.awt.Graphics;
28 | import java.util.Random;
29 |
30 | import javax.swing.JPanel;
31 |
32 | import org.encog.mathutil.IntPair;
33 | import org.encog.neural.hyperneat.HyperNEATCODEC;
34 | import org.encog.neural.hyperneat.substrate.Substrate;
35 | import org.encog.neural.hyperneat.substrate.SubstrateFactory;
36 | import org.encog.neural.neat.NEATNetwork;
37 | import org.encog.neural.neat.NEATPopulation;
38 | import org.encog.neural.neat.training.NEATGenome;
39 |
40 | public class DisplayBoxesPanel extends JPanel {
41 |
42 | /**
43 | * The serial.
44 | */
45 | private static final long serialVersionUID = 1L;
46 | private BoxTrialCase testCase = new BoxTrialCase(new Random());
47 | private NEATPopulation pop;
48 | private int resolution = BoxTrialCase.BASE_RESOLUTION;
49 |
50 | public DisplayBoxesPanel(NEATPopulation thePopulation) {
51 | testCase.initTestCase(0);
52 | this.pop = thePopulation;
53 | }
54 |
55 | @Override
56 | public void paint(Graphics g) {
57 |
58 | NEATGenome genome = (NEATGenome) this.pop.getBestGenome();
59 | Substrate substrate = SubstrateFactory.factorSandwichSubstrate(resolution, resolution);
60 | HyperNEATCODEC codec = new HyperNEATCODEC();
61 | NEATNetwork phenotype = (NEATNetwork) codec.decode(this.pop, substrate, genome);
62 |
63 | TrialEvaluation trial = new TrialEvaluation(phenotype, this.testCase);
64 | IntPair actualPos = trial.query(resolution);
65 |
66 | // clear what was there before
67 | g.setColor(Color.white);
68 | g.fillRect(0, 0, getWidth(), getHeight());
69 |
70 | //
71 | int boxWidth = this.getWidth()/resolution;
72 | int boxHeight = this.getHeight()/resolution;
73 | double delta = 2.0 / resolution;
74 | int index = 0;
75 |
76 | for(int row = 0; row < resolution; row++ ) {
77 | double y = -1 + (row*delta);
78 | int boxY = row * boxHeight;
79 | for(int col = 0; col< resolution; col++ ) {
80 | double x = -1 + (col*delta);
81 | int boxX = col*boxWidth;
82 |
83 | if( this.testCase.getPixel(x, y)>0 ) {
84 | g.setColor(Color.blue);
85 | g.fillRect(boxX, boxY, boxWidth, boxHeight);
86 | } else {
87 | double d = trial.getOutput().getData(index);
88 | int c = trial.normalize(d,255);
89 | g.setColor(new Color(255,c,255));
90 | g.fillRect(boxX, boxY, boxWidth, boxHeight);
91 | g.setColor(Color.black);
92 | g.drawRect(boxX, boxY, boxWidth, boxHeight);
93 | g.drawRect(boxX+1, boxY+1, boxWidth-2, boxHeight-2);
94 | }
95 | index++;
96 | }
97 | }
98 |
99 | g.setColor(Color.red);
100 | g.fillRect(actualPos.getX()*boxWidth, actualPos.getY()*boxHeight, boxWidth, boxHeight);
101 | }
102 |
103 | public void createNewCase(int theResolution) {
104 | Random r = new Random();
105 | this.resolution = theResolution;
106 | this.testCase.initTestCase(r.nextInt(3));
107 | this.repaint();
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/normalize/NormalizeFile.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.normalize;
25 |
26 | import java.io.File;
27 |
28 | import org.encog.Encog;
29 | import org.encog.app.analyst.AnalystFileFormat;
30 | import org.encog.app.analyst.EncogAnalyst;
31 | import org.encog.app.analyst.csv.normalize.AnalystNormalizeCSV;
32 | import org.encog.app.analyst.script.normalize.AnalystField;
33 | import org.encog.app.analyst.wizard.AnalystWizard;
34 | import org.encog.util.arrayutil.NormalizationAction;
35 | import org.encog.util.csv.CSVFormat;
36 |
37 | /**
38 | * This is a simple example that will normalize a CSV file.
39 | * The fields are detected from CSV headers.
40 | */
41 | public class NormalizeFile {
42 |
43 | public static void dumpFieldInfo(EncogAnalyst analyst) {
44 | System.out.println("Fields found in file:");
45 | for (AnalystField field : analyst.getScript().getNormalize()
46 | .getNormalizedFields()) {
47 |
48 | StringBuilder line = new StringBuilder();
49 | line.append(field.getName());
50 | line.append(",action=");
51 | line.append(field.getAction());
52 | line.append(",min=");
53 | line.append(field.getActualLow());
54 | line.append(",max=");
55 | line.append(field.getActualHigh());
56 | System.out.println(line.toString());
57 | }
58 | }
59 |
60 | public static void main(String[] args) {
61 |
62 | if (args.length != 2) {
63 | System.out.println("Note: This example assumes that headers are present in the CSV files.");
64 | System.out.println("NormalizeFile [input file] [target file]");
65 | } else {
66 | File sourceFile = new File(args[0]);
67 | File targetFile = new File(args[1]);
68 |
69 | EncogAnalyst analyst = new EncogAnalyst();
70 | AnalystWizard wizard = new AnalystWizard(analyst);
71 | wizard.wizard(sourceFile, true, AnalystFileFormat.DECPNT_COMMA);
72 |
73 | dumpFieldInfo(analyst);
74 |
75 | final AnalystNormalizeCSV norm = new AnalystNormalizeCSV();
76 | norm.analyze(sourceFile, true, CSVFormat.ENGLISH, analyst);
77 | norm.setProduceOutputHeaders(true);
78 | norm.normalize(targetFile);
79 | Encog.getInstance().shutdown();
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/normalize/SimpleNormalize.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.normalize;
25 |
26 | import org.encog.util.arrayutil.NormalizationAction;
27 | import org.encog.util.arrayutil.NormalizedField;
28 |
29 | public class SimpleNormalize {
30 | public static void main(String[] args) {
31 |
32 | // Normalize values with an actual range of (0 to 100) to (-1 to 1)
33 | NormalizedField norm = new NormalizedField(NormalizationAction.Normalize,
34 | null,100,0,1,-1);
35 |
36 | double x = 5;
37 | double y = norm.normalize(x);
38 |
39 | System.out.println( x + " normalized is " + y);
40 |
41 | double z = norm.deNormalize(y);
42 |
43 | System.out.println( y + " denormalized is " + z);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/persist/EncogPersistence.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.persist;
25 |
26 | import java.io.File;
27 |
28 | import org.encog.Encog;
29 | import org.encog.mathutil.randomize.ConsistentRandomizer;
30 | import org.encog.ml.data.MLDataSet;
31 | import org.encog.ml.data.basic.BasicMLDataSet;
32 | import org.encog.ml.train.MLTrain;
33 | import org.encog.neural.networks.BasicNetwork;
34 | import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
35 | import org.encog.persist.EncogDirectoryPersistence;
36 | import org.encog.util.simple.EncogUtility;
37 |
38 | /**
39 | * This example shows how to use Encog persistence to store a neural network
40 | * to an EG file. The EG file is cross-platform and can be shared between
41 | * Encog Java and Encog C#.
42 | *
43 | */
44 | public class EncogPersistence {
45 |
46 | public static final String FILENAME = "encogexample.eg";
47 |
48 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
49 | { 0.0, 1.0 }, { 1.0, 1.0 } };
50 |
51 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
52 |
53 | public void trainAndSave() {
54 | System.out.println("Training XOR network to under 1% error rate.");
55 | BasicNetwork network = EncogUtility.simpleFeedForward(2, 3, 0, 1, false);
56 |
57 | // randomize consistent so that we get weights we know will converge
58 | (new ConsistentRandomizer(-1,1,100)).randomize(network);
59 |
60 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
61 |
62 | // train the neural network
63 | final MLTrain train = new ResilientPropagation(network, trainingSet);
64 |
65 | do {
66 | train.iteration();
67 | } while (train.getError() > 0.009);
68 |
69 | double e = network.calculateError(trainingSet);
70 | System.out.println("Network traiined to error: " + e);
71 |
72 | System.out.println("Saving network");
73 | EncogDirectoryPersistence.saveObject(new File(FILENAME), network);
74 | }
75 |
76 | public void loadAndEvaluate() {
77 | System.out.println("Loading network");
78 |
79 | BasicNetwork network = (BasicNetwork)EncogDirectoryPersistence.loadObject(new File(FILENAME));
80 |
81 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
82 | double e = network.calculateError(trainingSet);
83 | System.out
84 | .println("Loaded network's error is(should be same as above): "
85 | + e);
86 | }
87 |
88 | public static void main(String[] args) {
89 | try {
90 | EncogPersistence program = new EncogPersistence();
91 | program.trainAndSave();
92 | program.loadAndEvaluate();
93 | } catch (Throwable t) {
94 | t.printStackTrace();
95 | } finally {
96 | Encog.getInstance().shutdown();
97 | }
98 |
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/persist/Serial.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.persist;
25 |
26 | import java.io.File;
27 | import java.io.IOException;
28 |
29 | import org.encog.Encog;
30 | import org.encog.mathutil.randomize.ConsistentRandomizer;
31 | import org.encog.ml.data.MLDataSet;
32 | import org.encog.ml.data.basic.BasicMLDataSet;
33 | import org.encog.ml.train.MLTrain;
34 | import org.encog.neural.networks.BasicNetwork;
35 | import org.encog.neural.networks.layers.BasicLayer;
36 | import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
37 | import org.encog.util.obj.SerializeObject;
38 | import org.encog.util.simple.EncogUtility;
39 |
40 | /**
41 | * This example shows how to use Java serialization to store a neural network.
42 | * This file is not cross platform and cannot be shared with Encog C#. Additionally
43 | * future versions of Encog may not be compatable with this file.
44 | *
45 | */
46 | public class Serial {
47 |
48 | public static final String FILENAME = "encogexample.ser";
49 |
50 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
51 | { 0.0, 1.0 }, { 1.0, 1.0 } };
52 |
53 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
54 |
55 | public void trainAndSave() throws IOException {
56 | System.out.println("Training XOR network to under 1% error rate.");
57 | BasicNetwork network = EncogUtility.simpleFeedForward(2, 3, 0, 1, false);
58 |
59 | // randomize consistent so that we get weights we know will converge
60 | (new ConsistentRandomizer(-1,1,100)).randomize(network);
61 |
62 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
63 |
64 | // train the neural network
65 | final MLTrain train = new ResilientPropagation(network, trainingSet);
66 |
67 | do {
68 | train.iteration();
69 | } while (train.getError() > 0.009);
70 |
71 | double e = network.calculateError(trainingSet);
72 | System.out.println("Network traiined to error: " + e);
73 |
74 | System.out.println("Saving network");
75 | SerializeObject.save(new File(FILENAME), network);
76 | }
77 |
78 | public void loadAndEvaluate() throws IOException, ClassNotFoundException {
79 | System.out.println("Loading network");
80 | BasicNetwork network = (BasicNetwork) SerializeObject.load(new File(FILENAME));
81 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
82 | double e = network.calculateError(trainingSet);
83 | System.out
84 | .println("Loaded network's error is(should be same as above): "
85 | + e);
86 | }
87 |
88 | public static void main(String[] args) {
89 | try {
90 | Serial program = new Serial();
91 | program.trainAndSave();
92 | program.loadAndEvaluate();
93 | } catch (Throwable t) {
94 | t.printStackTrace();
95 | } finally {
96 | Encog.getInstance().shutdown();
97 | }
98 |
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/predict/market/Config.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.predict.market;
25 |
26 | import java.util.Calendar;
27 | import java.util.GregorianCalendar;
28 |
29 | import org.encog.ml.data.market.TickerSymbol;
30 |
31 | /**
32 | * Basic config info for the market prediction example.
33 | *
34 | * @author jeff
35 | *
36 | */
37 | public class Config {
38 | public static final String TRAINING_FILE = "marketData.egb";
39 | public static final String NETWORK_FILE = "marketNetwork.eg";
40 | public static final int TRAINING_MINUTES = 1;
41 | public static final int HIDDEN1_COUNT = 20;
42 | public static final int HIDDEN2_COUNT = 0;
43 | public static final int INPUT_WINDOW = 10;
44 | public static final int PREDICT_WINDOW = 1;
45 | public static final TickerSymbol TICKER = new TickerSymbol("AAPL");
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/predict/market/MarketBuildTraining.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.predict.market;
25 |
26 | import java.io.File;
27 | import java.util.Calendar;
28 | import java.util.GregorianCalendar;
29 |
30 | import org.encog.ml.data.market.MarketDataDescription;
31 | import org.encog.ml.data.market.MarketDataType;
32 | import org.encog.ml.data.market.MarketMLDataSet;
33 | import org.encog.ml.data.market.loader.MarketLoader;
34 | import org.encog.ml.data.market.loader.YahooFinanceLoader;
35 | import org.encog.neural.networks.BasicNetwork;
36 | import org.encog.neural.networks.layers.BasicLayer;
37 | import org.encog.persist.EncogDirectoryPersistence;
38 | import org.encog.util.simple.EncogUtility;
39 |
40 | /**
41 | * Build the training data for the prediction and store it in an Encog file for
42 | * later training.
43 | *
44 | * @author jeff
45 | *
46 | */
47 | public class MarketBuildTraining {
48 |
49 | public static void generate(File dataDir) {
50 |
51 | final MarketLoader loader = new YahooFinanceLoader();
52 | final MarketMLDataSet market = new MarketMLDataSet(loader,
53 | Config.INPUT_WINDOW, Config.PREDICT_WINDOW);
54 | final MarketDataDescription desc = new MarketDataDescription(
55 | Config.TICKER, MarketDataType.ADJUSTED_CLOSE, true, true);
56 | market.addDescription(desc);
57 |
58 | Calendar end = new GregorianCalendar();// end today
59 | Calendar begin = (Calendar) end.clone();// begin 30 days ago
60 |
61 | // Gather training data for the last 2 years, stopping 60 days short of today.
62 | // The 60 days will be used to evaluate prediction.
63 | begin.add(Calendar.DATE, -60);
64 | end.add(Calendar.DATE, -60);
65 | begin.add(Calendar.YEAR, -2);
66 |
67 | market.load(begin.getTime(), end.getTime());
68 | market.generate();
69 | EncogUtility.saveEGB(new File(dataDir,Config.TRAINING_FILE), market);
70 |
71 | // create a network
72 | final BasicNetwork network = EncogUtility.simpleFeedForward(
73 | market.getInputSize(),
74 | Config.HIDDEN1_COUNT,
75 | Config.HIDDEN2_COUNT,
76 | market.getIdealSize(),
77 | true);
78 |
79 | // save the network and the training
80 | EncogDirectoryPersistence.saveObject(new File(dataDir,Config.NETWORK_FILE), network);
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/predict/market/MarketEvaluate.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.predict.market;
25 |
26 | import java.io.File;
27 | import java.text.DecimalFormat;
28 | import java.util.Calendar;
29 | import java.util.GregorianCalendar;
30 |
31 | import org.encog.ml.data.MLData;
32 | import org.encog.ml.data.MLDataPair;
33 | import org.encog.ml.data.market.MarketDataDescription;
34 | import org.encog.ml.data.market.MarketDataType;
35 | import org.encog.ml.data.market.MarketMLDataSet;
36 | import org.encog.ml.data.market.loader.MarketLoader;
37 | import org.encog.ml.data.market.loader.YahooFinanceLoader;
38 | import org.encog.neural.data.NeuralData;
39 | import org.encog.neural.networks.BasicNetwork;
40 | import org.encog.persist.EncogDirectoryPersistence;
41 |
42 | public class MarketEvaluate {
43 |
44 | enum Direction {
45 | up, down
46 | };
47 |
48 | public static Direction determineDirection(double d) {
49 | if (d < 0)
50 | return Direction.down;
51 | else
52 | return Direction.up;
53 | }
54 |
55 | public static MarketMLDataSet grabData() {
56 | MarketLoader loader = new YahooFinanceLoader();
57 | MarketMLDataSet result = new MarketMLDataSet(loader,
58 | Config.INPUT_WINDOW, Config.PREDICT_WINDOW);
59 | MarketDataDescription desc = new MarketDataDescription(Config.TICKER,
60 | MarketDataType.ADJUSTED_CLOSE, true, true);
61 | result.addDescription(desc);
62 |
63 | Calendar end = new GregorianCalendar();// end today
64 | Calendar begin = (Calendar) end.clone();// begin 30 days ago
65 | begin.add(Calendar.DATE, -60);
66 |
67 | result.load(begin.getTime(), end.getTime());
68 | result.generate();
69 |
70 | return result;
71 |
72 | }
73 |
74 | public static void evaluate(File dataDir) {
75 |
76 | File file = new File(dataDir,Config.NETWORK_FILE);
77 |
78 | if (!file.exists()) {
79 | System.out.println("Can't read file: " + file.getAbsolutePath());
80 | return;
81 | }
82 |
83 | BasicNetwork network = (BasicNetwork)EncogDirectoryPersistence.loadObject(file);
84 |
85 | MarketMLDataSet data = grabData();
86 |
87 | DecimalFormat format = new DecimalFormat("#0.0000");
88 |
89 | int count = 0;
90 | int correct = 0;
91 | for (MLDataPair pair : data) {
92 | MLData input = pair.getInput();
93 | MLData actualData = pair.getIdeal();
94 | MLData predictData = network.compute(input);
95 |
96 | double actual = actualData.getData(0);
97 | double predict = predictData.getData(0);
98 | double diff = Math.abs(predict - actual);
99 |
100 | Direction actualDirection = determineDirection(actual);
101 | Direction predictDirection = determineDirection(predict);
102 |
103 | if (actualDirection == predictDirection)
104 | correct++;
105 |
106 | count++;
107 |
108 | System.out.println("Day " + count + ":actual="
109 | + format.format(actual) + "(" + actualDirection + ")"
110 | + ",predict=" + format.format(predict) + "("
111 | + predictDirection + ")" + ",diff=" + diff);
112 |
113 | }
114 | double percent = (double) correct / (double) count;
115 | System.out.println("Direction correct:" + correct + "/" + count);
116 | System.out.println("Directional Accuracy:"
117 | + format.format(percent * 100) + "%");
118 |
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/predict/market/MarketPredict.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.predict.market;
25 |
26 | import java.io.File;
27 |
28 | import org.encog.Encog;
29 |
30 |
31 |
32 | /**
33 | * Use the saved market neural network, and now attempt to predict for today, and the
34 | * last 60 days and see what the results are.
35 | */
36 | public class MarketPredict {
37 |
38 | public static void main(String[] args)
39 | {
40 | if( args.length<1 ) {
41 | System.out.println("MarketPredict [data dir] [generate/train/incremental/evaluate]");
42 | }
43 | else
44 | {
45 | File dataDir = new File(args[0]);
46 | if( args[1].equalsIgnoreCase("generate") ) {
47 | MarketBuildTraining.generate(dataDir);
48 | }
49 | else if( args[1].equalsIgnoreCase("train") ) {
50 | MarketTrain.train(dataDir);
51 | }
52 | else if( args[1].equalsIgnoreCase("evaluate") ) {
53 | MarketEvaluate.evaluate(dataDir);
54 | } else if( args[1].equalsIgnoreCase("prune") ) {
55 | MarketPrune.incremental(dataDir);
56 | }
57 | Encog.getInstance().shutdown();
58 | }
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/predict/market/MarketPrune.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.predict.market;
25 |
26 | import java.io.File;
27 |
28 | import org.encog.ConsoleStatusReportable;
29 | import org.encog.engine.network.activation.ActivationTANH;
30 | import org.encog.ml.data.MLDataSet;
31 | import org.encog.neural.data.NeuralDataSet;
32 | import org.encog.neural.pattern.FeedForwardPattern;
33 | import org.encog.neural.prune.PruneIncremental;
34 | import org.encog.persist.EncogDirectoryPersistence;
35 | import org.encog.util.simple.EncogUtility;
36 |
37 | public class MarketPrune {
38 |
39 | public static void incremental(File dataDir) {
40 | File file = new File(dataDir, Config.TRAINING_FILE);
41 |
42 | if (!file.exists()) {
43 | System.out.println("Can't read file: " + file.getAbsolutePath());
44 | return;
45 | }
46 |
47 | MLDataSet training = EncogUtility.loadEGB2Memory(file);
48 |
49 | FeedForwardPattern pattern = new FeedForwardPattern();
50 | pattern.setInputNeurons(training.getInputSize());
51 | pattern.setOutputNeurons(training.getIdealSize());
52 | pattern.setActivationFunction(new ActivationTANH());
53 |
54 | PruneIncremental prune = new PruneIncremental(training, pattern, 100, 1, 10,
55 | new ConsoleStatusReportable());
56 |
57 | prune.addHiddenLayer(5, 50);
58 | prune.addHiddenLayer(0, 50);
59 |
60 | prune.process();
61 |
62 | File networkFile = new File(dataDir, Config.NETWORK_FILE);
63 | EncogDirectoryPersistence.saveObject(networkFile, prune.getBestNetwork());
64 |
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/predict/market/MarketTrain.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.predict.market;
25 |
26 | import java.io.File;
27 |
28 | import org.encog.Encog;
29 | import org.encog.ml.data.MLDataSet;
30 | import org.encog.neural.networks.BasicNetwork;
31 | import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
32 | import org.encog.persist.EncogDirectoryPersistence;
33 | import org.encog.util.simple.EncogUtility;
34 |
35 | /**
36 | * Load the training data from an Encog file, produced during the
37 | * "build training step", and attempt to train.
38 | *
39 | * @author jeff
40 | *
41 | */
42 | public class MarketTrain {
43 |
44 | public static void train(File dataDir) {
45 |
46 | final File networkFile = new File(dataDir, Config.NETWORK_FILE);
47 | final File trainingFile = new File(dataDir, Config.TRAINING_FILE);
48 |
49 | // network file
50 | if (!networkFile.exists()) {
51 | System.out.println("Can't read file: " + networkFile.getAbsolutePath());
52 | return;
53 | }
54 |
55 | BasicNetwork network = (BasicNetwork)EncogDirectoryPersistence.loadObject(networkFile);
56 |
57 | // training file
58 | if (!trainingFile.exists()) {
59 | System.out.println("Can't read file: " + trainingFile.getAbsolutePath());
60 | return;
61 | }
62 |
63 | final MLDataSet trainingSet = EncogUtility.loadEGB2Memory(trainingFile);
64 |
65 | // train the neural network
66 | EncogUtility.trainConsole(network, trainingSet, Config.TRAINING_MINUTES);
67 |
68 | System.out.println("Final Error: " + network.calculateError(trainingSet));
69 | System.out.println("Training complete, saving network.");
70 | EncogDirectoryPersistence.saveObject(networkFile, network);
71 | System.out.println("Network saved.");
72 |
73 | Encog.getInstance().shutdown();
74 |
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/resume/TrainResume.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.resume;
25 |
26 | import java.io.File;
27 | import java.util.Arrays;
28 |
29 | import org.encog.Encog;
30 | import org.encog.mathutil.randomize.ConsistentRandomizer;
31 | import org.encog.ml.data.MLDataSet;
32 | import org.encog.ml.data.basic.BasicMLDataSet;
33 | import org.encog.ml.train.strategy.RequiredImprovementStrategy;
34 | import org.encog.neural.networks.BasicNetwork;
35 | import org.encog.neural.networks.training.propagation.TrainingContinuation;
36 | import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
37 | import org.encog.util.obj.SerializeObject;
38 | import org.encog.util.simple.EncogUtility;
39 |
40 | /**
41 | * This example shows how to begin training a neural network, stop, and then resume.
42 | *
43 | */
44 | public class TrainResume {
45 |
46 | public static String FILENAME = "resume.ser";
47 |
48 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
49 | { 0.0, 1.0 }, { 1.0, 1.0 } };
50 |
51 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
52 |
53 |
54 | public static void main(String[] args)
55 | {
56 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
57 | BasicNetwork network = EncogUtility.simpleFeedForward(2, 3, 0, 1, false);
58 |
59 | // randomize consistent so that we get weights we know will converge
60 | (new ConsistentRandomizer(-1,1,100)).randomize(network);
61 |
62 | ResilientPropagation train = new ResilientPropagation(network, trainingSet);
63 |
64 | System.out.println("Perform initial train.");
65 | EncogUtility.trainToError(train,0.01);
66 | TrainingContinuation cont = train.pause();
67 | System.out.println(Arrays.toString((double[])cont.getContents().get(ResilientPropagation.LAST_GRADIENTS)));
68 | System.out.println(Arrays.toString((double[])cont.getContents().get(ResilientPropagation.UPDATE_VALUES)));
69 |
70 |
71 |
72 | try
73 | {
74 | SerializeObject.save(new File(FILENAME), cont);
75 | cont = (TrainingContinuation)SerializeObject.load(new File(FILENAME));
76 | }
77 | catch(Exception ex)
78 | {
79 | ex.printStackTrace();
80 | }
81 |
82 | System.out.println("Now trying a second train, with continue from the first. Should stop after one iteration");
83 | ResilientPropagation train2 = new ResilientPropagation(network, trainingSet);
84 | train2.resume(cont);
85 | EncogUtility.trainToError(train2,0.01);
86 | Encog.getInstance().shutdown();
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/som/SimpleSOM.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.som;
25 |
26 | import org.encog.Encog;
27 | import org.encog.ml.data.MLData;
28 | import org.encog.ml.data.MLDataSet;
29 | import org.encog.ml.data.basic.BasicMLData;
30 | import org.encog.ml.data.basic.BasicMLDataSet;
31 | import org.encog.neural.som.SOM;
32 | import org.encog.neural.som.training.basic.BasicTrainSOM;
33 | import org.encog.neural.som.training.basic.neighborhood.NeighborhoodSingle;
34 |
35 | /**
36 | * Implement a simple SOM using Encog. It learns to recognize two patterns.
37 | * @author jeff
38 | *
39 | */
40 | public class SimpleSOM {
41 |
42 | public static double SOM_INPUT[][] = {
43 | { -1.0, -1.0, 1.0, 1.0 },
44 | { 1.0, 1.0, -1.0, -1.0 } };
45 |
46 | public static void main(String args[])
47 | {
48 | // create the training set
49 | MLDataSet training = new BasicMLDataSet(SOM_INPUT,null);
50 |
51 | // Create the neural network.
52 | SOM network = new SOM(4,2);
53 | network.reset();
54 |
55 | BasicTrainSOM train = new BasicTrainSOM(
56 | network,
57 | 0.7,
58 | training,
59 | new NeighborhoodSingle());
60 |
61 | int iteration = 0;
62 |
63 | for(iteration = 0;iteration<=10;iteration++)
64 | {
65 | train.iteration();
66 | System.out.println("Iteration: " + iteration + ", Error:" + train.getError());
67 | }
68 |
69 | MLData data1 = new BasicMLData(SOM_INPUT[0]);
70 | MLData data2 = new BasicMLData(SOM_INPUT[1]);
71 | System.out.println("Pattern 1 winner: " + network.classify(data1));
72 | System.out.println("Pattern 2 winner: " + network.classify(data2));
73 | Encog.getInstance().shutdown();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/util/TemporalXOR.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.util;
25 |
26 | import org.encog.ml.data.MLDataSet;
27 | import org.encog.ml.data.basic.BasicMLDataSet;
28 |
29 | /**
30 | * Utility class that presents the XOR operator as a serial stream of values.
31 | * This is used to predict the next value in the XOR sequence. This provides a
32 | * simple stream of numbers that can be predicted.
33 | *
34 | * @author jeff
35 | *
36 | */
37 | public class TemporalXOR {
38 |
39 | /**
40 | * 1 xor 0 = 1, 0 xor 0 = 0, 0 xor 1 = 1, 1 xor 1 = 0
41 | */
42 | public static final double[] SEQUENCE = { 1.0, 0.0, 1.0, 0.0, 0.0, 0.0,
43 | 0.0, 1.0, 1.0, 1.0, 1.0, 0.0 };
44 |
45 | private double[][] input;
46 | private double[][] ideal;
47 |
48 | public MLDataSet generate(final int count) {
49 | this.input = new double[count][1];
50 | this.ideal = new double[count][1];
51 |
52 | for (int i = 0; i < this.input.length; i++) {
53 | this.input[i][0] = TemporalXOR.SEQUENCE[i
54 | % TemporalXOR.SEQUENCE.length];
55 | this.ideal[i][0] = TemporalXOR.SEQUENCE[(i + 1)
56 | % TemporalXOR.SEQUENCE.length];
57 | }
58 |
59 | return new BasicMLDataSet(this.input, this.ideal);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/util/XOR.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.util;
25 |
26 | /**
27 | * Training data for the XOR operator.
28 | * @author jeff
29 | *
30 | */
31 | public class XOR {
32 |
33 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
34 | { 0.0, 1.0 }, { 1.0, 1.0 } };
35 |
36 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/xor/XORConst.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.xor;
25 |
26 | import org.encog.Encog;
27 | import org.encog.engine.network.activation.ActivationSigmoid;
28 | import org.encog.mathutil.randomize.ConsistentRandomizer;
29 | import org.encog.ml.data.MLData;
30 | import org.encog.ml.data.MLDataPair;
31 | import org.encog.ml.data.MLDataSet;
32 | import org.encog.ml.data.basic.BasicMLDataSet;
33 | import org.encog.neural.networks.BasicNetwork;
34 | import org.encog.neural.networks.layers.BasicLayer;
35 | import org.encog.neural.networks.training.propagation.back.Backpropagation;
36 |
37 | public class XORConst {
38 |
39 | /**
40 | * The input necessary for XOR.
41 | */
42 | public static double XOR_INPUT[][] = { { 1.0, 0.0 }, { 0.0, 0.0 },
43 | { 0.0, 1.0 }, { 1.0, 1.0 } };
44 |
45 | /**
46 | * The ideal data necessary for XOR.
47 | */
48 | public static double XOR_IDEAL[][] = { { 1.0 }, { 0.0 }, { 1.0 }, { 0.0 } };
49 |
50 | /**
51 | * The main method.
52 | * @param args No arguments are used.
53 | */
54 | public static void main(final String args[]) {
55 |
56 | // create a neural network, without using a factory
57 | BasicNetwork network = new BasicNetwork();
58 | network.addLayer(new BasicLayer(null,true,2));
59 | network.addLayer(new BasicLayer(new ActivationSigmoid(),true,2));
60 | network.addLayer(new BasicLayer(new ActivationSigmoid(),false,1));
61 | network.getStructure().finalizeStructure();
62 | network.reset();
63 | new ConsistentRandomizer(-1,1,500).randomize(network);
64 | System.out.println(network.dumpWeights());
65 |
66 | // create training data
67 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
68 |
69 | // train the neural network
70 | final Backpropagation train = new Backpropagation(network, trainingSet, 0.7, 0.3);
71 | train.fixFlatSpot(false);
72 |
73 | int epoch = 1;
74 |
75 | do {
76 | train.iteration();
77 | System.out
78 | .println("Epoch #" + epoch + " Error:" + train.getError());
79 | epoch++;
80 | } while(train.getError() > 0.01);
81 |
82 | // test the neural network
83 | System.out.println("Neural Network Results:");
84 | for(MLDataPair pair: trainingSet ) {
85 | final MLData output = network.compute(pair.getInput());
86 | System.out.println(pair.getInput().getData(0) + "," + pair.getInput().getData(1)
87 | + ", actual=" + output.getData(0) + ",ideal=" + pair.getIdeal().getData(0));
88 | }
89 |
90 | Encog.getInstance().shutdown();
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/xor/XORHelloWorld.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.xor;
25 |
26 | import org.encog.Encog;
27 | import org.encog.engine.network.activation.ActivationReLU;
28 | import org.encog.engine.network.activation.ActivationSigmoid;
29 | import org.encog.ml.data.MLData;
30 | import org.encog.ml.data.MLDataPair;
31 | import org.encog.ml.data.MLDataSet;
32 | import org.encog.ml.data.basic.BasicMLDataSet;
33 | import org.encog.neural.networks.BasicNetwork;
34 | import org.encog.neural.networks.layers.BasicLayer;
35 | import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
36 |
37 | /**
38 | * XOR: This example is essentially the "Hello World" of neural network
39 | * programming. This example shows how to construct an Encog neural
40 | * network to predict the output from the XOR operator. This example
41 | * uses backpropagation to train the neural network.
42 | *
43 | * This example attempts to use a minimum of Encog features to create and
44 | * train the neural network. This allows you to see exactly what is going
45 | * on. For a more advanced example, that uses Encog factories, refer to
46 | * the XORFactory example.
47 | *
48 | */
49 | public class XORHelloWorld {
50 |
51 | /**
52 | * The input necessary for XOR.
53 | */
54 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
55 | { 0.0, 1.0 }, { 1.0, 1.0 } };
56 |
57 | /**
58 | * The ideal data necessary for XOR.
59 | */
60 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
61 |
62 | /**
63 | * The main method.
64 | * @param args No arguments are used.
65 | */
66 | public static void main(final String args[]) {
67 |
68 | // create a neural network, without using a factory
69 | BasicNetwork network = new BasicNetwork();
70 | network.addLayer(new BasicLayer(null,true,2));
71 | network.addLayer(new BasicLayer(new ActivationReLU(),true,5));
72 | network.addLayer(new BasicLayer(new ActivationSigmoid(),false,1));
73 | network.getStructure().finalizeStructure();
74 | network.reset();
75 |
76 | // create training data
77 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
78 |
79 | // train the neural network
80 | final ResilientPropagation train = new ResilientPropagation(network, trainingSet);
81 |
82 | int epoch = 1;
83 |
84 | do {
85 | train.iteration();
86 | System.out.println("Epoch #" + epoch + " Error:" + train.getError());
87 | epoch++;
88 | } while(train.getError() > 0.01);
89 | train.finishTraining();
90 |
91 | // test the neural network
92 | System.out.println("Neural Network Results:");
93 | for(MLDataPair pair: trainingSet ) {
94 | final MLData output = network.compute(pair.getInput());
95 | System.out.println(pair.getInput().getData(0) + "," + pair.getInput().getData(1)
96 | + ", actual=" + output.getData(0) + ",ideal=" + pair.getIdeal().getData(0));
97 | }
98 |
99 | Encog.getInstance().shutdown();
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/xor/XORPSO.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.xor;
25 |
26 | import org.encog.Encog;
27 | import org.encog.mathutil.randomize.NguyenWidrowRandomizer;
28 | import org.encog.mathutil.randomize.Randomizer;
29 | import org.encog.ml.CalculateScore;
30 | import org.encog.ml.data.MLDataSet;
31 | import org.encog.ml.data.basic.BasicMLDataSet;
32 | import org.encog.ml.train.MLTrain;
33 | import org.encog.neural.networks.BasicNetwork;
34 | import org.encog.neural.networks.training.TrainingSetScore;
35 | import org.encog.neural.networks.training.pso.NeuralPSO;
36 | import org.encog.util.simple.EncogUtility;
37 |
38 | /**
39 | * XOR-PSO: This example solves the classic XOR operator neural
40 | * network problem. However, it uses PSO training.
41 | *
42 | * @author $Author$
43 | * @version $Revision$
44 | */
45 | public class XORPSO {
46 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
47 | { 0.0, 1.0 }, { 1.0, 1.0 } };
48 |
49 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
50 |
51 | public static void main(final String args[]) {
52 |
53 | MLDataSet trainingSet = new BasicMLDataSet(XOR_INPUT, XOR_IDEAL);
54 | BasicNetwork network = EncogUtility.simpleFeedForward(2, 2, 0, 1, false);
55 | CalculateScore score = new TrainingSetScore(trainingSet);
56 | Randomizer randomizer = new NguyenWidrowRandomizer();
57 |
58 | final MLTrain train = new NeuralPSO(network,randomizer,score,20);
59 |
60 | EncogUtility.trainToError(train, 0.01);
61 |
62 | network = (BasicNetwork)train.getMethod();
63 |
64 | // test the neural network
65 | System.out.println("Neural Network Results:");
66 | EncogUtility.evaluate(network, trainingSet);
67 |
68 | Encog.getInstance().shutdown();
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/xorpartial/XORPartial.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.xorpartial;
25 |
26 | import org.encog.neural.data.NeuralDataSet;
27 | import org.encog.neural.data.basic.BasicNeuralDataSet;
28 | import org.encog.neural.networks.BasicNetwork;
29 | import org.encog.neural.networks.layers.Layer;
30 | import org.encog.util.simple.EncogUtility;
31 |
32 |
33 | /**
34 | * Partial neural networks. Encog allows you to remove any neuron connection in
35 | * a fully connected neural network. This example creates a 2x10x10x1 neural
36 | * network to learn the XOR. Several connections are removed prior to training.
37 | */
38 | public class XORPartial {
39 |
40 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
41 | { 0.0, 1.0 }, { 1.0, 1.0 } };
42 |
43 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
44 |
45 | public static void main(final String args[]) {
46 |
47 | BasicNetwork network = EncogUtility.simpleFeedForward(2, 10, 10, 1,
48 | false);
49 | network.reset();
50 |
51 | // Remove a few connections (does not really matter which, the network
52 | // will train around them).
53 | network.enableConnection(0, 0, 0, false);
54 | network.enableConnection(0, 1, 3, false);
55 | network.enableConnection(1, 1, 1, false);
56 | network.enableConnection(1, 4, 4, false);
57 |
58 | NeuralDataSet trainingSet = new BasicNeuralDataSet(XOR_INPUT, XOR_IDEAL);
59 |
60 | EncogUtility.trainToError(network, trainingSet, 0.01);
61 |
62 | System.out.println("Final output:");
63 | EncogUtility.evaluate(network, trainingSet);
64 |
65 | System.out
66 | .println("Training should leave hidden neuron weights at zero.");
67 | System.out.println("First removed neuron weight:" + network.getWeight(0, 0, 0) );
68 | System.out.println("Second removed neuron weight:" + network.getWeight(0, 1, 3) );
69 | System.out.println("Third removed neuron weight:" + network.getWeight(1, 1, 1) );
70 | System.out.println("Fourth removed neuron weight:" + network.getWeight(1, 4, 4) );
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/neural/xorpartial/XORPartialAuto.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.neural.xorpartial;
25 |
26 | import org.encog.neural.data.NeuralDataSet;
27 | import org.encog.neural.data.basic.BasicNeuralDataSet;
28 | import org.encog.neural.networks.BasicNetwork;
29 | import org.encog.neural.networks.structure.AnalyzeNetwork;
30 | import org.encog.util.Format;
31 | import org.encog.util.simple.EncogUtility;
32 |
33 |
34 | /**
35 | * Partial neural networks. Encog allows you to remove any neuron connection in
36 | * a fully connected neural network. This example creates a 2x10x10x1 neural
37 | * network to learn the XOR. Several connections are removed prior to training.
38 | */
39 | public class XORPartialAuto {
40 |
41 | public static double XOR_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
42 | { 0.0, 1.0 }, { 1.0, 1.0 } };
43 |
44 | public static double XOR_IDEAL[][] = { { 0.0 }, { 1.0 }, { 1.0 }, { 0.0 } };
45 |
46 | public static void main(final String args[]) {
47 |
48 | BasicNetwork network = EncogUtility.simpleFeedForward(2, 10, 10, 1,
49 | false);
50 | network.reset();
51 |
52 | NeuralDataSet trainingSet = new BasicNeuralDataSet(XOR_INPUT, XOR_IDEAL);
53 |
54 | EncogUtility.trainToError(network, trainingSet, 0.01);
55 |
56 |
57 | AnalyzeNetwork analyze = new AnalyzeNetwork(network);
58 | double remove = analyze.getWeights().getHigh()/50;
59 | System.out.println(analyze.toString());
60 | System.out.println("Remove connections below:" + Format.formatDouble(remove,5));
61 |
62 | network.setProperty(BasicNetwork.TAG_LIMIT,remove);
63 | network.getStructure().finalizeLimit();
64 |
65 | analyze = new AnalyzeNetwork(network);
66 | System.out.println(analyze.toString());
67 |
68 | System.out.println("Final output:");
69 | EncogUtility.evaluate(network, trainingSet);
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/proben/BenchmarkDefinition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.proben;
25 |
26 | import java.io.File;
27 |
28 | import org.encog.ml.MLMethod;
29 | import org.encog.ml.train.MLTrain;
30 |
31 | public interface BenchmarkDefinition {
32 | public MLMethod createMethod(ProBenData data);
33 | public MLTrain createTrainer(MLMethod method, ProBenData data);
34 | public String getProBenFolder();
35 | public boolean shouldCenter();
36 | public double getInputCenter();
37 | public double getOutputCenter();
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/proben/EncogBenchmarkDefinition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.proben;
25 |
26 | import org.encog.ml.MLMethod;
27 | import org.encog.ml.MLResettable;
28 | import org.encog.ml.factory.MLMethodFactory;
29 | import org.encog.ml.factory.MLTrainFactory;
30 | import org.encog.ml.train.MLTrain;
31 | import org.encog.ml.train.strategy.RequiredImprovementStrategy;
32 | import org.encog.ml.train.strategy.end.EarlyStoppingStrategy;
33 | import org.encog.neural.networks.training.propagation.manhattan.ManhattanPropagation;
34 |
35 | public class EncogBenchmarkDefinition implements BenchmarkDefinition {
36 |
37 | private String methodName;
38 | private String trainingName;
39 | private String methodArchitecture;
40 | private String trainingArgs;
41 | private String probenPath;
42 | private boolean shouldCenter;
43 | private double inputCenter;
44 | private double outputCenter;
45 |
46 | public EncogBenchmarkDefinition(String theProbenPath, String theMethodName,
47 | String theTrainingName, String theMethodArchitecture,
48 | String theTrainingArgs) {
49 | this(theProbenPath, theMethodName, theTrainingName,
50 | theMethodArchitecture, theTrainingArgs, false, 0, 0);
51 | }
52 |
53 | public EncogBenchmarkDefinition(String theProbenPath, String theMethodName,
54 | String theTrainingName, String theMethodArchitecture,
55 | String theTrainingArgs, boolean theShouldCenter,
56 | double theInputCenter, double theOutputCenter) {
57 | this.methodName = theMethodName;
58 | this.trainingName = theTrainingName;
59 | this.methodArchitecture = theMethodArchitecture;
60 | this.trainingArgs = theTrainingArgs;
61 | this.probenPath = theProbenPath;
62 | this.inputCenter = theInputCenter;
63 | this.outputCenter = theOutputCenter;
64 | }
65 |
66 | @Override
67 | public MLMethod createMethod(ProBenData data) {
68 | MLMethodFactory methodFactory = new MLMethodFactory();
69 | MLMethod method = methodFactory.create(methodName, methodArchitecture,
70 | data.getInputCount(), data.getIdealCount());
71 | return method;
72 | }
73 |
74 | @Override
75 | public MLTrain createTrainer(MLMethod method, ProBenData data) {
76 | MLTrainFactory trainFactory = new MLTrainFactory();
77 | MLTrain train = trainFactory.create(method, data.getTrainingDataSet(),
78 | trainingName, trainingArgs);
79 |
80 | train.addStrategy(new EarlyStoppingStrategy(data
81 | .getValidationDataSet()));
82 | // reset if improve is less than 1% over 5 cycles
83 | if (method instanceof MLResettable
84 | && !(train instanceof ManhattanPropagation)) {
85 | train.addStrategy(new RequiredImprovementStrategy(100));
86 | }
87 | return train;
88 | }
89 |
90 | @Override
91 | public String getProBenFolder() {
92 | return this.probenPath;
93 | }
94 |
95 | @Override
96 | public boolean shouldCenter() {
97 | return this.shouldCenter;
98 | }
99 |
100 | @Override
101 | public double getInputCenter() {
102 | return this.inputCenter;
103 | }
104 |
105 | @Override
106 | public double getOutputCenter() {
107 | return this.outputCenter;
108 | }
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/proben/ProBen.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.proben;
25 |
26 | import org.encog.Encog;
27 | import org.encog.ml.factory.MLMethodFactory;
28 | import org.encog.ml.factory.MLTrainFactory;
29 |
30 | public class ProBen {
31 |
32 | public final static String METHOD_NAME = MLMethodFactory.TYPE_FEEDFORWARD;
33 | public final static String TRAINING_TYPE = MLTrainFactory.TYPE_RPROP;
34 | public final static String METHOD_ARCHITECTURE = "?:B->RELU->40:B->LINEAR->?";
35 | public final static String TRAINING_ARGS = "";
36 |
37 | public static void main(String[] args) {
38 | String probenPath = ProBenData.obtainProbenPath(args);
39 |
40 | try {
41 | EncogBenchmarkDefinition def = new EncogBenchmarkDefinition(
42 | probenPath, METHOD_NAME, TRAINING_TYPE,
43 | METHOD_ARCHITECTURE, TRAINING_ARGS);
44 |
45 | ProBenRunner runner = new ProBenRunner(def);
46 | System.out.println("Starting...");
47 | runner.run();
48 |
49 | Encog.getInstance().shutdown();
50 |
51 | } catch (Exception ex) {
52 | ex.printStackTrace();
53 | }
54 |
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/proben/ProBenError.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.proben;
25 |
26 | import org.encog.EncogError;
27 |
28 | public class ProBenError extends EncogError {
29 |
30 | public ProBenError(String msg, Throwable t) {
31 | super(msg, t);
32 | }
33 |
34 | public ProBenError(Throwable t) {
35 | super(t);
36 | }
37 |
38 | public ProBenError(String msg) {
39 | super(msg);
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/proben/ProBenEvaluate.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.proben;
25 |
26 | import java.util.Set;
27 | import java.util.TreeSet;
28 |
29 | import org.encog.ml.MLError;
30 | import org.encog.ml.MLMethod;
31 | import org.encog.ml.train.MLTrain;
32 |
33 | public class ProBenEvaluate {
34 |
35 | private ProBenData data;
36 | private int iterations;
37 | private BenchmarkDefinition def;
38 |
39 | public ProBenEvaluate(ProBenData theData, BenchmarkDefinition theDefinition) {
40 | this.data = theData;
41 | this.def = theDefinition;
42 | }
43 |
44 | public ProBenResult evaluate() {
45 | Set results = new TreeSet();
46 | for(int i=0;i<5;i++) {
47 | ProBenResult result = evaluateSingle();
48 | results.add(result);
49 | System.out.println(i+":"+result);
50 | }
51 | return results.iterator().next();
52 | }
53 |
54 | private ProBenResult evaluateSingle() {
55 | MLMethod method = this.def.createMethod(this.data);
56 | MLTrain train = this.def.createTrainer(method, this.data);
57 |
58 | this.iterations = 0;
59 | do {
60 | //System.out.println(this.iterations + " " + train.getError());
61 | train.iteration();
62 | this.iterations++;
63 | } while (!train.isTrainingDone());
64 |
65 | MLError calc = (MLError)train.getMethod();
66 |
67 | return new ProBenResult(data.getName(),
68 | iterations,
69 | calc.calculateError(data.getTrainingDataSet()),
70 | calc.calculateError(data.getValidationDataSet()));
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/proben/ProBenResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.proben;
25 |
26 | import org.encog.util.Format;
27 |
28 | public class ProBenResult implements Comparable {
29 | private final String name;
30 | private final int iterations;
31 | private final double trainingError;
32 | private final double validationError;
33 |
34 |
35 | public ProBenResult(String name, int iterations, double trainingError,
36 | double validationError) {
37 | super();
38 | this.name = name;
39 | this.iterations = iterations;
40 | this.trainingError = trainingError;
41 | this.validationError = validationError;
42 | }
43 |
44 |
45 | @Override
46 | public int compareTo(ProBenResult other) {
47 | return Double.compare(this.validationError, other.validationError);
48 | }
49 |
50 | public String toString() {
51 | return(this.name + "; Iterations=" + iterations
52 | + "; Training Error=" + Format.formatDouble(this.trainingError, 4)
53 | + "; Validation Error=" + Format.formatDouble(this.validationError, 4));
54 | }
55 |
56 |
57 | /**
58 | * @return the name
59 | */
60 | public String getName() {
61 | return name;
62 | }
63 |
64 |
65 | /**
66 | * @return the iterations
67 | */
68 | public int getIterations() {
69 | return iterations;
70 | }
71 |
72 |
73 | /**
74 | * @return the trainingError
75 | */
76 | public double getTrainingError() {
77 | return trainingError;
78 | }
79 |
80 |
81 | /**
82 | * @return the validationError
83 | */
84 | public double getValidationError() {
85 | return validationError;
86 | }
87 |
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/proben/ProBenResultAccumulator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.proben;
25 |
26 | import org.encog.util.Format;
27 |
28 | public class ProBenResultAccumulator {
29 |
30 | private int iterations;
31 | private double trainingError;
32 | private double validationError;
33 | private int count;
34 |
35 | /**
36 | * @return the iterations
37 | */
38 | public int getIterations() {
39 | return iterations;
40 | }
41 |
42 | /**
43 | * @return the trainingError
44 | */
45 | public double getTrainingError() {
46 | return trainingError;
47 | }
48 |
49 | /**
50 | * @return the validationError
51 | */
52 | public double getValidationError() {
53 | return validationError;
54 | }
55 |
56 | /**
57 | * @return the count
58 | */
59 | public int getCount() {
60 | return count;
61 | }
62 |
63 | public void accumulate(ProBenResult result) {
64 | this.iterations+=result.getIterations();
65 | this.trainingError+=result.getTrainingError();
66 | this.validationError+=result.getValidationError();
67 | this.count++;
68 | }
69 |
70 | public String toString() {
71 | return("Mean Iterations=" + iterations/this.count
72 | + "; Mean Training Error=" + Format.formatDouble(this.trainingError/this.count, 4)
73 | + "; Mean Validation Error=" + Format.formatDouble(this.validationError/this.count, 4));
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/org/encog/examples/proben/ProBenRunner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Encog(tm) Java Examples v3.4
3 | * http://www.heatonresearch.com/encog/
4 | * https://github.com/encog/encog-java-examples
5 | *
6 | * Copyright 2008-2017 Heaton Research, Inc.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | *
20 | * For more information on Heaton Research copyrights, licenses
21 | * and trademarks visit:
22 | * http://www.heatonresearch.com/copyright
23 | */
24 | package org.encog.examples.proben;
25 |
26 | import java.io.File;
27 |
28 | import org.encog.util.Stopwatch;
29 | import org.encog.util.file.FileUtil;
30 |
31 | public class ProBenRunner {
32 | private BenchmarkDefinition def;
33 | private File dir;
34 | private boolean mergeTest = true;
35 | private ProBenResultAccumulator accumulator = new ProBenResultAccumulator();
36 |
37 | public ProBenRunner(BenchmarkDefinition benchmarkDef) {
38 | this.def = benchmarkDef;
39 | this.dir = new File(def.getProBenFolder());
40 | }
41 |
42 | /**
43 | * @return the mergeTest
44 | */
45 | public boolean isMergeTest() {
46 | return mergeTest;
47 | }
48 |
49 |
50 |
51 | /**
52 | * @param mergeTest the mergeTest to set
53 | */
54 | public void setMergeTest(boolean mergeTest) {
55 | this.mergeTest = mergeTest;
56 | }
57 |
58 |
59 |
60 | public ProBenResultAccumulator run() {
61 | Stopwatch sw = new Stopwatch();
62 | sw.start();
63 | runDirectory(this.dir);
64 |
65 | System.out.println("Final results: " + this.accumulator.toString());
66 | sw.stop();
67 | System.out.println("Runtime: " + sw.toString());
68 | return this.accumulator;
69 | }
70 |
71 | public void runDirectory(File file) {
72 |
73 | for(File childFile: file.listFiles()) {
74 | if( childFile.isDirectory()) {
75 | runDirectory(childFile);
76 | } else {
77 | if( FileUtil.getFileExt(childFile).equalsIgnoreCase("dt")) {
78 | runFile(childFile);
79 | }
80 | }
81 | }
82 |
83 | }
84 |
85 | public void runFile(File file) {
86 | ProBenData data = new ProBenData(file,this.mergeTest);
87 | data.load();
88 |
89 | if( this.def.shouldCenter() ) {
90 | data.center(def.getInputCenter(), def.getOutputCenter());
91 | }
92 |
93 | ProBenEvaluate eval = new ProBenEvaluate(data, this.def);
94 | ProBenResult result = eval.evaluate();
95 | System.out.println("Using result:" + result.toString());
96 | this.accumulator.accumulate(result);
97 | }
98 | }
99 |
--------------------------------------------------------------------------------