Скачиваний:
0
Добавлен:
26.10.2025
Размер:
133.02 Кб
Скачать

3.5. Отдельный индивида в генетическом алгоритме gaPerceptronIndividual.Cs

namespace PerceptronSymbolsHybrid

{

public class GAPerceptronIndividual

{

XMin = xmin;

XMax = xmax;

Weights = genes.Select(g => Math.Max(xmin, Math.Min(g, xmax))).ToList();

TargetSymbol = targetSymbol;

this.trainingSet = trainingSet;

EvaluateFitness();

}

public static int Predict(List<double> weights, int[] input)

{

double sum = 0;

for (int i = 0; i < weights.Count; i++)

sum += weights[i] * input[i];

return sum >= 0 ? 1 : 0;

}

public void EvaluateFitness()

{

int errorCount = 0;

foreach (var sample in trainingSet)

{

int expected = (sample.Label == TargetSymbol) ? 1 : 0;

int output = Predict(Weights, sample.Input);

if (output != expected)

errorCount++;

}

Fitness = (double)errorCount / trainingSet.Count * 100.0;

}

public void UniformMutation(double mutationProbability, Random rnd)

{

if (rnd.NextDouble() < mutationProbability)

{

int index = rnd.Next(Weights.Count);

double delta = (XMax - XMin) * 0.05; // 5% от диапазона

double mutation = (rnd.NextDouble() * 2 - 1) * delta;

double newVal = Weights[index] + mutation;

newVal = Math.Max(XMin, Math.Min(newVal, XMax));

Weights[index] = newVal;

EvaluateFitness();

}

}

public static (GAPerceptronIndividual, GAPerceptronIndividual) BLXabCrossover(

GAPerceptronIndividual parent1,

GAPerceptronIndividual parent2,

double a, double b,

double xmin, double xmax,

Random rnd)

{

if (parent1.Weights.Count != parent2.Weights.Count)

throw new Exception("Размерность хромосом должна совпадать.");

int n = parent1.Weights.Count;

List<double> child1Genes = new List<double>();

List<double> child2Genes = new List<double>();

for (int i = 0; i < n; i++)

{

double x = parent1.Weights[i];

double y = parent2.Weights[i];

double d = Math.Abs(x - y);

double lower, upper;

if (x <= y)

{

lower = x - a * d;

upper = y + b * d;

}

else

{

lower = y - b * d;

upper = x + a * d;

}

double gene1 = lower + rnd.NextDouble() * (upper - lower);

double gene2 = lower + rnd.NextDouble() * (upper - lower);

gene1 = Math.Max(xmin, Math.Min(gene1, xmax));

gene2 = Math.Max(xmin, Math.Min(gene2, xmax));

child1Genes.Add(gene1);

child2Genes.Add(gene2);

}

GAPerceptronIndividual child1 = new GAPerceptronIndividual(child1Genes, xmin, xmax, parent1.TargetSymbol, parent1.trainingSet);

GAPerceptronIndividual child2 = new GAPerceptronIndividual(child2Genes, xmin, xmax, parent1.TargetSymbol, parent1.trainingSet);

return (child1, child2);

}

}

}

Соседние файлы в предмете Методы и модели искусственного интеллекта в управлении техническими системами