AttributeError: объект «ParticleSwarmOptimization» не имеет атрибута «global_best_fitnes».Python

Программы на Python
Anonymous
AttributeError: объект «ParticleSwarmOptimization» не имеет атрибута «global_best_fitnes».

Сообщение Anonymous »

ошибка в коде выполнения PSO для выбора функции
def fitness(position):
selected_features = np.array(position, dtype=bool)
X_selected = X.iloc[:, selected_features]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

classifier = KNeighborsClassifier()
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
return accuracy

import numpy as np

class ParticleSwarmOptimization:
def __init__(self, n_particles, n_features, n_iterations, fitness_function, w=0.5, c1=1, c2=2):
self.n_particles = n_particles
self.n_features = n_features
self.n_iterations = n_iterations
self.fitness_function = fitness_function
self.w = w
self.c1 = c1
self.c2 = c2

def initialize_particles(self):
return np.random.choice([0, 1], size=(self.n_particles, self.n_features))

def update_velocity(self, velocity, personal_best, global_best, position):
cognitive = self.c1 * np.random.rand() * (personal_best - position)
social = self.c2 * np.random.rand() * (global_best - position)
return self.w * velocity + cognitive + social

def update_position(self, position, velocity):
return np.round(1 / (1 + np.exp(-velocity))).astype(int)

def optimize(self):
self.best_fitness_history = [] # Add this line to store fitness history

# Initialize particles
position = self.initialize_particles()
velocity = np.zeros((self.n_particles, self.n_features))

personal_best = position.copy()
personal_best_fitness = np.array([self.fitness_function(pos) for pos in personal_best])

self.global_best = personal_best[np.argmax(personal_best_fitness)]
self.global_best_fitness = np.max(personal_best_fitness)

for iteration in range(self.n_iterations):
for i in range(self.n_particles):
# Update velocity and position
velocity = self.update_velocity(velocity, personal_best, self.global_best, position)
position = self.update_position(position, velocity)

# Update personal best
current_fitness = self.fitness_function(position)
if current_fitness > personal_best_fitness:
personal_best = position[i].copy()
personal_best_fitness[i] = current_fitness

# Update global best
if current_fitness > self.global_best_fitness:
self.global_best = position[i].copy()
self.global_best_fitness = current_fitness

self.best_fitness_history.append(self.global_best_fitness)

return self.global_best, self.global_best_fitnes


Подробнее здесь: https://stackoverflow.com/questions/784 ... lobal-best

Вернуться в «Python»