贝叶斯自适应实验设计

badapted的Python项目详细描述


badapted:贝叶斯自适应实验设计

PyPI

status:工作代码,但仍在开发中

运行有效的贝叶斯自适应实验。

此代码与以下预打印相关。但是,最终出版时,预印本可能会以完全不同的形式出现。

Vincent, B. T., & Rainforth, T. (2017, October 20). The DARC Toolbox: automated, flexible, and efficient delayed and risky choice experiments using Bayesian adaptive design. Retrieved from psyarxiv.com/yehjb

badapted

之上构建自己的自适应实验工具箱

下面我们将概述如何使用badapted包来运行自适应实验。这个badapted包本身不会做任何事情。它还需要一些类(可能还有一些助手函数),开发人员必须为其特定的实验范式创建这些类。这形成了一个“工具箱”,允许在特定的实验领域中运行自适应实验。

最好的(第一个)例子是我们的DARC Toolbox,它允许对延迟和危险的选择任务进行适应性实验。

但下面我们将概述如何为您感兴趣的实验领域创建一个新的“工具箱”。

步骤1:定义您的设计空间

首先,我们使用编写的函数创建一个名为designs的pandas数据帧。每一列都是一个设计变量。每一行都是特定的设计。

defbuild_my_design_space(my_arguments):designs=# CREATE PANDAS DATAFRAME OF THE DESIGN SPACE HEREreturndesigns

步骤2:定义自定义设计生成器

为了生成使用贝叶斯自适应设计(在您的实验领域)的自己的设计生成器,您需要创建一个类,该类将badapted.BayesianAdaptiveDesignGenerator作为子类。您还需要实现一些特定于您的实验域的方法,特别是:

  • add_design_response_to_dataframe
  • df_to_design_tuple

目前,我们只提供在darc工具箱中使用的示例。首先,我们的具体设计生成器类定义为:

frombadapted.designsimportBayesianAdaptiveDesignGeneratorclassBayesianAdaptiveDesignGeneratorDARC(DARCDesignGenerator,BayesianAdaptiveDesignGenerator):'''This will be the concrete class for doing Bayesian adaptive design    in the DARC experiment domain.'''def__init__(self,design_space,max_trials=20,allow_repeats=True,penalty_function_option='default',λ=2):# call superclass constructors - note that the order of calling these is importantBayesianAdaptiveDesignGenerator.__init__(self,design_space,max_trials=max_trials,allow_repeats=allow_repeats,penalty_function_option=penalty_function_option,λ=λ)DARCDesignGenerator.__init__(self)

注意,这有多个继承,所以我们还有一个类DARCDesignGenerator,它只包括特定于darc的方法(add_design_response_to_dataframedf_to_design_tuple)。定义如下:

frombadapted.designsimportDesignGeneratorABCfromdarc_toolboximportProspect,DesignclassDARCDesignGenerator(DesignGeneratorABC):'''This adds DARC specific functionality to the design generator'''def__init__(self):# super().__init__()DesignGeneratorABC.__init__(self)# generate empty dataframedata_columns=['RA','DA','PA','RB','DB','PB','R']self.data=pd.DataFrame(columns=data_columns)defadd_design_response_to_dataframe(self,design,response):'''        This method must take in `design` and `reward` from the current trial        and store this as a new row in self.data which is a pandas data frame.        '''trial_data={'RA':design.ProspectA.reward,'DA':design.ProspectA.delay,'PA':design.ProspectA.prob,'RB':design.ProspectB.reward,'DB':design.ProspectB.delay,'PB':design.ProspectB.prob,'R':[int(response)]}self.data=self.data.append(pd.DataFrame(trial_data))# a bit clumsy but...self.data['R']=self.data['R'].astype('int64')self.data=self.data.reset_index(drop=True)return@staticmethoddefdf_to_design_tuple(df):'''User must impliment this method. It takes in a design in the form of a        single row of pandas dataframe, and it must return the chosen design as a        named tuple.        Convert 1-row pandas dataframe into named tuple'''RA=df.RA.values[0]DA=df.DA.values[0]PA=df.PA.values[0]RB=df.RB.values[0]DB=df.DB.values[0]PB=df.PB.values[0]chosen_design=Design(ProspectA=Prospect(reward=RA,delay=DA,prob=PA),ProspectB=Prospect(reward=RB,delay=DB,prob=PB))returnchosen_design

我们之所以进行这种多重继承,是因为我们希望其他(非贝叶斯自适应)设计生成器在darc域中工作,但没有任何贝叶斯自适应设计组件。在大多数情况下,只要关注贝叶斯自适应设计,就可以在一个具体的设计生成器类中定义add_design_response_to_dataframedf_to_design_tuple类。

步骤3:定义模型

必须提供从Model继承的模型类。您还必须提供以下方法:

  • __init__
  • predictive_y

下面是用户定义模型的最小实现示例:

frombadapted.modelimportModelfrombadapted.choice_functionsimportCumulativeNormalChoiceFunc,StandardCumulativeNormalChoiceFuncfromscipy.statsimportnorm,halfnorm,uniformimportnumpyasnpclassMyCustomModel(Model):'''My custom model which does XYZ.'''def__init__(self,n_particles,prior={'logk':norm(loc=-4.5,scale=1),'α':halfnorm(loc=0,scale=2)}):'''        INPUTS        - n_particles (integer).        - prior (dictionary). The keys provide the parameter name. The values        must be scipy.stats objects which define the prior distribution for        this parameter.        We provide choice functions in `badapted.choice_functions.py`. In this        example, we define it in the __init__ but it is not necessary to happen        here.        '''self.n_particles=int(n_particles)self.prior=priorself.θ_fixed={'ϵ':0.01}self.choiceFunction=CumulativeNormalChoiceFuncdefpredictive_y(self,θ,data):'''        INPUTS:        - θ = parameters        - data =        OUTPUT:        - p_chose_B (float) Must return a value between 0-1.        '''# Step 1 - calculate decision variablek=np.exp(θ['logk'].valuesVA=data['RA'].values*1/(1+k*data['DA'].values)VB=data['RB'].values*1/(1+k*data['DB'].values)decision_variable=VB-VA# Step 2 - apply choice functionp_chose_B=self.choiceFunction(decision_variable,θ,self.θ_fixed)returnp_chose_B

第四步:建立一个实验循环

这是非常直接的,这里不需要任何主要的定制。

defrun_experiment(design_generator,model,max_trials):'''Run an adaptive experiment    INPUTS:    - design_generator: a class    '''fortrialinrange(max_trials):design=design_generator.get_next_design(model)ifdesignisNone:breakresponse=get_response(design)design_generator.enter_trial_design_and_response(design,response)model.update_beliefs(design_generator.data)returnmodel

注意,response = get_response(design)行由您来实现。你在这里做什么取决于你是在模拟反应还是从精神病患者那里得到真实的反应等等。这个run_experiment函数只是一个例子,说明了代码的各个部分是如何协同工作的。在使用psychopy运行actual实验时,最好参考我们在DARC Toolbox中提供的演示psychopy文件作为示例,以了解这是如何实现的。

步骤5:设置并运行实验

designs=build_my_design_space(my_arguments)design_generator=MyCustomDesignGenerator(designs,max_trials=max_trials)model=MyCustomModel()model=run_experiment(design_generator,model,max_trials)

请注意,run_experiment函数的使用只是对事物如何组合的逻辑的演示。如前所述,请参阅DARC Toolbox中的心理变态示例实验,以了解这一切在心理变态实验中是如何结合在一起的。

使用badapted

的工具箱

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
算法图形。路径方向Java枚举方向问题无法使用EAST   Java:将字符串转换为特定语言环境   javaspringboot&Thymeleaf为后续调用保存搜索表单的最佳方法   mapreduce程序中未调用java reducer   java如何将url中的Gif文件保存到手机中?   如何在JavaSwing中使用[Esc]键最小化JInternalFrame?   java创建了一个包含100个按钮、80个空按钮和20个随机按钮的网格布局   如何在java中使用数组对2d字符串数组中的每一行进行排序。分类   java无法识别的SSL消息,纯文本连接?例外   为什么Java编译器允许在抛出部分列出方法无法抛出的异常   java将预测数组添加到训练数组   java从Ajax调用获取响应文本   使用改型2的java应用程序等待一分钟后退出