簡體   English   中英

在2-D陣列上使用插值函數

[英]Using interpolate function over 2-D array

我有一個1-D函數需要花費很多時間來計算大的2-D'x'值數組,因此使用SciPy工具創建插值函數然后使用它來計算y很容易,這將是快多了。 但是,我不能在具有1-D以上的數組上使用插值函數。

例:

# First, I create the interpolation function in the domain I want to work
x = np.arange(1, 100, 0.1)
f = exp(x) # a complicated function
f_int = sp.interpolate.InterpolatedUnivariateSpline(x, f, k=2)

# Now, in the code I do that
x = [[13, ..., 1], [99, ..., 45], [33, ..., 98] ..., [15, ..., 65]]
y = f_int(x)
# Which I want that it returns y = [[f_int(13), ..., f_int(1)], ..., [f_int(15), ..., f_int(65)]]

但回報:

ValueError: object too deep for desired array

我知道我可以遍歷所有x成員,但我不知道這是否是更好的選擇...

謝謝!

編輯:

像這樣的功能也可以完成這項工作:

def vector_op(function, values):

    orig_shape = values.shape
    values = np.reshape(values, values.size)

    return np.reshape(function(values), orig_shape)

我試過np.vectorize但它太慢了......

如果f_int單維數據,則應平整輸入,將其輸入到插值器,然后重建原始形狀:

>>> x = np.arange(1, 100, 0.1)
>>> f = 2 * x # a simple function to see the results are good
>>> f_int = scipy.interpolate.InterpolatedUnivariateSpline(x, f, k=2)

>>> x = np.arange(25).reshape(5, 5) + 1
>>> x
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])
>>> x_int = f_int(x.reshape(-1)).reshape(x.shape)
>>> x_int
array([[  2.,   4.,   6.,   8.,  10.],
       [ 12.,  14.,  16.,  18.,  20.],
       [ 22.,  24.,  26.,  28.,  30.],
       [ 32.,  34.,  36.,  38.,  40.],
       [ 42.,  44.,  46.,  48.,  50.]])

x.reshape(-1)執行展平,而.reshape(x.shape)將其返回到其原始形式。

我想你想在numpy中做一個矢量化函數:

#create some random test data
test = numpy.random.random((100,100))

#a normal python function that you want to apply
def myFunc(i):
    return np.exp(i)

#now vectorize the function so that it will work on numpy arrays
myVecFunc = np.vectorize(myFunc)

result = myVecFunc(test)

我會使用list comprehensionmap的組合(可能有一種方法可以使用我缺少的兩個嵌套maps

In [24]: x
Out[24]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

In [25]: [map(lambda a: a*0.1, x_val) for x_val in x]
Out[25]: 
[[0.1, 0.2, 0.30000000000000004],
 [0.1, 0.2, 0.30000000000000004],
 [0.1, 0.2, 0.30000000000000004]]

這僅用於說明目的....用你的函數f_int替換lambda a: a*0.1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM