Нейронные сети и генетический алгоритм
import random
import numpy as np
import matplotlib.pyplot as plt
from deap import base, creator, tools, algorithms
import gym
import algelitism
import tensorflow as tf
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
# Инициализация весов
self.weights_input_hidden = tf.Variable(tf.random.normal([input_size, hidden_size]))
self.weights_hidden_output = tf.Variable(tf.random.normal([hidden_size, output_size]))
def get_total_weights(self):
# Подсчет общего числа весов в нейросети
return tf.size(self.weights_input_hidden) + tf.size(self.weights_hidden_output)
def get_weights(self):
# Получение общего числа весов в виде строки
total_weights = self.get_total_weights()
return f"({total_weights.numpy()} весов)"
def set_weights(self, new_weights):
# Установка новых весов для нейросети
if len(new_weights) == self.get_total_weights():
start = 0
end = tf.size(self.weights_input_hidden)
self.weights_input_hidden.assign(tf.reshape(new_weights[start:end], self.weights_input_hidden.shape))
start = end
end = start + tf.size(self.weights_hidden_output)
self.weights_hidden_output.assign(tf.reshape(new_weights[start:end], self.weights_hidden_output.shape))
else:
raise ValueError("Неверное количество весов")
def forward(self, input_data):
# Прямое распространение с активациями
hidden_activations = tf.nn.relu(np.dot(input_data, self.weights_input_hidden) + 1)
output_activations = tf.nn.softmax(np.dot(hidden_activations, self.weights_hidden_output) + 1)
return output_activations
def predict(self, input_data):
# Получение предсказания от нейросети
return self.forward(input_data)
nn = NeuralNetwork(4,5,4)
def update_agent_coordinates(action, agent_coordinates):
# Получение индекса максимального значения в массиве action
# Применение действия к координатам агента
if action == 0:
# Движение вперед: К первому числу прибавляется 1
agent_coordinates[0] += 1
elif action == 1:
# Движение назад: От первого числа отнимается 1
agent_coordinates[0] -= 1
elif action == 2:
# Движение вправо: К второму числу прибавляется 1
agent_coordinates[1] += 1
elif action == 3:
# Движение влево: От второго числа отнимается 1
agent_coordinates[1] -= 1
return agent_coordinates
def get_apple_coordinates():
# Генерация случайных координат яблока в диапазоне от -100 до 100
apple = np.array([random.randint(-100, 100), random.randint(-100, 100)])
return apple
def compute_reward(agent_coordinates, apple_coordinates):
# Пример: расстояние между координатами агента и яблока
distance = np.sqrt((agent_coordinates[0] - apple_coordinates[0])**2 + (agent_coordinates[1] - apple_coordinates[1])**2)
# Пример: штраф за дальнее расстояние
penalty_threshold = 20.0
penalty = 1.0 if distance > penalty_threshold else 0.0
# Пример: высокое вознаграждение, уменьшающееся с приближением к яблоку
high_reward = 10.0
scaling_factor = 0.1 # Уменьшает вознаграждение с приближением к яблоку
# Вычисление вознаграждения с учетом штрафа и расстояния
reward = high_reward - scaling_factor * distance - penalty
return reward
def get_fitness(individual):
nn.set_weights(individual)
max_generations = 500
goal_reached = False
total_reward = 0
for generation in range(max_generations):
# Получение координат яблока и агента
apple_coordinates = get_apple_coordinates() # Ваш код получения координат яблока
agent_coordinates = np.array([0, 0]) # Начальные координаты агента
# Получение предсказания от нейросети
input_data = np.concatenate([apple_coordinates, agent_coordinates])
action = np.argmax(nn.predict(input_data.reshape(1, -1)))
# Выполнение действия в среде
agent_coordinates = update_agent_coordinates(action, agent_coordinates)
if (agent_coordinates == apple_coordinates).all():
goal_reached = True
reward = compute_reward(agent_coordinates, apple_coordinates)
total_reward += reward
# Проверка условий остановки
if goal_reached or generation >= max_generations:
break
return total_reward,
LENGTH_CHROM = 4 * 5 + 5 * 4
print(4 * 5 + 5 * 4)
LOW = 1.0
UP = -1.0
ETA = 20
POPULATION_SIZE = 50
P_CROSSOVER = 0.9
P_MUTATION = 0.2
MAX_GENERATIONS = 150
HALL_OF_FAME_SIZE = 2
hof = tools.HallOfFame(HALL_OF_FAME_SIZE)
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("randomWeight", random.uniform, -1.0, 1.0)
toolbox.register("individualCreator", tools.initRepeat, creator.Individual, toolbox.randomWeight, LENGTH_CHROM)
toolbox.register("populationCreator", tools.initRepeat, list, toolbox.individualCreator)
population = toolbox.populationCreator(n=POPULATION_SIZE)
toolbox.register("evaluate", get_fitness)
toolbox.register("select", tools.selTournament, tournsize=2)
toolbox.register("mate", tools.cxSimulatedBinaryBounded, low=LOW, up=UP, eta=ETA)
toolbox.register("mutate", tools.mutUniformInt,low=LOW, up=UP, eta=ETA, indpb=1.0/LENGTH_CHROM)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("max", np.max)
stats.register("avg", np.mean)
population, logbook = algelitism.eaSimpleElitism(population, toolbox,
cxpb=P_CROSSOVER,
mutpb=P_MUTATION,
ngen=MAX_GENERATIONS,
stats=stats,
halloffame=hof,
verbose=True)
max_fitness_values, mean_fitness_values = logbook.select("max", "avg")
best = hof.items[0]
print(best)
plt.plot(max_fitness_values, color="red", label="Минимальная приспособленность")
plt.plot(mean_fitness_values, color="green", label="Средняя приспособленность")
plt.xlabel("Поколение")
plt.ylabel("Приспособленность")
plt.title("Динамика приспособленности в течение поколений")
plt.legend()
plt.show()
выдает ошибку
40
gen nevals max avg
0 50 786.659 656.63
Traceback (most recent call last):
File "C:\Програмирование\Python\Тестовые файлы пайтон\mygen.py", line 157, in <module>
population, logbook = algelitism.eaSimpleElitism(population, toolbox,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Програмирование\Python\Тестовые файлы пайтон\algelitism.py", line 35, in eaSimpleElitism
offspring = varAnd(offspring, toolbox, cxpb, mutpb)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\blago\AppData\Local\Programs\Python\Python311\Lib\site-packages\deap\algorithms.py", line 73, in varAnd
offspring[i - 1], offspring[i] = toolbox.mate(offspring[i - 1],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\blago\AppData\Local\Programs\Python\Python311\Lib\site-packages\deap\tools\crossover.py", line 349, in cxSimulatedBinaryBounded
c1 = min(max(c1, xl), xu)
^^^^^^^^^^^
TypeError: '>' not supported between instances of 'float' and 'complex'
Почему выдает ошибку, ведь в коде я не задавал комплексных чисел?