对python函数具有相同args的多个调用输出不同的返回值

就我而言,这一定是一个非常基本的误解。我有一个函数,可以根据随机值返回插值函数。

fct = create_interp_fct(x,y)

现在 fct 是可调用的插值函数。例如:

fct([0,0])

返回

array([[ 0.75894378,0.72761319,-0.23003647,-0.34790905,-0.51531125,-0.91211147]])

该函数的定义大致如下:

def create_interp_fct(x,y):
    u,v = compute_some_random_values(x,y)
    return RegularGridInterpolator(u,v) #from from scipy.interpolate

问题是,如果我再次调用 fct([0,0]),则会得到不同的输出。因此很明显,该函数是根据新的随机值重新定义的。 我的问题是:如何使用 fct 以便每次调用它时都不会重新定义它?想象一下 fct 的计算是非常昂贵的,但实际上却没有。如何“保存”当前计算的函数?或查看scikit中的所有机器学习资料(例如线性回归等)。如果我打电话

 lr = lm.LinearRegression() # import sklearn.linear_model as lm
 lr.fit(M,n)

您不能说我每次调用lr.score(M,n)都会重新计算线性回归吗?

yhl19870621 回答:对python函数具有相同args的多个调用输出不同的返回值

在以下示例中,未复制来自fct给定的实例的不确定输出问题:

In [13]: paste                                                                                                                                                                      

import numpy
from scipy.interpolate import RegularGridInterpolator                                                                                                                      

def compute_some_random_values(shape):
    return [numpy.arange(extent) for extent in shape],numpy.random.uniform(0,1,size=shape)

def create_interp_fct(shape):
    u,v = compute_some_random_values(shape)
    return RegularGridInterpolator(u,v) #from from scipy.interpolate

## -- End pasted text --


In [24]: fct = create_interp_fct([2,3,4,5,6,7])                                                                                                                                     

In [25]: fct([0,0])                                                                                                                                                         
Out[25]: array([0.24572906])

In [26]: fct([0,0])                                                                                                                                                         
Out[26]: array([0.24572906])

In [27]: fct([0,0])                                                                                                                                                         
Out[27]: array([0.24572906])

In [28]: fct([0,0])                                                                                                                                                         
Out[28]: array([0.24572906])

我怀疑您在程序逻辑中的某个地方,在两次调用之间刷新了fct,是通过再次调用fct = create_interp_fct(...)却没有意识到这一点。这自然会重新安排事情。

本文链接:https://www.f2er.com/3124554.html

大家都在问