2016-03-10 54 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装饰似乎很强大)的优化,所以它可以为你的统计计算有用。

相关问题