Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace neuro {
- class NeuralNetwork {
- private double?[][] network;
- private double?[] results;
- private int inputs;
- private int hide;
- private int outputs;
- private int cnt;
- private Random rnd = new Random();
- public NeuralNetwork(int inputs, int hide) {
- this.inputs = inputs;
- this.hide = hide;
- this.outputs = 1;
- int n = inputs + hide + outputs;
- this.cnt = n;
- network = new double?[n][];
- results = new double?[n];
- for (int i = 0; i < n; ++ i) {
- network[i] = new double?[n];
- for (int j = 0; j < n; ++ j) {
- network[i][j] = null;
- }
- }
- for (int i = 0; i < inputs; ++ i) {
- for (int j = 0; j < hide; ++ j) {
- network[i][inputs + j] = 1.0 / rnd.Next(1, 101);
- }
- }
- for (int i = 0; i < hide; ++ i) {
- for (int j = 0; j < outputs; ++ j) {
- network[inputs + i][inputs + hide + j] = 1.0 / rnd.Next(1, 101);
- }
- }
- }
- public double F(double x) {
- return 1.0 / (1.0 + Math.Exp(-x));
- }
- public void Init(double[] inputValues) {
- if (inputValues.Length != inputs) throw new Exception();
- for (int i = 0; i < cnt; ++ i) {
- results[i] = null;
- }
- for (int i = 0; i < inputs; ++ i) {
- results[i] = inputValues[i];
- }
- }
- public double Count() {
- for (int i = inputs; i < cnt; ++ i) {
- double s = 0;
- for (int j = 0; j < cnt; ++ j) {
- if (network[j][i] != null)
- s += (double)results[j] * (double)network[j][i];
- }
- results[i] = F(s);
- }
- double answer = (double)results[inputs + hide];
- return answer;
- }
- private bool isOutputNeuron(int n) {
- for (int i = 0; i < cnt; ++ i) {
- if (network[n][i] != null)
- return false;
- }
- return true;
- }
- private bool isInputNeuron(int n) {
- for (int i = 0; i < cnt; ++ i) {
- if (network[i][n] != null)
- return false;
- }
- return true;
- }
- public void Learn(double[] test, double testAnswer) {
- double[] errors = new double[cnt];
- Init(test);
- for (int i = cnt - 1; i >= 0; -- i) {
- if (isOutputNeuron(i)) {
- errors[i] = testAnswer - Count();
- continue;
- }
- else if (isInputNeuron(i)) continue;
- double s = 0;
- for (int j = 0; j < cnt; ++ j) {
- if (network[i][j] != null) {
- s += errors[j] * (double)network[i][j];
- }
- }
- errors[i] = (double)results[i] * (1 - (double)results[i]) * s;
- }
- for (int i = 0; i < cnt; ++ i) {
- if (isOutputNeuron(i)) continue;
- for (int j = 0; j < cnt; ++ j) {
- if (network[i][j] != null) {
- network[i][j] += (double)results[i] * errors[j] * (double)results[j] * (1 - (double)results[j]);
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement