繁体   English   中英

Python- np.random.choice

[英]Python- np.random.choice

我正在使用 numpy.random.choice 模块根据函数数组生成一个“数组”选择:

def f(x):
    return np.sin(x)

def g(x):
    return np.cos(x)


base=[f, g]

funcs=np.random.choice(base,size=2)

此代码将生成一个包含 2 个项目的“数组”,引用基本数组中的 function。

这篇文章的原因是,我已经打印了 funcs 的结果并收到:

[<function f at 0x00000225AC94F0D0> <function f at 0x00000225AC94F0D0>]

显然,这会以某种形式返回对函数的引用,并不是我了解该形式是什么或如何操作它,这就是问题所在。我想更改 function 的选择,使其不再随机而取决于某些条件,因此它可能是:

for i in range(2):
    if testvar=='true':
        choice[i] = 0 
    if testvar== 'false':
        choice[i] = 1

这将返回一组索引,稍后放入 function

问题是,代码的进一步操作(我认为)需要以前形式的 function 参考:[] 作为输入,而不是简单的 0,1 Indicies 数组,我不知道如何获得数组形式 [ ] 通过使用 if 语句。

关于需要此输入的代码的 rest,我可能完全错了,但我不知道如何修改它,因此我将它发布在这里。 完整代码如下:(它是@Attack68 在 python 中Evolving 函数中提供的代码的细微变化)它旨在存储一个 function,它在每次迭代中乘以一个随机的 function,并相应地进行积分。 (我已经对导致问题的 function 上面的代码发表了评论)

import numpy as np
import scipy.integrate as int

def f(x):
    return np.sin(x)

def g(x):
    return np.cos(x)

base = [f, g]

funcs = np.random.choice(base, size=2)
print(funcs)
#The below function is where I believe the [<function...>] input to be required
def apply(x, funcs):
    y = 1
    for func in funcs:
        y *= func(x)
    return y

print('function value at 1.5 ', apply(1.5, funcs))

answer = int.quad(apply, 1, 2, args=(funcs,))
print('integration over [1,2]: ', answer)

这是我实现非随机事件的尝试:

import numpy as np
import scipy.integrate as int
import random
def f(x):
    return np.sin(x)

def g(x):
    return np.cos(x)

base = [f, g]

funcs = list()
for i in range(2):
    testvar=random.randint(0,100) #In my actual code, this would not be random but dependent on some other situation I have not accounted for here
    if testvar>50:
        func_idx = 0 # choose a np.random operation: 0=f, 1=g
    else:
        func_idx= 1
    funcs.append(func_idx)
#funcs = np.random.choice(base, size=10)
print(funcs)
def apply(x, funcs):
    y = 1
    for func in funcs:
        y *= func(x)
    return y

print('function value at 1.5 ', apply(1.5, funcs))

answer = int.quad(apply, 1, 2, args=(funcs,))
print('integration over [1,2]: ', answer)

这将返回以下错误:

TypeError: 'int' object is not callable

如果您仍想按原样使用您的 function apply程序,则需要将您的输入保留为功能列表。 您可以使用这些索引来创建您的函数列表,而不是提供索引列表。

而不是apply(1.5, funcs) ,尝试:

apply(1.5, [base(n) for n in funcs])

如果:您正在尝试将对随机选择的函数列表进行操作的原始代码重构为使用与函数列表中的项目相对应的随机索引进行操作的版本。 重构apply

def apply(x,indices,base=base):
    y = 1
    for i in indices:
        f = base[i]
        y *= f(x)
    return y

...这会以某种形式返回对函数的引用,而不是我了解该形式是什么或如何操作它...

函数是对象,列表包含对对象本身的引用。 可以通过将它们分配给一个名称然后调用它们或索引列表并调用 object 来使用它们:

>>> def f():
...     return 'f'

>>> def g():
...     return 'g'

>>> a = [f,g]
>>> q = a[0]
>>> q()
'f'
>>> a[1]()
'g'
>>> for thing in a:
    print(thing())

f
g

或者你可以传递它们:

>>> def h(thing):
...     return thing()

>>> h(a[1])
'g'
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM