如何动画化matplotlib函数优化?

1 投票
1 回答
1324 浏览
提问于 2025-04-18 18:01

我想做一个类似于Matlab中函数优化动画的东西。Matlab里有一个包可以让优化函数进行动画展示。

我不想使用anim.FuncAnimation,因为我的优化函数会通过scipy.minimize自动调用。

scipy.minimize的参数中,优化函数应该能够进行动画展示,比如说...

lines.set_data(x,y)

这里的x和y将来自优化函数。显然,这样是行不通的。

1 个回答

2

实际上,你事先并不知道在目标函数被最小化之前会有多少次函数调用。因此,先获取所有的优化向量,然后再进行绘图可能更有意义。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import scipy.optimize as si
import scipy.optimize as so

fig = plt.figure()
ax = plt.axes(xlim=(-0.5, 3.5), ylim=(-10, 100))
line, = ax.plot([], [], 'o')

def F(x):
        return (x**3-x**2-9.)**2

#get the optimize progress
res_x = []
so.fmin(F, -9, callback=res_x.append)
res_x = np.array(res_x).ravel()
res_y = F(res_x)

def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    line.set_data(res_x[i], res_y[i])
    return line,

ax.plot(np.linspace(0,10,100), F(np.linspace(0,10,100)), 'g')
#frames is the length of res_x
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=len(res_x), interval=200, blit=True)

enter image description here

撰写回答