【问题标题】:Function with two different length variables具有两个不同长度变量的函数
【发布时间】:2016-06-24 15:36:56
【问题描述】:

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

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 中的 50 个数字中的每一个。如果我要这样做一次,它看起来像:

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

我可以让它与“for”循环一起工作,但我最终需要将它输入到一个最大似然函数中,因此使用它是行不通的。有什么想法吗?

【问题讨论】:

  • 尝试map对每个x执行最后一次操作

标签: python function numpy pandas iteration


【解决方案1】:

在 2D 和 1D 中“矢量化”函数的关键部分是 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]]

【讨论】:

    【解决方案2】:

    您可能对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 装饰器似乎非常强大)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多