Skip to content
Snippets Groups Projects
Commit 7958e665 authored by Martin Mrovec's avatar Martin Mrovec
Browse files

FIX: deleted folder 4neuro with former Eclipse project.

parent 73c2beb3
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 3882 deletions
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="photran.managedbuild.config.gnu.fortran.win32.exe.debug.338229552">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="photran.managedbuild.config.gnu.fortran.win32.exe.debug.338229552" moduleId="org.eclipse.cdt.core.settings" name="Debug">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.PE" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.Cygwin_PE" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GNU_ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.photran.core.GFortranErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration artifactName="${ProjName}" buildProperties="" cleanCommand="rm -rf" description="" errorParsers="org.eclipse.photran.core.GFortranErrorParser;org.eclipse.cdt.core.GCCErrorParser;org.eclipse.cdt.core.GLDErrorParser;org.eclipse.cdt.core.GASErrorParser;org.eclipse.cdt.core.GmakeErrorParser" id="photran.managedbuild.config.gnu.fortran.win32.exe.debug.338229552" name="Debug" parent="photran.managedbuild.config.gnu.fortran.win32.exe.debug">
<folderInfo id="photran.managedbuild.config.gnu.fortran.win32.exe.debug.338229552." name="/" resourcePath="">
<toolChain id="photran.managedbuild.toolchain.gnu.fortran.win32.exe.debug.609204123" name="GCC Fortran" nonInternalBuilderId="photran.managedbuild.target.gnu.builder.win32.exe.debug" superClass="photran.managedbuild.toolchain.gnu.fortran.win32.exe.debug">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.PE;org.eclipse.cdt.core.Cygwin_PE;org.eclipse.cdt.core.GNU_ELF" id="photran.managedbuild.target.gnu.platform.win32.exe.debug.1367946370" name="Debug Platform" osList="win32" superClass="photran.managedbuild.target.gnu.platform.win32.exe.debug"/>
<builder autoBuildTarget="all" buildPath="${workspace_loc:/4neuro}/Debug" cleanBuildTarget="clean" command="./build.sh" id="org.eclipse.cdt.build.core.internal.builder.1589687311" incrementalBuildTarget="all" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="CDT Internal Builder" superClass="org.eclipse.cdt.build.core.internal.builder"/>
<tool id="photran.managedbuild.tool.gnu.c.compiler.win32.exe.debug.778780997" name="GCC C Compiler" superClass="photran.managedbuild.tool.gnu.c.compiler.win32.exe.debug">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.2016360279" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="photran.managedbuild.tool.gnu.fortran.compiler.win32.exe.debug.1743211871" name="GNU Fortran Compiler" superClass="photran.managedbuild.tool.gnu.fortran.compiler.win32.exe.debug">
<option id="gnu.fortran.compiler.option.include.paths.769321882" name="Include paths (-I)" superClass="gnu.fortran.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
<listOptionValue builtIn="false" value="&quot;C:\msys64\mingw32\bin&quot;"/>
</option>
<inputType id="photran.managedbuild.tool.gnu.fortran.compiler.input.2145534976" superClass="photran.managedbuild.tool.gnu.fortran.compiler.input"/>
</tool>
<tool id="photran.managedbuild.tool.gnu.fortran.linker.win32.exe.debug.437267444" name="GNU Fortran Linker" superClass="photran.managedbuild.tool.gnu.fortran.linker.win32.exe.debug">
<inputType id="photran.managedbuild.tool.gnu.fortran.linker.input.1813142317" superClass="photran.managedbuild.tool.gnu.fortran.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="photran.managedbuild.tool.gnu.assembler.win32.exe.debug.432119483" name="GCC Assembler" superClass="photran.managedbuild.tool.gnu.assembler.win32.exe.debug">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1934367141" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
<cconfiguration id="photran.managedbuild.config.gnu.fortran.win32.exe.release.1957908145">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="photran.managedbuild.config.gnu.fortran.win32.exe.release.1957908145" moduleId="org.eclipse.cdt.core.settings" name="Release">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.PE" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.Cygwin_PE" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GNU_ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.photran.core.GFortranErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration artifactName="${ProjName}" buildProperties="" cleanCommand="rm -rf" description="" errorParsers="org.eclipse.photran.core.GFortranErrorParser;org.eclipse.cdt.core.GCCErrorParser;org.eclipse.cdt.core.GLDErrorParser;org.eclipse.cdt.core.GASErrorParser;org.eclipse.cdt.core.GmakeErrorParser" id="photran.managedbuild.config.gnu.fortran.win32.exe.release.1957908145" name="Release" parent="photran.managedbuild.config.gnu.fortran.win32.exe.release">
<folderInfo id="photran.managedbuild.config.gnu.fortran.win32.exe.release.1957908145." name="/" resourcePath="">
<toolChain id="photran.managedbuild.toolchain.gnu.fortran.win32.exe.release.1111724220" name="GCC Fortran" superClass="photran.managedbuild.toolchain.gnu.fortran.win32.exe.release">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.PE;org.eclipse.cdt.core.Cygwin_PE;org.eclipse.cdt.core.GNU_ELF" id="photran.managedbuild.target.gnu.platform.fortran.win32.exe.release.1225476161" name="Release Platform" osList="win32" superClass="photran.managedbuild.target.gnu.platform.fortran.win32.exe.release"/>
<builder buildPath="${workspace_loc:/4neuro}/Release" id="photran.managedbuild.target.gnu.builder.win32.exe.release.1043598058" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Gnu Make Builder" superClass="photran.managedbuild.target.gnu.builder.win32.exe.release"/>
<tool id="photran.managedbuild.tool.gnu.c.compiler.win32.exe.release.1436794482" name="GCC C Compiler" superClass="photran.managedbuild.tool.gnu.c.compiler.win32.exe.release">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1856045908" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="photran.managedbuild.tool.gnu.fortran.compiler.win32.exe.release.1119644158" name="GNU Fortran Compiler" superClass="photran.managedbuild.tool.gnu.fortran.compiler.win32.exe.release">
<inputType id="photran.managedbuild.tool.gnu.fortran.compiler.input.1812093560" superClass="photran.managedbuild.tool.gnu.fortran.compiler.input"/>
</tool>
<tool id="photran.managedbuild.tool.gnu.fortran.linker.win32.exe.release.1754062441" name="GNU Fortran Linker" superClass="photran.managedbuild.tool.gnu.fortran.linker.win32.exe.release">
<inputType id="photran.managedbuild.tool.gnu.fortran.linker.input.197505219" superClass="photran.managedbuild.tool.gnu.fortran.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="photran.managedbuild.tool.gnu.assembler.win32.exe.release.1039785129" name="GCC Assembler" superClass="photran.managedbuild.tool.gnu.assembler.win32.exe.release">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.440312833" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="4neuro.photran.managedbuild.target.gnu.fortran.win32.exe.1809620819" name="Executable (Gnu Fortran on Windows)" projectType="photran.managedbuild.target.gnu.fortran.win32.exe"/>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="refreshScope" versionNumber="2">
<configuration configurationName="Debug">
<resource resourceType="PROJECT" workspacePath="/4neuro"/>
</configuration>
<configuration configurationName="Release">
<resource resourceType="PROJECT" workspacePath="/4neuro"/>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.make.core.buildtargets"/>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
<scannerConfigBuildInfo instanceId="photran.managedbuild.config.gnu.fortran.win32.exe.debug.338229552;photran.managedbuild.config.gnu.fortran.win32.exe.debug.338229552.">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"/>
</scannerConfigBuildInfo>
<scannerConfigBuildInfo instanceId="photran.managedbuild.config.gnu.fortran.win32.exe.debug.338229552;photran.managedbuild.config.gnu.fortran.win32.exe.debug.338229552.;photran.managedbuild.tool.gnu.c.compiler.win32.exe.debug.778780997;cdt.managedbuild.tool.gnu.c.compiler.input.2016360279">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
</scannerConfigBuildInfo>
</storageModule>
</cproject>
*.o
*.mod
*.out
/Debug/
before_script:
- apt-get update
- apt-get install -y -qq make gfortran cmake gem
- gem install funit
- ./build.sh
run_tests:
script: "./run_tests.sh"
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>4neuro</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.photran.core.fnature</nature>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
</natures>
</projectDescription>
cmake_minimum_required(VERSION 3.0)
project(4Neuro)
enable_language(Fortran)
#-------------------------------#
# Default installation location #
#-------------------------------#
# Linux: /usr/local
# Windows: C:/Users/Marti/OneDrive/Dokumenty/Fortran/git4Neuro/4NeuroMrovma/4Neuro/t
#------------#
# Build type #
#------------#
# Default: Release
# Others: None, Debug
if (NOT CMAKE_BUILD_TYPE)
set (CMAKE_BUILD_TYPE RELEASE CACHE STRING
"Choose the type of build, options are: None Debug Release."
FORCE)
endif (NOT CMAKE_BUILD_TYPE)
#--------------------------------#
# Setting Fortran compiler flags #
#--------------------------------#
# TODO overit, jak rychle jede kod s funroll-loops
# funroll-all-loops a bez prepinace
set(standard "-std=f2008")
if (Fortran_COMPILER_NAME MATCHES "gfortran.*")
# gfortran
set (CMAKE_Fortran_FLAGS_RELEASE "-funroll-loops -fno-f2c -O3 ${standard}")
set (CMAKE_Fortran_FLAGS_DEBUG "-fno-f2c -O0 -g ${standard}")
elseif (Fortran_COMPILER_NAME MATCHES "ifort.*")
# ifort (untested)
set (CMAKE_Fortran_FLAGS_RELEASE "-f77rtl -O3 ${standard}")
set (CMAKE_Fortran_FLAGS_DEBUG "-f77rtl -O0 -g ${standard}")
elseif (Fortran_COMPILER_NAME MATCHES "g77")
# g77
set (CMAKE_Fortran_FLAGS_RELEASE "-funroll-loops -fno-f2c -O3 -m32 ${standard}")
set (CMAKE_Fortran_FLAGS_DEBUG "-fno-f2c -O0 -g -m32 ${standard}")
else (Fortran_COMPILER_NAME MATCHES "gfortran.*")
message ("CMAKE_Fortran_COMPILER full path: " ${CMAKE_Fortran_COMPILER})
message ("Fortran compiler: " ${Fortran_COMPILER_NAME})
message ("No optimized Fortran compiler flags are known, we just try -O2...")
set (CMAKE_Fortran_FLAGS_RELEASE "-O2 ${standard}")
set (CMAKE_Fortran_FLAGS_DEBUG "-O0 -g ${standard}")
endif (Fortran_COMPILER_NAME MATCHES "gfortran.*")
#----------------#
# User variables #
#----------------#
set(SRC_DIR src)
set(BUILD_DIR build)
set(LIB_DIR lib)
#--------------------#
# Building libraries #
#--------------------#
link_directories("${LIB_DIR}")
include_directories("${BUILD_DIR}/${LIB_DIR}")
add_subdirectory("${SRC_DIR}" "${LIB_DIR}")
add_executable(connection_test.out ${SRC_DIR}/connection_test.f90)
target_link_libraries(connection_test.out connection_m neuron_dummy_m)
This diff is collapsed.
4Neuro
#!/bin/bash
echo "Creating folder 'build'...";
mkdir -p build/lib;
echo "Folder 'build' was created'";
cd build;
cmake ..;
make && echo "Installation complete." || exit -1;
#make install;
echo "Generating documentation into folder 'docs'...";
doxygen >/dev/null && echo "Documenation was generated." || exit -1;
cd docs/latex;
echo "Building LaTeX documentation../";
make >/dev/null && echo "Documentation was built." || exit -1;
cd ../..;
#!/bin/bash
rm -rf build
rm -rf docs/*
4neuro/img/4neuro_logo_small.png

44.7 KiB

package cz.vsb.mro0010.neuralnetworks;
import java.util.ArrayList;
import java.util.Arrays;
public class BPNet extends MultiLayeredNet {
protected float error;
public float getError() {
return error;
}
public void setError(float error) {
this.error = error;
}
protected float tolerance;
protected String neuronType;
protected float learnCoeff;
public BPNet( float tolerance, int nrOfLayers, int nrOfInputs, ArrayList<Integer> nrOfNeuronsPerLayer, float slope, float learnCoeff ) {
super(nrOfInputs, nrOfLayers, nrOfNeuronsPerLayer);
this.neuronType = "SigmoidalNeuron";
this.tolerance = tolerance;
this.learnCoeff = learnCoeff;
for (int i = 0; i < nrOfLayers; i++) {
for (int j = 0; j < nrOfNeuronsPerLayer.get(i); j++) {
this.neuronLayers.get(i).add(new SigmoidalNeuron(slope));
}
}
for (int i = 0; i < nrOfLayers; i++) {
this.interconnectionsLayers.add(new InterconnectionsBP(this.learnCoeff));
}
for (Neuron neuronIn : this.inputNeuronLayer) {
for (Neuron neuronFirstLevel : this.neuronLayers.get(0)) {
this.interconnectionsLayers.get(0).addConnection(new Connection(neuronIn, neuronFirstLevel, (float) (Math.random())));
}
}
for (int i = 1; i < nrOfLayers; i++) {
for (Neuron neuronIn : this.neuronLayers.get(i-1)) {
for (Neuron neuronOut : this.neuronLayers.get(i)) {
this.interconnectionsLayers.get(i).addConnection(new Connection(neuronIn, neuronOut, (float) (Math.random())));
}
}
}
}
public float getTolerance() {
return tolerance;
}
public void setTolerance(float tolerance) {
this.tolerance = tolerance;
}
@Override
public String getNeuronType() {
return this.neuronType;
}
@Override
public int learn(String trainingSet) {
boolean learned = false;
int iter = 0;
ArrayList<String> trainingElements = new ArrayList<String>(Arrays.asList(trainingSet.split("\n")));
while(!learned) {
learned = true;
this.error = 0;
for (int i = 0; i < trainingElements.size(); i++) {
learned &= learnStep(trainingElements.get(i));
}
iter++;
// System.out.println(iter);
}
return iter;
// System.out.println("Learned in " + iter + " whole training set iterations.");
}
public boolean learnStep(String trainingElement) {
// Run training Element
String[] splitedTrainingElement = trainingElement.split(" ");
StringBuffer inputString = new StringBuffer();
for (int i = 0; i < this.nrOfInputs; i++) { //Input values
inputString.append(splitedTrainingElement[i]);
inputString.append(" ");
}
ArrayList<Float> expectedValues = new ArrayList<Float>();
for (int i = this.nrOfInputs; i < splitedTrainingElement.length; i++) { //Expected values
expectedValues.add(Float.parseFloat(splitedTrainingElement[i]));
}
this.run(inputString.substring(0, inputString.length() - 1));
// Calculate error
float error = 0;
for (int i = 0; i < expectedValues.size(); i++) {
float y = this.neuronLayers.get(this.nrOfLayers-1).get(i).getState(); //output of ith neuron
float o = expectedValues.get(i);
error += (float)( 0.5 * Math.pow((y-o), 2));
}
if (this.error < error) {
this.error = error;
}
if (error > this.tolerance) { //Error is too high -> modify weights
// Calculate deltas
for (int i = this.nrOfLayers - 1; i >= 0; i -= 1) {
for (Neuron n : this.neuronLayers.get(i)) {
SigmoidalNeuron neuron = (SigmoidalNeuron)n;
if (i == this.nrOfLayers - 1) { //Top layer
float y = neuron.getState();
float o = expectedValues.get(this.neuronLayers.get(i).indexOf(neuron));
float delta = y - o;
neuron.setError(delta);
} else { //Other layers
ArrayList<Connection> connectionsToUpperLayerFromNeuron = new ArrayList<Connection>();
// Find all connections, that have "neuron" as input
for (Connection c : this.interconnectionsLayers.get(i+1).getConnections()) {
if (c.getInputNeuron().equals(neuron))
connectionsToUpperLayerFromNeuron.add(c);
}
float delta = 0;
for (Connection c : connectionsToUpperLayerFromNeuron) {
float deltaUpper = ((SigmoidalNeuron)c.getOutputNeuron()).getError();
float lambdaUpper = ((SigmoidalNeuron)c.getOutputNeuron()).getSlope();
float yUpper = c.getOutputNeuron().getState();
float w = c.getWeight();
delta += deltaUpper*lambdaUpper*yUpper*(1-yUpper)*w;
}
neuron.setError(delta);
}
}
}
// Adjust weights
for (Interconnections interconnectionsLayer : this.interconnectionsLayers) {
interconnectionsLayer.adjustWeights();
}
return false;
} else {
return true;
}
}
public String getOutput() {
StringBuffer output = new StringBuffer();
ArrayList<Neuron> outputLayer = this.neuronLayers.get(this.nrOfLayers-1);
for (int i = 0; i < outputLayer.size(); i++) {
output.append(String.valueOf(outputLayer.get(i).getState()));
output.append(" ");
}
return output.toString();
}
public void changeSlopeTo(float slope) {
for (ArrayList<Neuron> neuronLayer : this.neuronLayers) {
for (Neuron neuron : neuronLayer) {
((SigmoidalNeuron)neuron).setSlope(slope);
}
}
}
public void changeLearnCoeffTo(float learnCoeff) {
for (Interconnections layer : interconnectionsLayers) {
((InterconnectionsBP)layer).setLearningRate(learnCoeff);
}
}
public void resetWeights() {
for (Interconnections layer : interconnectionsLayers) {
for (Connection connection : layer.getConnections()) {
connection.setWeight((float)Math.random());
}
}
}
public void addNeuron(int layerIndex, float slope) {
SigmoidalNeuron newNeuron = new SigmoidalNeuron(slope);
neuronLayers.get(layerIndex).add(newNeuron);
if ((layerIndex < nrOfLayers) && (layerIndex >= 0)) {
Interconnections inputConnectionLayer = this.interconnectionsLayers.get(layerIndex);
if (layerIndex == 0) {
ArrayList<InputLayerPseudoNeuron> inputNeurons = this.inputNeuronLayer;
for (Neuron inputNeuron : inputNeurons) {
inputConnectionLayer.addConnection(new Connection(inputNeuron, newNeuron, (float)Math.random()));
}
} else {
ArrayList<Neuron> inputNeurons = this.neuronLayers.get(layerIndex - 1);
for (Neuron inputNeuron : inputNeurons) {
inputConnectionLayer.addConnection(new Connection(inputNeuron, newNeuron, (float)Math.random()));
}
}
if (layerIndex < nrOfLayers - 1) {
Interconnections outputConnectionLayer = this.interconnectionsLayers.get(layerIndex + 1);
ArrayList<Neuron> outputNeurons = this.neuronLayers.get(layerIndex + 1);
for (Neuron outputNeuron : outputNeurons) {
outputConnectionLayer.addConnection(new Connection(newNeuron, outputNeuron, (float)Math.random()));
}
}
this.nrOfNeuronsPerLayer.set(layerIndex, this.nrOfNeuronsPerLayer.get(layerIndex) + 1 );
} else {
throw new InvalidLayerNumberException();
}
}
public void removeNeuron(int layerIndex) {
int nrOfNeuronsInThisLayer = this.nrOfNeuronsPerLayer.get(layerIndex);
if ((layerIndex < nrOfLayers) && (layerIndex >= 0)) {
if (nrOfNeuronsInThisLayer == 1) {
removeNeuronLayer(layerIndex);
} else {
Neuron removedNeuron = this.neuronLayers.get(layerIndex).get(nrOfNeuronsInThisLayer - 1);
Interconnections inputConnectionLayer = this.interconnectionsLayers.get(layerIndex);
ArrayList<Connection> removedConnections = new ArrayList<Connection>();
for (Connection connection : inputConnectionLayer.getConnections()) {
if (connection.getOutputNeuron().equals(removedNeuron)) {
removedConnections.add(connection);
}
}
for (Connection connection : removedConnections) {
inputConnectionLayer.getConnections().remove(connection);
}
removedConnections = new ArrayList<Connection>();
if (layerIndex < nrOfLayers - 1) {
Interconnections outputConnectionLayer = this.interconnectionsLayers.get(layerIndex + 1);
for (Connection connection : outputConnectionLayer.getConnections()) {
if (connection.getInputNeuron().equals(removedNeuron)) {
removedConnections.add(connection);
}
}
for (Connection connection : removedConnections) {
outputConnectionLayer.getConnections().remove(connection);
}
}
this.neuronLayers.get(layerIndex).remove(removedNeuron);
this.nrOfNeuronsPerLayer.set(layerIndex, this.nrOfNeuronsPerLayer.get(layerIndex) - 1 );
}
} else {
throw new InvalidLayerNumberException();
}
}
public void addNeuronLayer(int nrOfNeurons, int layerIndex, float slope) {
if ((layerIndex < nrOfLayers + 1) && (layerIndex >= 0) && (nrOfNeurons > 0)) {
this.nrOfLayers++;
this.nrOfNeuronsPerLayer.add(layerIndex, nrOfNeurons);
// new layer creation
ArrayList<Neuron> newNeuronLayer = new ArrayList<Neuron>();
for (int i = 0; i < nrOfNeurons; i++) {
newNeuronLayer.add(new SigmoidalNeuron(slope));
}
// old connections removal
if (layerIndex < nrOfLayers - 1) { // only if inner layer is added
this.interconnectionsLayers.remove(layerIndex);
}
// new layer adding
this.neuronLayers.add(layerIndex, newNeuronLayer);
// new connections creation
// input
Interconnections inputConnLayer = new InterconnectionsBP(learnCoeff);
if (layerIndex == 0) {
ArrayList<InputLayerPseudoNeuron> inputNeurons = this.inputNeuronLayer;
ArrayList<Neuron> outputNeurons = newNeuronLayer; //Layers already shifted
for (Neuron inputNeuron : inputNeurons) {
for (Neuron outputNeuron : outputNeurons) {
inputConnLayer.addConnection(new Connection(inputNeuron, outputNeuron, (float)Math.random()));
}
}
} else {
ArrayList<Neuron> inputNeurons = this.neuronLayers.get(layerIndex - 1);
ArrayList<Neuron> outputNeurons = newNeuronLayer; //Layers already shifted, this is new layer
for (Neuron inputNeuron : inputNeurons) {
for (Neuron outputNeuron : outputNeurons) {
inputConnLayer.addConnection(new Connection(inputNeuron, outputNeuron, (float)Math.random()));
}
}
}
this.interconnectionsLayers.add(layerIndex, inputConnLayer);
// output
Interconnections outputConnLayer = new InterconnectionsBP(learnCoeff);
if (layerIndex < nrOfLayers - 1) {
ArrayList<Neuron> inputNeurons = newNeuronLayer;
ArrayList<Neuron> outputNeurons = this.neuronLayers.get(layerIndex + 1); //Layers already shifted
for (Neuron inputNeuron : inputNeurons) {
for (Neuron outputNeuron : outputNeurons) {
outputConnLayer.addConnection(new Connection(inputNeuron, outputNeuron, (float)Math.random()));
}
}
this.interconnectionsLayers.add(layerIndex + 1, outputConnLayer);
}
} else {
throw new InvalidLayerNumberException();
}
}
public void removeNeuronLayer(int layerIndex) {
if ((layerIndex < nrOfLayers ) && (layerIndex >= 0) && (nrOfLayers > 1)) {
// delete output connections
if (layerIndex < nrOfLayers - 1) {
this.interconnectionsLayers.remove(layerIndex + 1);
}
// delete input connections
this.interconnectionsLayers.remove(layerIndex);
// delete neurons on layer
this.neuronLayers.remove(layerIndex);
this.nrOfNeuronsPerLayer.remove(layerIndex);
this.nrOfLayers--;
// create new connections
if (layerIndex < nrOfLayers + 1) {
Interconnections connLayer = new InterconnectionsBP(learnCoeff);
if (layerIndex == 0) {
ArrayList<InputLayerPseudoNeuron> inputNeurons = this.inputNeuronLayer;
ArrayList<Neuron> outputNeurons = this.neuronLayers.get(0);
for (Neuron inputNeuron : inputNeurons) {
for (Neuron outputNeuron : outputNeurons) {
connLayer.addConnection(new Connection(inputNeuron, outputNeuron, (float)Math.random()));
}
}
} else {
ArrayList<Neuron> inputNeurons = this.neuronLayers.get(layerIndex - 1);
ArrayList<Neuron> outputNeurons = this.neuronLayers.get(layerIndex);
for (Neuron inputNeuron : inputNeurons) {
for (Neuron outputNeuron : outputNeurons) {
connLayer.addConnection(new Connection(inputNeuron, outputNeuron, (float)Math.random()));
}
}
}
this.interconnectionsLayers.add(layerIndex, connLayer);
}
} else {
throw new InvalidLayerNumberException();
}
}
@Override
public String toString() {
return getNeuronMap();
}
public String getNeuronMap() {
StringBuffer map = new StringBuffer();
for (int i = 0; i < nrOfLayers; i++) {
map.append(String.valueOf(nrOfNeuronsPerLayer.get(i)));
map.append(" ");
}
map.deleteCharAt(map.length() - 1);
return map.toString();
}
public static void main(String[] args) {
ArrayList<Integer> nrOfNeuronsPerLayer = new ArrayList<Integer>();
nrOfNeuronsPerLayer.add(10);
nrOfNeuronsPerLayer.add(7);
nrOfNeuronsPerLayer.add(2);
BPNet net = new BPNet( (float)0.01, 3, 5, nrOfNeuronsPerLayer, (float)1.8, (float)0.7); // bigger slope = better resolution
String trainingSet = "0.4 0.5 1 0.5 1 0 1\n0 0 0 0 0 1 1\n0.1 0.2 0.3 0.4 0.5 0 0\n1 0 1 0 1 1 0\n0.2 0.4 0 0 0.9 0 1";
net.learn(trainingSet);
net.run("0.4 0.5 1 0.5 1"); //expected 0 1
System.out.println(net.getOutput());
net.run("0 0 0 0 0"); // 1 1
System.out.println(net.getOutput());
net.run("0.1 0.2 0.3 0.4 0.5"); // 0 0
System.out.println(net.getOutput());
net.run("1 0 1 0 1"); // 1 0
System.out.println(net.getOutput());
net.run("0.2 0.4 0 0 0.9"); // 0 1
System.out.println(net.getOutput());
System.out.println("Not trained elements:");
net.run("0.9 0.1 0.9 0.1 0.9"); // expected 1 0
System.out.println(net.getOutput());
net.run("0.01 0.01 0.01 0.01 0.01"); // expected 1 1
System.out.println(net.getOutput());
net.run("0.15 0.15 0.35 0.35 0.5"); // 0 0
System.out.println(net.getOutput());
System.out.println(net.getNeuronMap());
net.addNeuron(0, 1.8f);
System.out.println(net.getNeuronMap());
net.addNeuron(1, 1.8f);
System.out.println(net.getNeuronMap());
net.addNeuron(2, 1.8f);
System.out.println(net.getNeuronMap());
net.removeNeuron(0);
System.out.println(net.getNeuronMap());
net.removeNeuron(1);
System.out.println(net.getNeuronMap());
net.removeNeuron(2);
System.out.println(net.getNeuronMap());
net.addNeuronLayer(5, 0, 1.8f);
System.out.println(net.getNeuronMap());
net.addNeuronLayer(5, 2, 1.8f);
System.out.println(net.getNeuronMap());
net.addNeuronLayer(5, 5, 1.8f);
System.out.println(net.getNeuronMap());
net.removeNeuronLayer(5);
System.out.println(net.getNeuronMap());
net.removeNeuronLayer(2);
System.out.println(net.getNeuronMap());
net.removeNeuronLayer(0);
System.out.println(net.getNeuronMap());
net.learn(trainingSet);
net.run("0.4 0.5 1 0.5 1"); //expected 0 1
System.out.println(net.getOutput());
net.run("0 0 0 0 0"); // 1 1
System.out.println(net.getOutput());
net.run("0.1 0.2 0.3 0.4 0.5"); // 0 0
System.out.println(net.getOutput());
net.run("1 0 1 0 1"); // 1 0
System.out.println(net.getOutput());
net.run("0.2 0.4 0 0 0.9"); // 0 1
System.out.println(net.getOutput());
System.out.println("Not trained elements:");
net.run("0.9 0.1 0.9 0.1 0.9"); // expected 1 0
System.out.println(net.getOutput());
net.run("0.01 0.01 0.01 0.01 0.01"); // expected 1 1
System.out.println(net.getOutput());
net.run("0.15 0.15 0.35 0.35 0.5"); // 0 0
System.out.println(net.getOutput());
}
}
package cz.vsb.mro0010.neuralnetworks;
public class BinaryNeuron extends Neuron {
@Override
public void transfer() {
if (this.getPotential() > this.getThreshold()) {
this.setState(1);
} else {
this.setState(0);
}
}
}
package cz.vsb.mro0010.neuralnetworks;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.net.ConnectException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JOptionPane;
/**
* Jednoduchy ukazkovy klient.
* Pripoji se k zavodnimu serveru a ridi auto.
*
*/
public class CarDriverClient {
private Socket socket; // spojeni
private BufferedReader in; // cteni se serveru
private BufferedWriter out; // zapis na server
private BPNet neuralNetwork;
/**
* Pripoji se k zavodu.
*
* @param host zavodni server
* @param port port serveru
* @param raceName nazev zavodu, do nehoz se chce klient pripojit
* @param driverName jmeno ridice
* @throws java.lang.IOException problem s pripojenim
*/
public CarDriverClient(String host, int port, String raceName, String driverName, String carType, BPNet neuralNetwork) throws IOException {
// add neural net
this.neuralNetwork = neuralNetwork;
// connect to server
socket = new Socket(host, port);
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
// connect to race
out.write("driver\n"); // protocol specification
out.write("race:" + raceName + "\n"); // race name
out.write("driver:" + driverName + "\n"); // driver name
out.write("color:0000FF\n"); // car color
if(carType != null){
out.write("car:" + carType + "\n"); // car type
}
out.write("\n");
out.flush();
// precteni a kontrola dopovedi serveru
String line = in.readLine();
if (!line.equals("ok")) {
// pokud se pripojeni nepodari, je oznamena chyba a vyvolana vyjimka
System.err.println("Chyba: " + line);
throw new ConnectException(line);
}
in.readLine(); // precteni prazdneho radku
}
public static List<String> listRaces(String host, int port) throws IOException {
// pripojeni k serveru
Socket socket = new Socket(host, port);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
// pripojeni k zavodu
out.write("racelist\n"); // specifikace protokolu
out.write("\n");
out.flush();
// precteni a kontrola dopovedi serveru
String line = in.readLine();
if (!line.equals("ok")) {
// pokud se pripojeni nepodari, je oznamena chyba a vyvolana vyjimka
System.err.println("Chyba: " + line);
throw new ConnectException(line);
}
line = in.readLine(); // precteni prazdneho radku
List<String> racelist = new ArrayList<String>();
line = in.readLine();
System.out.println("Races:");
while(line != null && !"".equals(line)){
racelist.add(line);
System.out.println(line);
line = in.readLine();
}
return racelist;
}
public static List<String> listCars(String host, int port, String raceName) throws IOException {
// pripojeni k serveru
Socket socket = new Socket(host, port);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
// pripojeni k zavodu
out.write("carlist\n"); // specifikace protokolu
out.write("race:" + raceName + "\n");
out.write("\n");
out.flush();
// precteni a kontrola dopovedi serveru
String line = in.readLine();
if (!line.equals("ok")) {
// pokud se pripojeni nepodari, je oznamena chyba a vyvolana vyjimka
System.err.println("Chyba: " + line);
throw new ConnectException(line);
}
line = in.readLine(); // precteni prazdneho radku
List<String> carList = new ArrayList<String>();
line = in.readLine();
System.out.println("cars:");
while(line != null && !"".equals(line)){
carList.add(line);
System.out.println(line);
line = in.readLine();
}
return carList;
}
/**
* Beh zavodu. Cte data ze serveru. Spousti rizeni auta.
* Ukonci se po ukonceni zavodu.
*
* @throws java.io.IOException problem ve spojeni k serveru
*/
public void run() throws IOException {
while (true) { // smycka do konce zavodu
String line = in.readLine();
// System.out.println(line);
if (line.equals("round")) { // dalsi kolo v zavode
round();
} else if (line.equals("finish")) { // konec zavodu konci smucku
break;
} else {
System.err.println("Chyba se serveru: " + line);
}
}
}
/**
* Resi jedno posunuti auta. Precte pozici auta od servru,
* vypocte nastaveni rizeni, ktere na server.
*
* @throws java.io.IOException problem ve spojeni k serveru
*/
public void round() throws IOException {
float angle = 0; // uhel k care <0,1>
float speed = 0; // rychlost auta <0,1>
float distance0 = 0; // vzdalenost od cary <0,1>
float distance4 = 0; // vzdalenost od cary za 4m<0,1>
float distance8 = 0; // vzdalenost od cary za 8m<0,1>
float distance16 = 0; // vzdalenost od cary za 16m<0,1>
float distance32 = 0; // vzdalenost od cary za 32m<0,1>
float friction = 0;
float skid = 0;
float checkpoint = 0;
float sensorFrontLeft = 0;
float sensorFrontMiddleLeft = 0;
float sensorFrontMiddleRight = 0;
float sensorFrontRight = 0;
float sensorFrontRightCorner1 = 0;
float sensorFrontRightCorner2 = 0;
float sensorRight1 = 0;
float sensorRight2 = 0;
float sensorRearRightCorner2 = 0;
float sensorRearRightCorner1 = 0;
float sensorRearRight = 0;
float sensorRearLeft = 0;
float sensorRearLeftCorner1 = 0;
float sensorRearLeftCorner2 = 0;
float sensorLeft1 = 0;
float sensorLeft2 = 0;
float sensorFrontLeftCorner1 = 0;
float sensorFrontLeftCorner2 = 0;
// cteni dat ze serveru
String line = in.readLine();
// System.out.println(line);
while (line.length() > 0) {
String[] data = line.split(":", 2);
String key = data[0];
String value = data[1];
if (key.equals("angle")) {
angle = Float.parseFloat(value);
} else if (key.equals("speed")) {
speed = Float.parseFloat(value);
} else if (key.equals("distance0")) {
distance0 = Float.parseFloat(value);
} else if (key.equals("distance4")) {
distance4 = Float.parseFloat(value);
} else if (key.equals("distance8")) {
distance8 = Float.parseFloat(value);
} else if (key.equals("distance16")) {
distance16 = Float.parseFloat(value);
} else if (key.equals("distance32")) {
distance32 = Float.parseFloat(value);
} else if (key.equals("friction")) {
friction = Float.parseFloat(value);
} else if (key.equals("skid")) {
skid = Float.parseFloat(value);
} else if (key.equals("checkpoint")) {
checkpoint = Float.parseFloat(value);
} else if (key.equals("sensorFrontLeft")) {
sensorFrontLeft = Float.parseFloat(value);
} else if (key.equals("sensorFrontMiddleLeft")) {
sensorFrontMiddleLeft = Float.parseFloat(value);
} else if (key.equals("sensorFrontMiddleRight")) {
sensorFrontMiddleRight = Float.parseFloat(value);
} else if (key.equals("sensorFrontRight")) {
sensorFrontRight = Float.parseFloat(value);
} else if (key.equals("sensorFrontRightCorner1")) {
sensorFrontRightCorner1 = Float.parseFloat(value);
} else if (key.equals("sensorFrontRightCorner2")) {
sensorFrontRightCorner2 = Float.parseFloat(value);
} else if (key.equals("sensorRight1")) {
sensorRight1 = Float.parseFloat(value);
} else if (key.equals("sensorRight2")) {
sensorRight2 = Float.parseFloat(value);
} else if (key.equals("sensorRearRightCorner2")) {
sensorRearRightCorner2 = Float.parseFloat(value);
} else if (key.equals("sensorRearRightCorner1")) {
sensorRearRightCorner1 = Float.parseFloat(value);
} else if (key.equals("sensorRearRight")) {
sensorRearRight = Float.parseFloat(value);
} else if (key.equals("sensorRearLeft")) {
sensorRearLeft = Float.parseFloat(value);
} else if (key.equals("sensorRearLeftCorner1")) {
sensorRearLeftCorner1 = Float.parseFloat(value);
} else if (key.equals("sensorRearLeftCorner2")) {
sensorRearLeftCorner2 = Float.parseFloat(value);
} else if (key.equals("sensorLeft1")) {
sensorLeft1 = Float.parseFloat(value);
} else if (key.equals("sensorLeft2")) {
sensorLeft2 = Float.parseFloat(value);
} else if (key.equals("sensorFrontLeftCorner1")) {
sensorFrontLeftCorner1 = Float.parseFloat(value);
} else if (key.equals("sensorFrontLeftCorner2")) {
sensorFrontLeftCorner2 = Float.parseFloat(value);
} else {
System.err.println("Chyba se serveru: " + line);
}
line = in.readLine();
// System.out.println(line);
}
// vypocet nastaveni rizeni, ktery je mozno zmenit za jiny algoritmus
float acc; // zrychleni auta <0,1>
float wheel; // otoceni volantem (kolama) <0,1>
StringBuffer neuralNetInput = new StringBuffer();
// float angle = 0; // uhel k care <0,1>
// float speed = 0; // rychlost auta <0,1>
// float distance0 = 0; // vzdalenost od cary <0,1>
// float distance4 = 0; // vzdalenost od cary za 4m<0,1>
// float distance8 = 0; // vzdalenost od cary za 8m<0,1>
// float distance16 = 0; // vzdalenost od cary za 16m<0,1>
// float distance32 = 0; // vzdalenost od cary za 32m<0,1>
// float friction = 0;
// float skid = 0;
// float checkpoint = 0;
// float sensorFrontLeft = 0;
// float sensorFrontMiddleLeft = 0;
// float sensorFrontMiddleRight = 0;
// float sensorFrontRight = 0;
// float sensorFrontRightCorner1 = 0;
// float sensorFrontRightCorner2 = 0;
// float sensorRight1 = 0;
// float sensorRight2 = 0;
// float sensorRearRightCorner2 = 0;
// float sensorRearRightCorner1 = 0;
// float sensorRearRight = 0;
// float sensorRearLeft = 0;
// float sensorRearLeftCorner1 = 0;
// float sensorRearLeftCorner2 = 0;
// float sensorLeft1 = 0;
// float sensorLeft2 = 0;
// float sensorFrontLeftCorner1 = 0;
// float sensorFrontLeftCorner2 = 0;
// neuralNetInput.append(String.valueOf(angle));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(speed));
// neuralNetInput.append(" ");
neuralNetInput.append("0.5 0.5 ");
neuralNetInput.append(String.valueOf(distance0));
neuralNetInput.append(" ");
neuralNetInput.append(String.valueOf(distance4));
neuralNetInput.append(" ");
neuralNetInput.append(String.valueOf(distance8));
neuralNetInput.append(" ");
neuralNetInput.append(String.valueOf(distance16));
neuralNetInput.append(" ");
neuralNetInput.append(String.valueOf(distance32));
neuralNetInput.append(" ");
neuralNetInput.append("1 1 0.5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0");
// neuralNetInput.append(String.valueOf(friction));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(skid));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(checkpoint));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorFrontLeft));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorFrontMiddleLeft));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorFrontMiddleRight));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorFrontRight));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorFrontRightCorner1));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorFrontRightCorner2));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorRight1));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorRight2));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorRearRightCorner2));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorRearRightCorner1));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorRearRight));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorRearLeft));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorRearLeftCorner1));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorRearLeftCorner2));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorLeft1));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorLeft2));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorFrontLeftCorner1));
// neuralNetInput.append(" ");
// neuralNetInput.append(String.valueOf(sensorFrontLeftCorner2));
neuralNetwork.run(neuralNetInput.toString());
String output = neuralNetwork.getOutput();
String[] outputArray = output.split(" ");
wheel = Float.parseFloat(outputArray[0]);
acc = Float.parseFloat(outputArray[1]);
// odpoved serveru
out.write("ok\n");
out.write("acc:" + acc + "\n");
out.write("wheel:" + wheel + "\n");
out.write("\n");
out.flush();
}
/**
* Funkce, ktera vytvari a spousti klienta.
*
* @param args pole argumentu: server port nazev_zavodu jmeno_ridice
* @throws java.io.IOException problem ve spojeni k serveru, zavodu
*/
public static void main(String[] args) throws IOException {
// String host = "java.cs.vsb.cz";
// int port = 9460;
String host = "localhost";
// int port = 9461; // test
int port = 9460; // normal
String raceName = "Zavod";
String driverName = "basic_client";
String carType = null;
if (args.length < 4) {
// kontrola argumentu programu
System.err.println("argumenty: server port nazev_zavodu jmeno_ridice [typ_auta]");
List<String> raceList = CarDriverClient.listRaces(host, port);
raceName = raceList.get(new Random().nextInt(raceList.size()));
List<String> carList = CarDriverClient.listCars(host, port, raceName);
carType = carList.get(0);
driverName += "_" + carType;
// host = JOptionPane.showInputDialog("Host:", host);
// port = Integer.parseInt(JOptionPane.showInputDialog("Port:", Integer.toString(port)));
// raceName = JOptionPane.showInputDialog("Race name:", raceName);
// driverName = JOptionPane.showInputDialog("Driver name:", driverName);
} else {
// nacteni parametu
host = args[0];
port = Integer.parseInt(args[1]);
raceName = args[2];
driverName = args[3];
if(args.length > 4){
carType = args[4];
}
}
// vytvoreni neuronove site
ArrayList<Integer> nrOfNeuronsPerLayer = new ArrayList<Integer>();
//nrOfNeuronsPerLayer.add(20);
// nrOfNeuronsPerLayer.add(15);
// nrOfNeuronsPerLayer.add(10);
// nrOfNeuronsPerLayer.add(2);
nrOfNeuronsPerLayer.add(3);
nrOfNeuronsPerLayer.add(3);
nrOfNeuronsPerLayer.add(2);
BPNet neuralNet = new BPNet(0.1f, 3, 28, nrOfNeuronsPerLayer, 1.4f, 0.4f);
FileReader fr = new FileReader(new File("C:\\Users\\Martin\\Desktop\\NSProjekty\\testTrainingSet5.txt"));
StreamTokenizer tokenizer = new StreamTokenizer(fr);
/*for (int i = 0; i < 6; i++ )
tokenizer.nextToken();
*/
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
int nrOfLayers = (int)tokenizer.nval;
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
int nrOfInputs = (int)tokenizer.nval;
tokenizer.nextToken();
tokenizer.nextToken();
tokenizer.nextToken();
tokenizer.nextToken();
ArrayList<float[]> inputRanges = new ArrayList<float[]>();
ArrayList<String> inputNames = new ArrayList<String>();
for (int i = 0; i < nrOfInputs; i++) {
String inputName = tokenizer.sval;
inputNames.add(inputName);
tokenizer.nextToken();
float[] dims = new float[2];
dims[0] = (float)tokenizer.nval;
tokenizer.nextToken();
dims[1] = (float)tokenizer.nval;
inputRanges.add(dims);
tokenizer.nextToken();
}
/*for (int i = 0; i < 3; i++ )
tokenizer.nextToken();*/
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
nrOfNeuronsPerLayer = new ArrayList<Integer>();
int nrOfOutputs = 0;
for (int i = 0; i < nrOfLayers; i++) {
nrOfNeuronsPerLayer.add((int)tokenizer.nval);
if (i == nrOfLayers - 1) {
nrOfOutputs = (int)tokenizer.nval;
}
tokenizer.nextToken();
}
for (int i = 0; i < 3; i++ )
tokenizer.nextToken();
ArrayList<String> outputNames = new ArrayList<String>();
for (int i = 0; i < nrOfOutputs; i++) {
outputNames.add(tokenizer.sval);
tokenizer.nextToken();
}
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
float learnCoeff = (float)tokenizer.nval;
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
float inertiaCoeff = (float)tokenizer.nval;
/*for (int i = 0; i < 7; i++ )
tokenizer.nextToken();*/
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
int nrOfTrainingElements = (int)tokenizer.nval;
/*for (int i = 0; i < 4; i++ )
tokenizer.nextToken();*/
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nrOfTrainingElements; i++) {
for (int j = 0; j < nrOfInputs; j++) {
sb.append(String.valueOf(tokenizer.nval/(inputRanges.get(j)[1]-inputRanges.get(j)[0]) - inputRanges.get(j)[0]/(inputRanges.get(j)[1]-inputRanges.get(j)[0])));
sb.append(" ");
tokenizer.nextToken();
}
for (int j = 0; j < nrOfOutputs; j++) {
sb.append(String.valueOf(tokenizer.nval));
sb.append(" ");
tokenizer.nextToken();
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
}
String trainingData = sb.toString();
sb = new StringBuffer();
/*for (int i = 0; i < 5; i++ )
tokenizer.nextToken();*/
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
int nrOfTestElements = (int)tokenizer.nval;
String testData;
/*tokenizer.nextToken();*/
if (nrOfTestElements > 0) {
while(tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {}
for (int i = 0; i < nrOfTestElements; i++) {
for (int j = 0; j < nrOfInputs; j++) {
sb.append(String.valueOf(String.valueOf(tokenizer.nval/(inputRanges.get(j)[1]-inputRanges.get(j)[0]) - inputRanges.get(j)[0]/(inputRanges.get(j)[1]-inputRanges.get(j)[0]))));
sb.append(" ");
tokenizer.nextToken();
}
sb.deleteCharAt(sb.lastIndexOf(" "));
sb.append("\n");
}
testData = sb.substring(0,sb.lastIndexOf("\n"));
} else {
testData = "";
}
fr.close();
String trainingSet = trainingData;
System.out.println("Learning started.");
;
System.out.println("Net learned in " + neuralNet.learn(trainingSet) + " iterations");
// vytvoreni klienta
CarDriverClient driver = new CarDriverClient(host, port, raceName, driverName, carType, neuralNet);
// spusteni
driver.run();
}
}
package cz.vsb.mro0010.neuralnetworks;
public class Connection {
private Neuron inputNeuron;
private Neuron outputNeuron;
private float weight;
public Connection(Neuron inputNeuron, Neuron outputNeuron, float weight) {
this.setInputNeuron(inputNeuron);
this.setOutputNeuron(outputNeuron);
this.setWeight(weight);
}
protected Neuron getInputNeuron() {
return inputNeuron;
}
protected void setInputNeuron(Neuron inputNeuron) {
this.inputNeuron = inputNeuron;
}
protected Neuron getOutputNeuron() {
return outputNeuron;
}
protected void setOutputNeuron(Neuron outputNeuron) {
this.outputNeuron = outputNeuron;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public void adjustWeight(float value) {
this.weight += value;
}
public void passSignal() {
outputNeuron.adjustPotential(inputNeuron.getState()*this.getWeight());
}
@Override
public String toString() {
return "Weight: " + this.getWeight();
}
}
package cz.vsb.mro0010.neuralnetworks;
public class InputLayerPseudoNeuron extends Neuron {
public InputLayerPseudoNeuron() {
super();
}
@Override
public void transfer() {
this.setState(this.getPotential());
}
}
package cz.vsb.mro0010.neuralnetworks;
import java.util.ArrayList;
public abstract class Interconnections {
protected ArrayList<Connection> connections;
public ArrayList<Connection> getConnections() {
return connections;
}
public Interconnections() {
this.connections = new ArrayList<Connection>();
}
public void addConnection(Connection connection) {
this.connections.add(connection);
}
// public void passSignal() {
// for (Connection c : this.connections) {
//
// Neuron n = c.getOutputNeuron();
// n.initialize();
// for (Connection cn : this.connections) {
// if (cn.getOutputNeuron().equals(n)) {
// cn.passSignal();
// }
// }
// n.transfer();
// }
// }
public void passSignal() { // Faster version
ArrayList<Neuron> processedNeurons = new ArrayList<Neuron>();
for (Connection c : this.connections) {
Neuron n = c.getOutputNeuron();
if (!processedNeurons.contains(n)) {
processedNeurons.add(n);
n.initialize();
for (Connection cn : this.connections) {
if (cn.getOutputNeuron().equals(n)) {
cn.passSignal();
}
}
n.transfer();
}
}
}
public abstract void adjustWeights();
}
package cz.vsb.mro0010.neuralnetworks;
public class InterconnectionsBP extends InterconnectionsMultiLayer {
public InterconnectionsBP(float learningRate) {
super(learningRate);
}
public void setLearningRate(float learningRate) {
this.learningRate = learningRate;
}
@Override
public void adjustWeights() { // backPropagation - set new weights !after! all deltas are calculated
for (Connection connection : this.connections) {
float delta = ((SigmoidalNeuron)connection.getOutputNeuron()).getError();
float lambda = ((SigmoidalNeuron)connection.getOutputNeuron()).getSlope();
float y = connection.getOutputNeuron().getState();
float x = connection.getInputNeuron().getState();
float errorDerivative = delta*lambda*y*(1-y)*x;
connection.adjustWeight(-learningRate*errorDerivative);
}
}
}
package cz.vsb.mro0010.neuralnetworks;
public abstract class InterconnectionsMultiLayer extends Interconnections {
protected float learningRate; //eta
public InterconnectionsMultiLayer(float learningRate) {
this.learningRate = learningRate;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment