程序无法运行,求更正
python用matplotlib绘制动画时无法运行
通过梯度下降求抛物线极值并绘制过程图
试图让每一次迭代的点依次出现并保留在图上,每一帧的点显示数据,到下一帧图上点保留、数据消失
from gettext import lngettext
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as pan
#输入函数的参数
a = input('请输入二次函数的 A, B, C ( A不为0 且 A、B、C 不大于 |10|)\n').split(' ')
A = int(a[0]) ; B = int(a[1]) ; C = int(a[2])
#函数f(x)
def f(x):
return A*x**2 + B*x + C
#x方向上的梯度
def dx(x):
return 2*A*x + B
#输入初始值
x = x0 = float(input('请输入初始值:\n'))
t = 0 #初始化迭代次数
#构建画布、轴、点
fig = plt.figure()
ax = fig.add_subplot(111)
line = plt.plot(x,f(x)) #抛物线
#line = ax.plot(color = 'blue')
point, = ax.plot([], [], 'o', color = 'red')
#学习率
delta = 0.1
#迭代次数
i = 30
#保存梯度下降所经过的点
bx = [x0]
by = [f(x0)]
#迭代
def step():
while( t<= i):
global x
xchange = x - delta * dx(x)
ychange = f( xchange )
#对x进行重新赋值
x = xchange
#储存值
bx.append(xchange)
by.append(ychange)
return bx
#绘制动画
def init():
ax.set_xlim(-10,10)
return line
def every(frame):
# 清空文字
ax.texts.clear()
#标点
ax.text(frame, f(frame), '({:.2f}, {:.2f})\n gra={:.2f}').format(frame,f(frame),delta * dx(frame))
point.set_data(frame,f(frame))
return point, line
bx = step()
#画图
if A!=0: anime = pan.FuncAnimation(fig, every, innit_fucn=init,frame = bx, interval = 60)
#输出
print(u'最终结果为:(x,y)=(%.2f,%.2f)' % (x,f(x)))
ax.set_title('梯度下降法求极值')
plt.show()