2016-03-10 50 views
0

我試圖創建一個函數,但它涉及兩個不同長度的變量。我的設置如下:具有兩個不同長度變量的函數

import pandas as pd 
import numpy as np 

u = np.random.normal(0,1,50) 
t = 25 
x = t*u/(1-u) 
x = np.sort(x, axis=0) 

theta = list(range(1, 1001, 1) 
theta = np.divide(theta, 10) # theta is now 1000 numbers, going from 0.1 to 100 

fx = np.zeros(1000)*np.nan 
fx = np.reshape(fx, (1000,1)) 

我希望我的功能如下所示:

def function(theta): 
    fx = 50/theta - 2 * np.sum(1/(theta + x)) 
    return fx 

,但它不會工作,因爲THETA是長度1000和X的長度爲50。我希望它爲每個THETA反覆工作,並在結尾部分:

np.sum(1/(theta + x) 

我希望它將單個theta添加到x中的五十個數字中的每一個。如果我這樣做一次,它看起來像:

fx[0] = 50/theta[0] - 2 * np.sum(1/(theta[0] + x)) 

我能得到這個與工作「for」循環,但我最終需要輸入此爲最大似然函數,以便使用韓元」工作。有什麼想法嗎?

+0

嘗試地圖上每x執行最後一次操作 – sabbahillel

回答

0

在一維中「向量化」函數的關鍵部分不止是2D,而且2D是meshgrid。請參閱下面的內容並打印xv,yv以瞭解它的工作原理。

import numpy as np 

u = np.random.normal(0,1,50) 
t = 25 
x = t*u/(1-u) 

x = np.sort(x, axis=0) 

theta = np.array(range(1, 1001, 1)) 
theta = theta/10.0 # theta is now 1000 numbers, going from 0.1 to 100 

def function(x,theta): 
    fx = 50/theta - 2 * np.sum(1/(theta + x)) 
    return fx 

xv, tv = np.meshgrid(x,theta) 
print function(xv,tv) 

輸出:

[[-6582.19087928 -6582.19087928 -6582.19087928 ..., -6582.19087928 
    -6582.19087928 -6582.19087928] 
[-6832.19087928 -6832.19087928 -6832.19087928 ..., -6832.19087928 
    -6832.19087928 -6832.19087928] 
[-6915.52421261 -6915.52421261 -6915.52421261 ..., -6915.52421261 
    -6915.52421261 -6915.52421261] 
..., 
[-7081.68987727 -7081.68987727 -7081.68987727 ..., -7081.68987727 
    -7081.68987727 -7081.68987727] 
[-7081.69037878 -7081.69037878 -7081.69037878 ..., -7081.69037878 
    -7081.69037878 -7081.69037878] 
[-7081.69087928 -7081.69087928 -7081.69087928 ..., -7081.69087928 
    -7081.69087928 -7081.69087928]] 
0

您可能感興趣的Numba

@vectorize裝飾允許你定義一個標量函數,並用它在陣列上。

from numba import vectorize 
import pandas as pd 
import numpy as np 

u = np.random.normal(0,1,50) 
t = 25 
x = t*u/(1-u) 
x = np.sort(x, axis=0) 

theta = list(range(1, 1001, 1)) 
theta = np.divide(theta, 10) # theta is now 1000 numbers, going from 0.1 to 100 

@vectorize 
def myFunction(theta): 
    fx = 50/theta - 2 * np.sum(1/(theta + x)) 
    return fx 

myFunction(theta) 

如果您要信任該功能,則可以運行以下代碼。

theta = 1 
print(50/theta - 2 * np.sum(1/(theta + x))) 
theta = 2 
print(50/theta - 2 * np.sum(1/(theta + x))) 
print(myFunction(np.array([1,2]))) 

輸出:

21.1464816231 
32.8089699838 
[ 21.14648162 32.80896998] 

順便說一句,我認爲這是非常(@jit裝飾似乎很強大)的優化,所以它可以爲你的統計計算有用。

相關問題