2

1. 背景

我绘制了一个具有最小值的二次函数曲线(ax^2+bx+c,a>0),并使用可迭代的方法来搜索该值。每一步之后,都会产生一个点。我想要做的是动态地绘制这一点。

2.伪代码

f(x)=ax^2+bx+c, a>0
g(t) is the mentioned method which is used to search the minimum value

plot f(x)
plot initial point (x0,y0)

for t in range(10000):
  new_x,new_y = g(t)

  move (x0,y0) to new position (new_x,new_y)

3.解决方案

3.1 互动情节

3.1.1 示例
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

matplotlib.use("TkAgg")

plt.figure()
plt.grid(True)
plt.ion()

ft = np.linspace(0, 100, 1000)
plt.plot(ft, ft ** 2 + 1, c='r')
for t in range(100):
    plt.scatter(t, t ** 2 + 1, marker='.', c='b')

    plt.pause(1e-6)

plt.ioff()
plt.show()
3.1.2 注意事项
  1. 它有效,但运行缓慢。
  2. 该方法生成一个轨道,这是冗余的。

3.2 动画

3.2.1 示例

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

matplotlib.use("TkAgg")
def update_points(num):

    point_ani.set_data(x[num], y[num])
    return point_ani,


x = np.linspace(0, 100, 1000)
y = x**2+1

fig = plt.figure(tight_layout=True)
plt.plot(x, y)
point_ani, = plt.plot(x[0], y[0], "ro")
plt.grid(ls="--")
ani = animation.FuncAnimation(fig,
                              update_points,
                              interval=1,
                              blit=True)
plt.show()

print('finish')

3.2.2 注意事项

这种方法可以在没有任何轨迹的情况下工作,但是在绘制之前必须知道点的整个移动路径。

所以,假设有一个艺术家,它每次收到一个新点就画;如果没有收到点,它会等待。如何实施?

4

1 回答 1

0

使用此 Wikipedia链接中描述的梯度下降方法,这里是 Python 实现,以及指示每一步新“最小值”的动画。

import numpy as np
import matplotlib.pyplot as plt
###initializing the parameters##################
next_x = -5  # We start the search at x=-5
gamma = 0.01  # Step size multiplier
precision = 0.000001  # Desired precision of result
max_iters = 10000  # Maximum number of iterations
########setup the plot################
fig, ax = plt.subplots()
ax.set_ylabel('y')
ax.set_xlabel('x')
ft = np.linspace(-50, 50, 1000)
line, = ax.plot(ft, ft**2 + 1,c='r',linestyle='-')
ax.set_title('Gradient descent showing the minima at each step')
plt.ion()   # set interactive mode
plt.show()
#################################
a=1
b=0
c=1
# Derivative function
def df(a,b,c,x):
    return 2*a*x + b
# function
def f(a,b,c,x):
    return a*x**2+b*x+c
for _ in range(max_iters):
    current_x = next_x
    next_x = next_x - gamma * df(a,b,c,current_x)
    step = next_x - current_x
    #do the plotting after setting up canvas
    plt.gcf().canvas.draw()
    #show the new minima as a '.'
    line, = ax.plot(next_x,f(a,b,c,next_x),'.',c='black')
    plt.pause(0.1)
    #remove the track
    line.remove()
    del line
    if abs(step) <= precision:
        break
print ("Minima at :{}".format(next_x))

动画

于 2020-05-27T16:09:43.523 回答