當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。