在Python中存储自定义梯度下降算法每一步的参数值

Storing parameter values in every step of the custom gradient descent algorithm in Python

我正在尝试制作自定义梯度下降估计器,但是,我遇到了在梯度下降算法的每一步存储参数值的问题。这是代码框架:

from numpy import *
import pandas as pd
from joblib import Parallel, delayed
from multiprocessing import cpu_count

ftemp = zeros((2, )) 
stemp = empty([1, ], dtype='<U10') 
la = 10

vals = pd.DataFrame(index=range(la), columns=['a', 'b', 'string']

def sfun(k1, k2, k3, string):
    a = k1*k2
    b = k2*k3
    s = string

    nums = [a, b]
    strs = [s]

    return(nums, strs)

def store(inp):
    r = rsfun(inp[0], inp[1], inp[2], inp[3])

    ftemp = append(ftemp, asarray(r[0]), axis = 0)
    stemp = append(stemp, asarray(r[1]), axis = 0)
    
    return(ftemp, stemp)

for l in range(la):
    inputs = [(2, 3, 4, 'he'),
              (4, 6, 2, 'je'), 
              (2, 7, 5, 'ke')]

    Parallel(n_jobs = cpu_count)(delayed(store)(i) for i in inputs)

    vals.iloc[l, 0:2] = ftemp[0, 0], ftemp[0, 1]
    vals.iloc[l, 2] = stemp[0]

    d = ftemp[2, 0]-ftemp[0, 0]
    

注意:大部分梯度下降的东西都被删除了,因为我对此没有任何问题。我遇到的主要问题是在每一步存储值。

sfun() 是损失函数(我知道它在这里看起来不像),而 store() 只是尝试存储每一步的参数值。

这里的重要方面是我想并行化进程,因为 sfun() 的计算成本很高,而且我想为所有并行运行保存值。

我尝试了很多不同的方法来解决这个问题,但我总是得到不同的错误。

不需要做临时存储数组,可以直接存储Parallel()函数的结果:

a = Parallel(n_jobs = cpu_count)(delayed(store)(i) for i in inputs)

最重要的是,填充 a 是为了给出输入。