如何为matplotlib函数优化设置动画? [英] how to animate matplotlib function optimization?

查看:100
本文介绍了如何为matplotlib函数优化设置动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作类似于Matlab函数优化动画的内容. Matlab中有一个程序包,可用于优化功能的动画处理.

I am trying to make something similar to Matlab function optimization animation. There is a package in Matlab which allows animation of optimization functions.

我不想调用anim.FuncAnimation,因为我的优化函数将通过scipy.minimize

I don't want to call anim.FuncAnimation because my optimization function will be called automatically via scipy.minimize

scipy.minimize的参数中,优化功能应执行例如动画...

In the argument to scipy.minimize the optimization function should do the animation for instance...

lines.set_data(x,y)

这里x和y来自优化函数.显然这是行不通的.

Here x and y will be from the optimization function. Obviously this doesn't work.

推荐答案

实际上,您不预先知道在最小化目标函数之前将要存在多少个函数调用,因此,这样做可能更有意义检索所有优化向量,然后将它们绘制出来.

In fact you don't know in advance how many function call it is going to be there before the target function is minimized, therefore it may make more sense to retrieve all the optimize vectors and plot them afterwards.

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)

这篇关于如何为matplotlib函数优化设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆