Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Network {
- /**
- * Глобальная ошибка для обучения.
- */
- protected double globalError;
- /**
- * количество нейронов ввода
- */
- protected int inputCount;
- /**
- * количество скрытых нейронов
- */
- protected int hiddenCount;
- /**
- * количество нейронов выхода
- */
- protected int outputCount;
- /**
- * количество нейронов
- */
- protected int neuronCount;
- /**
- * The number of weights in the network.
- */
- protected int weightCount;
- /**
- * The learning rate.
- */
- protected double learnRate;
- /**
- * массив сигмоид нейронов.
- */
- protected double fire[];
- /**
- * Весовая матрица, считается «памятью» нейронной сети.
- */
- protected double matrixWeights[];
- /**
- * The errors from the last calculation.
- */
- protected double error[];
- /**
- * Accumulates matrixWeights delta's for training.
- */
- protected double accMatrixDelta[];
- /**
- * The thresholds, this value, along with the weight matrixWeights
- * can be thought of as the memory of the neural network.
- */
- protected double thresholds[];
- /**
- * The changes that should be applied to the weight
- * matrixWeights.
- */
- protected double matrixDelta[];
- /**
- * The accumulation of the threshold deltas.
- */
- protected double accThresholdDelta[];
- /**
- * The threshold deltas.
- */
- protected double thresholdDelta[];
- /**
- * The momentum for training.
- */
- protected double momentum;
- /**
- * The changes in the errors.
- */
- protected double errorDelta[];
- /**
- * @param inputCount Количество входных нейронов.
- * @param hiddenCount Количество скрытых нейронов
- * @param outputCount Количество выходных нейронов
- * @param learnRate Уровень обучения, который будет использоваться при обучении.
- * @param momentum Импульс, который будет использоваться при обучении.
- */
- public Network(int inputCount,
- int hiddenCount,
- int outputCount,
- double learnRate,
- double momentum) {
- this.learnRate = learnRate;
- this.momentum = momentum;
- this.inputCount = inputCount;
- this.hiddenCount = hiddenCount;
- this.outputCount = outputCount;
- neuronCount = inputCount + hiddenCount + outputCount;
- weightCount = (inputCount * hiddenCount) + (hiddenCount * outputCount);
- fire = new double[neuronCount];
- matrixWeights = new double[weightCount];
- matrixDelta = new double[weightCount];
- thresholds = new double[neuronCount];
- errorDelta = new double[neuronCount];
- error = new double[neuronCount];
- accThresholdDelta = new double[neuronCount];
- accMatrixDelta = new double[weightCount];
- thresholdDelta = new double[neuronCount];
- reset();
- }
- /**
- * Сигмоид, вычисляем экспоненту
- */
- public double threshold(double sum) {
- return 1.0 / (1 + Math.exp(-1.0 * sum));
- }
- /**
- * Вычислить результат
- * @param input обеспечивает нейронную сеть входными данными.
- * @return Результаты выходных нейронов.
- */
- public double[] computeOutputs(double input[]) {
- final int hiddenIndex = inputCount;
- final int outIndex = inputCount + hiddenCount;
- for (int i = 0; i < inputCount; i++) {// вытаскиваем входные данные и записываем в fire
- fire[i] = input[i];
- }
- //Из формулы видно, что входная информация — это сумма всех входных данных, умноженных на соответствующие им веса.
- // Тогда дадим на вход 1 и 0. Пусть w1=0.4 и w2 = 0.7 Входные данные нейрона Н1 будут следующими: 1*0.4+0*0.7=0.4.
- // Теперь когда у нас есть входные данные, мы можем получить выходные данные,
- // подставив входное значение в функцию активации
- // first layer
- for (int i = hiddenIndex; i < outIndex; i++) {
- double sum = thresholds[i];
- for (int j = 0; j < inputCount; j++) {
- sum += fire[j] * matrixWeights[j];
- }
- fire[i] = threshold(sum);//функция активации
- }
- // hidden layer
- double result[] = new double[outputCount];// сигмоид выходного нейрона
- for (int i = outIndex; i < neuronCount; i++) {
- double sum = thresholds[i];
- for (int j = hiddenIndex; j < outIndex; j++) {
- sum += fire[j] * matrixWeights[j];
- }
- fire[i] = threshold(sum);
- result[i - outIndex] = fire[i];
- }
- return result;
- }
- /**
- * Вычислите ошибку для только что достигнутого распознавания.
- *
- * @param ideal Что должны были дать выходные нейроны.
- */
- public void calcError(double ideal[]) {
- int i, j;
- final int hiddenIndex = inputCount;
- final int outputIndex = inputCount + hiddenCount;
- // очистить ошибки скрытого слоя
- for (i = inputCount; i < neuronCount; i++) {
- error[i] = 0;
- }
- // ошибки слоя и дельта для уровня вывода
- for (i = outputIndex; i < neuronCount; i++) {
- error[i] = ideal[i - outputIndex] - fire[i];
- globalError += error[i] * error[i];
- errorDelta[i] = error[i] * fire[i] * (1 - fire[i]);
- }
- // ошибки скрытого слоя
- int winx = inputCount * hiddenCount;
- for (i = outputIndex; i < neuronCount; i++) {
- for (j = hiddenIndex; j < outputIndex; j++) {
- accMatrixDelta[winx] += errorDelta[i] * fire[j];
- error[j] += matrixWeights[winx] * errorDelta[i];
- winx++;
- }
- accThresholdDelta[i] += errorDelta[i];
- }
- // скрытый слой дельты
- for (i = hiddenIndex; i < outputIndex; i++) {
- errorDelta[i] = error[i] * fire[i] * (1 - fire[i]);
- }
- // ошибки входного слоя
- winx = 0; // смещение массива весов
- for (i = hiddenIndex; i < outputIndex; i++) {
- for (j = 0; j < hiddenIndex; j++) {
- accMatrixDelta[winx] += errorDelta[i] * fire[j];
- error[j] += matrixWeights[winx] * errorDelta[i];
- winx++;
- }
- accThresholdDelta[i] += errorDelta[i];
- }
- }
- /**
- * Modify the weight matrixWeights and thresholds based on the last call to
- * calcError.
- */
- public void learn() {
- int i;
- // process the matrixWeights
- for (i = 0; i < matrixWeights.length; i++) {
- matrixDelta[i] = (learnRate * accMatrixDelta[i]) + (momentum * matrixDelta[i]);
- matrixWeights[i] += matrixDelta[i];
- accMatrixDelta[i] = 0;
- }
- // process the thresholds
- for (i = inputCount; i < neuronCount; i++) {
- thresholdDelta[i] = learnRate * accThresholdDelta[i] + (momentum * thresholdDelta[i]);
- thresholds[i] += thresholdDelta[i];
- accThresholdDelta[i] = 0;
- }
- }
- /**
- * Сброс весов
- */
- public void reset() {
- int i;
- for (i = 0; i < neuronCount; i++) {
- thresholds[i] = 0.5 - (Math.random());
- thresholdDelta[i] = 0;
- accThresholdDelta[i] = 0;
- }
- for (i = 0; i < matrixWeights.length; i++) {
- matrixWeights[i] = 0.5 - (Math.random());
- matrixDelta[i] = 0;
- accMatrixDelta[i] = 0;
- }
- }
- }
- public class TestNeuralNetwork {
- public static void main(String args[])
- {
- double xorInput[][] = {
- {1.0,0.0},
- {0.0,0.0},
- {0.0,1.0},
- {1.0,1.0}
- };
- double xorIdeal[][] = { {1.0},{0.0},{0.0},{1.0}};
- Network network = new Network(2,2,1,0.7,0.9);
- for (int i=0;i<10000;i++) {
- for (int j=0;j<xorInput.length;j++) {
- network.computeOutputs(xorInput[j]);
- network.calcError(xorIdeal[j]);
- network.learn();
- }
- }
- for (int i=0;i<xorInput.length;i++) {
- for (int j=0;j<xorInput[0].length;j++) {
- System.out.print( xorInput[i][j] +":" );
- }
- double out[] = network.computeOutputs(xorInput[i]);
- System.out.println("="+out[0]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement