gpt4 book ai didi

python - 使用 numpy 生成带有 case-when 条件的随机数据

转载 作者:行者123 更新时间:2023-12-04 10:46:38 25 4
gpt4 key购买 nike



我想生成要建模的数据。基于以下逻辑:

输入 : 2 个名为 z 的 numpy 数组和 d .
z : 一维数组,值 0/1
d : 一维数组,值 0/1

返回:y : 一维数组。值:范数随机数。

如果 z == 0 且 d==0, y ~ norm(1,1),

如果 z == 0 且 d == 1, y~ norm(0,1),

如果 z == 1 且 d == 0, y ~ norm(1,1),

如果 z == 1 且 d == 1,则 y ~ norm(2,1)。

我想以一种超快速、清晰和 Pythonic 的方式来做。

似乎是基础数学和np.where是比较快的。在这种情况下,我只有 3 个条件(从基础数学部分可以清楚地看到)。如果我有 10 个或更多条件,请在 if-else 中输入它们声明有时令人困惑。我要进行数据模拟,也就是说我会在不同的n生成百万次数据.那么,最好的方法是什么?

我尝试过的:

# generate data
n = 2000
z = np.random.binomial(1,0.5,n)
d = np.random.binomial(1,0.5,n)

dict case-when
def myfun(x):
return {(0,1):np.random.normal(0,1),\
(0,0):np.random.normal(1,1),\
(1,0):np.random.normal(1,1),\
(1,1):np.random.normal(2,1)}[x]
%%timeit
y = [myfun(i) for i in zip(z,d)]

出去:

16.2 ms ± 139 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)



简单 if-else
%%timeit
y = np.random.normal([0 if (i == 0) & (j ==1) else 2 if (i == 1) & (j == 1) else 1 for i,j in zip(z,d)],1)

出去:

1.38 ms ± 22.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)



基础数学
%%timeit
h0 = np.random.normal(0,1,n)
h1 = np.random.normal(1,1,n)
h2 = np.random.normal(2,1,n)
y = (1-z)*d*h0 + (1-d)*h1 + z*d*h2

出去:

140 µs ± 135 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)



np.where
%%timeit
h0 = np.random.normal(0,1,n)
h1 = np.random.normal(1,1,n)
h2 = np.random.normal(2,1,n)
y = np.where((d== 0),h1,0) + np.where((z ==1) & (d== 1),h2,0) + np.where((z ==0) & (d== 1),h0,0)

出去:

156 µs ± 598 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)



有没有其他新方法?

最佳答案

看来您已经在这里完成了跑腿工作。结果现在基于权衡。以上所有解决方案都在不同程度上满足标准。

这段代码是用来教别人的吗?也许它每天只执行一次或两次?它是更大项目的一部分,需要非常清楚以便其他人维护?如果是这种情况,请选择较慢但更易于理解和阅读的选项。

它每天执行数千次还是数百万次?资源成本降低了产品的利润?如果是这样,请对其进行很好的评论并使用更快的选项。

看来basic mathematics选项是最好的权衡,因为它简单、易于理解但执行起来很快。

我对每种方法的偏见评论:

  • dict case-when :慢,需要多次阅读/测试才能完全了解实际发生的情况并确定是否有任何未知的问题。
  • simple if-else :慢,需要多次阅读/测试才能完全了解实际发生的情况并确定是否有任何未知的问题。
  • basic mathematics : 快速、易于理解,即使您有轻微的数学背景(应该包括大多数程序员)。
  • np.where :快速,完成工作,需要多次读数/测试才能完全了解实际发生的情况,但由于它基于数组,因此不太容易出现问题。

  • 以下是编写代码的 Pythonic 哲学,供引用:
  • 美丽总比丑陋好。
  • 显式优于隐式。
  • 简单胜于复杂。
  • 复杂总比复杂好。
  • 扁平比嵌套好。
  • 稀疏比密集好。
  • 可读性很重要。

  • 使用上述作为标准更容易评估您的代码是否是 pythonic 。

    关于python - 使用 numpy 生成带有 case-when 条件的随机数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59676147/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com