2013-03-01 67 views
1

我有一個一維函數需要花費很多時間來計算一個大的「x」值的二維數組,因此使用SciPy創建一個插值函數非常容易然後使用它來計算y,這會快得多。但是,我不能在具有多於一維的數組上使用插值函數。在二維數組上使用插值函數

例子:

# 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是太慢了......

回答

2

如果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)將其返回到其原始形式。

+0

那可能會給邊緣帶來怪異 – reptilicus 2013-03-01 17:31:02

+0

@reptilicus爲什麼?我似乎不明白你的意思,對不起... – Jaime 2013-03-01 17:34:27

+0

我在想,插值會導致原始數組邊緣的值不同,一旦數組變平,然後插值然後重新變形。基本上,原始數組的左邊將插入下一行的右邊緣,這可能會或可能不會導致問題。 – reptilicus 2013-03-01 17:45:08

0

我會用一個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]] 

這僅僅是用於說明目的....更換lambda a: a*0.1與功能,f_int

1

我想你想要做一個量化的功能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)