如何通过生成计数器来绘制函数内部

问题描述

在下面的代码中,我想查看每次调用函数error的变化。但是,该图是点的垂直列。如何在函数生成一个计数器以提供x轴值?

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize

t = np.random.uniform(0.,100.,100)
y = t**3 - 130*t**2 + 5000*t - 56000 + np.random.normal(0.,10000.,100)

def fn(x):
    a,b,c,d = x;
    fit = a * t **3 + b * t **2 + c * t + d
    error = sum((fit - y)**2)
    plt.plot(error,".")
    fn.x = x
    return error

init_x = [2,-100,1000,-10000]
res = minimize(fn,init_x,method='Nelder-Mead',tol=1e-6)
fn(res.x)

解决方法

一种选择是使用global变量作为计数器,并在每次调用fn函数时增加其值。然后,您可以在使用plt.plot时将其用作x坐标。例如:

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize

t = np.random.uniform(0.,100.,100)
y = t**3 - 130*t**2 + 5000*t - 56000 + np.random.normal(0.,10000.,100)

xx = 0

def fn(x):
    global xx
    xx += 1
    a,b,c,d = x;
    fit = a * t **3 + b * t **2 + c * t + d
    error = sum((fit - y)**2)
    plt.plot(xx,error,".")
    fn.x = x
    return error

init_x = [2,-100,1000,-10000]
res = minimize(fn,init_x,method='Nelder-Mead',tol=1e-6)
fn(res.x)

plt.gca().set_yscale('log')
plt.show()

enter image description here