/// <summary> /// Save network to JSON file in application directory /// </summary> /// <param name="name">name of the saved file. Example - test.json</param> //public void SaveJSON(string name) //{ // string text = JsonSerializer.Serialize(this); // System.IO.File.WriteAllText(Environment.CurrentDirectory + "//" + name, text); //} ///// <summary> ///// Load network from JSON file in application directory ///// </summary> ///// <param name="filename">name of the uploaded file. Example - test.json</param> ///// <returns></returns> //public static NeuronNetwork LoadJSON (string filename) //{ // string text = System.IO.File.ReadAllText(Environment.CurrentDirectory + "//" + filename); // return JsonSerializer.Deserialize<NeuronNetwork>(text); //} public object Clone() { NeuronNetwork nw = new NeuronNetwork(); foreach (var a in layers) { NeuronLayer l = new NeuronLayer(); nw.AddLayer(l); foreach (var n in a.neurons) { l.AddNeuron((Neuron)Activator.CreateInstance(n.GetType())); } } nw.Create(); return(nw); }
} //провести рассчет если нейроны уже имеют входные значения /// <summary> /// Calculate answer using input data /// </summary> /// <param name="IN">Input values for first layer neurons</param> /// <returns></returns> public double[] GetAnswer(params double[] IN) //перегрузка с авто передачей входа на входной уровень нс { Reset(); NeuronLayer l1 = layers[0]; if (IN.Length != l1.neurons.Count) { throw new Exception("Incorrect input"); } for (int i = 0; i < IN.Length; i++) { l1.neurons[i].In = IN[i]; } return(GetAnswer()); }
/// <summary> /// Corrects weights using backpropagation algorithm /// </summary> /// <param name="koef">learning rate</param> /// <param name="expectedConclusions">expected conclusions</param> public void Backward(double koef, params double[] expectedConclusions) { ResetErrors(); if (expectedConclusions.Length != layers[layers.Count - 1].neurons.Count) { throw new Exception("Error"); } NeuronLayer last = layers[layers.Count - 1]; for (int i = 0; i < last.neurons.Count; i++) { last.neurons[i].error = (expectedConclusions[i] - last.neurons[i].Out); } for (int nextlayerIndex = layers.Count - 1; nextlayerIndex >= 1; nextlayerIndex--) { NeuronLayer nextLayer = layers[nextlayerIndex]; NeuronLayer curLayer = layers[nextlayerIndex - 1]; for (int nn = 0; nn < nextLayer.neurons.Count; nn++) { Neuron nextNeuron = nextLayer.neurons[nn]; if (nextNeuron is BiasNeuron) { continue; } double errorkoef = nextNeuron.error * koef; for (int cn = 0; cn < curLayer.neurons.Count; cn++) { Neuron curNeuron = curLayer.neurons[cn]; double weight = curNeuron.outWeights[nn]; double deltaWeight = errorkoef * curNeuron.Out; curNeuron.outWeights[nn] = weight + deltaWeight; curNeuron.error += weight * nextNeuron.error * curNeuron.Derivative(curNeuron.In); } } } }