具有两个不同长度变量的函数

时间:2016-03-10 00:43:13

标签: python function numpy pandas iteration

我正在尝试创建一个函数,但它涉及两个不同长度的变量。我的设置如下:

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”循环来实现这一点,但我最终需要将其输入到最大似然函数中,因此使用它将无效。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

“向量化”的关键部分'你的功能不只是1D,而是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]]

答案 1 :(得分: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装饰器似乎非常强大)。

相关问题