当前位置: 首页>>代码示例>>Python>>正文


Python pystan.StanModel方法代码示例

本文整理汇总了Python中pystan.StanModel方法的典型用法代码示例。如果您正苦于以下问题:Python pystan.StanModel方法的具体用法?Python pystan.StanModel怎么用?Python pystan.StanModel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pystan的用法示例。


在下文中一共展示了pystan.StanModel方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: stan_cache

# 需要导入模块: import pystan [as 别名]
# 或者: from pystan import StanModel [as 别名]
def stan_cache(model_name, optimization=False, **kwargs):
  f=open(model_name, 'rb')
  model_code=f.read()
  f.close()
  code_hash = md5(model_code.encode('ascii')).hexdigest()
  cache_fn = 'cached-{}-{}.pkl'.format(model_name, code_hash)
  try:
    sm = pickle.load(open(cache_fn, 'rb'))
  except:
    sm = pystan.StanModel(file=model_name)
    with open(cache_fn, 'wb') as f:
      pickle.dump(sm, f)
  else:
    logging.info("Using cached StanModel")
  if not optimization:
    return sm.sampling(**kwargs)
  else:
    return sm.optimizing(**kwargs) 
开发者ID:tare,项目名称:Lux,代码行数:20,代码来源:lux.py

示例2: run

# 需要导入模块: import pystan [as 别名]
# 或者: from pystan import StanModel [as 别名]
def run(self, samples=1000, chains=1, **kwargs):
        '''
        Run the Stan sampler.
        Args:
            samples (int): Number of samples to obtain (in each chain).
            chains (int): Number of chains to use.
            kwargs (dict): Optional keyword arguments passed onto the PyStan
                StanModel.sampling() call.
        Returns: A PyMC3ModelResults instance.
        '''
        self.fit = self.stan_model.sampling(data=self.X, iter=samples,
                                            chains=chains, **kwargs)
        return self._convert_to_results() 
开发者ID:bambinos,项目名称:bambi,代码行数:15,代码来源:stan.py

示例3: get_or_compile_stan_model

# 需要导入模块: import pystan [as 别名]
# 或者: from pystan import StanModel [as 别名]
def get_or_compile_stan_model(model_file, distribution):
    """
    Creates Stan model. Compiles a Stan model and saves it to .pkl file to the folder selected by tempfile module if
        file doesn't exist yet and load precompiled model if there is a model file in temporary dir.
    Args:
        model_file: model file location
        distribution: name of the KPI distribution model, which assumes a 
            Stan model file with the same name exists
    Returns:
        returns compiled Stan model for the selected distribution or normal distribution
            as a default option
    Note: compiled_model_file is the hardcoded file path which may cause some issues in future.
    There are 2 alternative implementations for Stan models handling:
        1. Using global variables
        2. Pre-compiling stan models and adding them as a part of expan project
        (3). Using temporary files with tempfile module is not currently possible, since it 
            generates a unique file name which is difficult to track.
        However, compiled modules are saved in temporary directory using tempfile module 
        which vary based on the current platform and settings. Cleaning up a temp dir is done on boot.
    """
    python_version = '{0[0]}.{0[1]}'.format(sys.version_info)
    compiled_model_file = tempfile.gettempdir() + '/expan_early_stop_compiled_stan_model_' \
                          + distribution + '_' + python_version + '.pkl'

    if os.path.isfile(compiled_model_file):
        sm = pickle.load(open(compiled_model_file, 'rb'))
    else:
        sm = StanModel(file=model_file)
        with open(compiled_model_file, 'wb') as f:
            pickle.dump(sm, f)
    return sm 
开发者ID:zalando,项目名称:expan,代码行数:33,代码来源:early_stopping.py

示例4: build_stan_models

# 需要导入模块: import pystan [as 别名]
# 或者: from pystan import StanModel [as 别名]
def build_stan_models(target_dir, models_dir=MODELS_DIR):
    from pystan import StanModel
    for model_type in ['linear', 'logistic']:
        model_name = 'prophet_{}_growth.stan'.format(model_type)
        target_name = '{}_growth.pkl'.format(model_type)
        with open(os.path.join(models_dir, model_name)) as f:
            model_code = f.read()
        sm = StanModel(model_code=model_code)
        with open(os.path.join(target_dir, target_name), 'wb') as f:
            pickle.dump(sm, f, protocol=pickle.HIGHEST_PROTOCOL) 
开发者ID:facebook,项目名称:prophet,代码行数:12,代码来源:setup.py

示例5: load_stan_model

# 需要导入模块: import pystan [as 别名]
# 或者: from pystan import StanModel [as 别名]
def load_stan_model( model_name ):
    """
    Load stan model from disk,
    if not exist, compile the model from source code
    """
    try:
        stan_model = cPickle.load( open(model_name + ".model", 'rb') )
    except IOError:
        stan_model = pystan.StanModel( file = model_name + ".stan" )
        with open(model_name + ".model", 'wb') as fout:
            cPickle.dump(stan_model, fout)
        pass

    return stan_model 
开发者ID:dtrckd,项目名称:pymake,代码行数:16,代码来源:mmsb_stan.py

示例6: fit_model

# 需要导入模块: import pystan [as 别名]
# 或者: from pystan import StanModel [as 别名]
def fit_model(data, team_map, model, use_cache, **kwargs):
    """
    Fit a Stan model and return the output.

    Arguments:
     * data      -- Data containing football scores : pd.DataFrame
     * team_map  -- name to id mapping : Dict
     * model     -- Model to be fit : model.SoccerModel
     * use_cache -- Whether the compiled Stan model should be loaded
                    from/saved to file : Bool

    Keyword arguments are passed to pystan.StanModel.sampling
    """
    if use_cache:
        cache_file = os.path.join(os.path.dirname(__file__),
                                  '../cache/{0}.pkl'.format(model.name))
        try:
            stan_model = joblib.load(cache_file)
        except FileNotFoundError:
            stan_model = pystan.StanModel(model.modelfile)
            joblib.dump(stan_model, cache_file)
    else:
        stan_model = pystan.StanModel(model.modelfile)

    model_data = {
        'n_teams': len(team_map),
        'n_games': len(data),
        'home_team': data['home_team_id'],
        'away_team': data['away_team_id'],
        'home_goals': data['home_goals'],
        'away_goals': data['away_goals']
    }

    fit = stan_model.sampling(data=model_data, **kwargs)
    output = fit.extract()

    # Tidy the output a little...
    reverse_map = {v: k for k, v in team_map.items()}
    for param in model.team_parameters:
        df = pd.DataFrame(output[param])
        df.columns = [reverse_map[id_ + 1] for id_ in df.columns]
        output[param] = df

    return output 
开发者ID:Torvaney,项目名称:soccerstan,代码行数:46,代码来源:soccerstan.py


注:本文中的pystan.StanModel方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。