【发布时间】:2019-12-23 18:03:40
【问题描述】:
我正在使用 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 个项目的“数组”,引用基本数组中的一个函数。
这个帖子的原因是,我打印了funcs的结果并收到了:
[<function f at 0x00000225AC94F0D0> <function f at 0x00000225AC94F0D0>]
显然,这以某种形式返回对函数的引用,而不是我理解该形式是什么或如何操作它,这就是问题所在。我想更改函数的选择,以便不再是随机的,而是取决于某些条件,所以它可能是:
for i in range(2):
if testvar=='true':
choice[i] = 0
if testvar== 'false':
choice[i] = 1
这将返回一个索引数组以放入以后的函数中
问题是,代码的进一步操作(我认为)需要以前形式的函数引用:[ ] 作为输入,而不是简单的 0,1 索引数组,我不知道该怎么做使用 if 语句获取表单 [ ] 的数组。
对于需要此输入的其余代码,我可能完全错了,但我不知道如何修改它,因此将其发布在这里。完整代码如下:(它是@Attack68 在Evolving functions in python 上提供的代码的轻微变体)它旨在存储一个函数,该函数在每次迭代时乘以随机函数并相应地积分。 (我已经对导致问题的函数上方的代码进行了注释)
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
【问题讨论】:
-
我不清楚
testvar和choice是否适合您的总体目标。 -
base是一个列表,而不是一个数组。为什么你决定使用 numpy.random 而不是 Python random 模块? -
不清楚你在问什么,或者你期望发生什么与它实际在做什么。
apply有什么不足? -
我仍然不清楚
testvar是如何适应的。它的值需要以某种方式改变以使 if 语句具有相关性。但是您似乎正在尝试将func定义为基于choice的函数列表,对吗?func = [base[n] for n in choice]之类的东西? -
您正在尝试将在随机选择的函数列表上运行的原始代码重构为使用与函数列表中的项目相对应的随机索引运行的版本?
标签: python function numpy random choice