// Factory method public static NeuronLayer copyLayer(int nbNeurons, int nbInputs, NeuronLayer original) { double[][] weights = new double[nbNeurons][]; Random geneticRandomizer = new Random((++someInt + Environment.TickCount) * 2); Random weightRandomizer = new Random((++someInt + Environment.TickCount) * 2); for (int i = 0; i < nbNeurons; i++) { weights[i] = new double[nbInputs + 1]; // +1 for the bias for (int j = 0; j < nbInputs + 1; j++) { if (geneticRandomizer.Next(0, Params.MUTATION_FREQUENCY) % Params.MUTATION_FREQUENCY == 0) // Mutation { weights[i][j] = Params.getRandomWeight(weightRandomizer); } else // no mutation { weights[i][j] = original.InputWeights[i][j]; } } } return(new NeuronLayer(nbNeurons, weights)); }
/** * Build's the neural net with one input layer and nbHiddenLayers hidden layers **/ public NeuralNet(int nbNeuronsPerLayer, int nbHiddenLayers) { this.nbNeuronsPerLayer = nbNeuronsPerLayer; this.nbHiddenLayers = nbHiddenLayers; // Build input layer this.inputLayer = NeuronLayer.buildNewLayer(nbNeuronsPerLayer, Program.Params.NB_INPUT_COLUMNS); // Build hidden layers this.hiddenLayers = new NeuronLayer[nbHiddenLayers]; for (int i = 0; i < nbHiddenLayers; i++) { this.hiddenLayers[i] = NeuronLayer.buildNewLayer(nbNeuronsPerLayer, nbNeuronsPerLayer); } this.outputLayer = NeuronLayer.buildNewLayer(1, nbNeuronsPerLayer); }
} // private constructor for cloning /** * Copy's the neural net and returns a new one with genetic mutations **/ public static NeuralNet getGeneticClone(NeuralNet original) { NeuralNet clone = new NeuralNet(); clone.nbNeuronsPerLayer = original.nbNeuronsPerLayer; clone.nbHiddenLayers = original.nbHiddenLayers; clone.inputLayer = NeuronLayer.copyLayer(original.nbNeuronsPerLayer, Program.Params.NB_INPUT_COLUMNS, original.inputLayer); clone.hiddenLayers = new NeuronLayer[original.nbHiddenLayers]; for (int i = 0; i < original.nbHiddenLayers; i++) { clone.hiddenLayers[i] = NeuronLayer.copyLayer(original.nbNeuronsPerLayer, original.nbNeuronsPerLayer, original.hiddenLayers[i]); } clone.outputLayer = NeuronLayer.copyLayer(1, original.nbNeuronsPerLayer, original.outputLayer); return(clone); }