You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib FuncAnimation仅显示单帧的问题求助及遗传算法代码审核

Matplotlib FuncAnimation仅显示单帧的问题求助及遗传算法代码审核

我正在尝试用Python实现遗传算法,并且想用matplotlib.animation中的FuncAnimation制作动画来展示算法的运行结果,但遇到了一个棘手的问题——最终只显示了单帧画面。更奇怪的是,在Google Colab里显示的是某一帧,而我日常使用的PyCharm IDE里显示的却是另一帧。

以下是我的完整代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def fitness_function(x, y):
    return x ** 2 + y ** 2

def initialize_population(pop_size, bounds):
    return np.random.uniform(bounds[0], bounds[1], (pop_size, 2))

def select(population, fitnesses):
    indices = np.argsort(fitnesses)[:len(population) // 2]
    return population[indices]

def crossover(parents, offspring_size):
    offsprings = []
    for _ in range(offspring_size):
        p1, p2 = parents[np.random.choice(len(parents), size=2, replace=False)]
        alpha = np.random.rand()
        child = alpha * p1 + (1 - alpha) * p2
        offsprings.append(child)
    return np.array(offsprings)

def mutate(population, bounds, mutation_rate=0.1):
    for i in range(len(population)):
        if np.random.rand() < mutation_rate:
            population[i] += np.random.uniform(-1, 1, size=2)
            population[i] = np.clip(population[i], bounds[0], bounds[1])
    return population

def genetic_algorithm(pop_size=500, generations=500, bounds=(-10, 10)):
    population = initialize_population(pop_size, bounds)
    history = []

    for gen in range(generations):
        fitnesses = np.array([fitness_function(x, y) for x, y in population])
        parents = select(population, fitnesses)
        offspring_size = pop_size - len(parents)
        offspring = crossover(parents, offspring_size)
        population = np.vstack((parents, offspring))
        population = mutate(population, bounds)
        history.append(population.copy())

        if gen % 50 == 0:
            print(f"Generation {gen}: Best fitness = {fitnesses.min():.4f}")

    return history

history = genetic_algorithm()

fig, ax = plt.subplots(figsize=(8, 8))
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
ax.set_title("Evolution of Genetic Algorithm Population")
ax.set_xlabel("X")
ax.set_ylabel("Y")

colors = np.linspace(0, 1, len(history))

scat = ax.scatter([], [], c=[], cmap='viridis', s=50, vmin=0, vmax=1)

ax.plot([0, 0], [-10, 10], color='blue', linewidth=1)
ax.plot([-10, 10], [0, 0], color='blue', linewidth=1)

def update(frame):
    print(f"Frame: {frame}, History Length: {len(history)}")
    data = history[frame]
    scat.set_offsets(data)
    scat.set_array(np.full(len(data), colors[frame]))
    ax.set_title(f"Generation {frame+1}/{len(history)}")
    return scat,

anim = FuncAnimation(fig, update, frames=len(history), interval=50, repeat=False)
plt.show()
print(plt.get_backend())

print(f"Number of generations: {len(history)}")

我已经查阅了很多类似问题,但现有的答案都没能解决我的问题。比如我试过一个被标记为解决方案的示例代码,运行后依然只显示单帧。如果是我遗漏了相关问题的话,先在这里说声抱歉。

另外,如果各位能发现我这个遗传算法实现中的错误,也麻烦帮忙指出来,我会非常感激!

我的运行环境如下:

  • Python 3.9.13
  • matplotlib 3.9.3
  • numpy 2.0.2

备注:内容来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:24:36