Returns an instance of Bayesian Model.
347549
def get_model(self):
        
        model = BayesianModel()
        model.add_nodes_from(self.variables)
        model.add_edges_from(self.edges)
        model.name = self.model_name

        tabular_cpds = []
        for var, values in self.variable_CPD.items():
            evidence = values['CONDSET'] if 'CONDSET' in values else []
            cpd = values['DPIS']
            evidence_card = values['CARDINALITY'] if 'CARDINALITY' in values else []
            states = self.variables[var]['STATES']
            cpd = TabularCPD(var, len(states), cpd,
                             evidence=evidence,
                             evidence_card=evidence_card)
            tabular_cpds.append(cpd)

        model.add_cpds(*tabular_cpds)

        if nx.__version__.startswith('1'):
            for var, properties in self.variables.items():
                model.node[var] = properties
        else:
            for var, properties in self.variables.items():
                model._node[var] = properties

        return model
1150054
def get_for_model(self, model):
        
        return self.get_or_create(
            content_type    = ContentType.objects.get_for_model(model),
            object_id       = model.pk
        )
1232295
def _parse_posterior(self):
        """"""
        paths = self.posterior_
        if isinstance(paths, str):
            paths = [paths]
        chain_data = []
        for path in paths:
            parsed_output = _read_output(path)
            for sample, sample_stats, config, adaptation, timing in parsed_output:
                chain_data.append(
                    {
                        "sample": sample,
                        "sample_stats": sample_stats,
                        "configuration_info": config,
                        "adaptation_info": adaptation,
                        "timing_info": timing,
                    }
                )
        self.posterior = [item["sample"] for item in chain_data]
        self.sample_stats = [item["sample_stats"] for item in chain_data]
897235
def model_argmax(model, samples):
  
  tfe = tf.contrib.eager
  tf_samples = tfe.Variable(samples)
  probabilities = model.get_probs(tf_samples)

  if samples.shape[0] == 1:
    return tf.argmax(probabilities)
  else:
    return tf.argmax(probabilities, axis=1)
1056049
def create_model_instance(self, data):
        
        return self.model(
            session_key=self._get_or_create_session_key(),
            session_data=self.encode(data),
            expire_date=self.get_expiry_date(),
        )
260661
def posterior(self, x, Sigma=None):
        
        n = x.shape[0]
        Sigma = np.eye(self.dim) if Sigma is None else Sigma
        Siginv = inv(Sigma)
        Qpost = inv(self.cov) + n * Siginv
        Sigpost = inv(Qpost)
        mupost = (np.matmul(Siginv, self.mean) + 
                  np.matmu(Siginv, np.sum(x, axis=0)))
        return MvNormal(loc=mupost, cov=Sigpost)
1032026
def build_modules(is_training, vocab_size):
  """"""

  # Construct the custom getter which implements Bayes by Backprop.
  if is_training:
    estimator_mode = tf.constant(bbb.EstimatorModes.sample)
  else:
    estimator_mode = tf.constant(bbb.EstimatorModes.mean)
  lstm_bbb_custom_getter = bbb.bayes_by_backprop_getter(
      posterior_builder=lstm_posterior_builder,
      prior_builder=custom_scale_mixture_prior_builder,
      kl_builder=bbb.stochastic_kl_builder,
      sampling_mode_tensor=estimator_mode)
  non_lstm_bbb_custom_getter = bbb.bayes_by_backprop_getter(
      posterior_builder=non_lstm_posterior_builder,
      prior_builder=custom_scale_mixture_prior_builder,
      kl_builder=bbb.stochastic_kl_builder,
      sampling_mode_tensor=estimator_mode)

  embed_layer = snt.Embed(
      vocab_size=vocab_size,
      embed_dim=FLAGS.embedding_size,
      custom_getter=non_lstm_bbb_custom_getter,
      name="input_embedding")

  cores = []
  for i in range(FLAGS.n_layers):
    cores.append(
        snt.LSTM(FLAGS.hidden_size,
                 custom_getter=lstm_bbb_custom_getter,
                 forget_bias=0.0,
                 name="lstm_layer_{}".format(i)))

  rnn_core = snt.DeepRNN(
      cores,
      skip_connections=False,
      name="deep_lstm_core")

  # Do BBB on weights but not biases of output layer.
  output_linear = snt.Linear(
      vocab_size, custom_getter={"w": non_lstm_bbb_custom_getter})
  return embed_layer, rnn_core, output_linear
414738
def get_model(model, ctx, opt):
    """"""
    kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes}
    if model.startswith('resnet'):
        kwargs['thumbnail'] = opt.use_thumbnail
    elif model.startswith('vgg'):
        kwargs['batch_norm'] = opt.batch_norm

    net = models.get_model(model, **kwargs)
    if opt.resume:
        net.load_parameters(opt.resume)
    elif not opt.use_pretrained:
        if model in ['alexnet']:
            net.initialize(mx.init.Normal())
        else:
            net.initialize(mx.init.Xavier(magnitude=2))
    net.cast(opt.dtype)
    return net
799579
def sample_from_posterior(self, A: pd.DataFrame) -> None:
        
        self.sample_from_proposal(A)
        self.set_latent_state_sequence(A)
        self.update_log_prior(A)
        self.update_log_likelihood()

        candidate_log_joint_probability = self.log_prior + self.log_likelihood

        delta_log_joint_probability = (
            candidate_log_joint_probability - self.log_joint_probability
        )

        acceptance_probability = min(1, np.exp(delta_log_joint_probability))
        if acceptance_probability > np.random.rand():
            self.update_log_joint_probability()
        else:
            A[f"∂({self.source})/∂t"][self.target] = self.original_value
            self.set_latent_state_sequence(A)
            self.update_log_likelihood()
            self.update_log_prior(A)
            self.update_log_joint_probability()
1371902
def get_domain(self):
        
        if isinstance(self.model, BayesianModel):
            cpds = self.model.get_cpds()
            cpds.sort(key=lambda x: x.variable)
            domain = {}
            for cpd in cpds:
                domain[cpd.variable] = str(cpd.variable_card)
            return domain
        elif isinstance(self.model, MarkovModel):
            factors = self.model.get_factors()
            domain = {}
            for factor in factors:
                variables = factor.variables
                for var in variables:
                    if var not in domain:
                        domain[var] = str(factor.get_cardinality([var])[var])
            return domain
        else:
            raise TypeError("Model must be an instance of Markov or Bayesian model.")
1111264
def get_model(self):
        
        model_cls = get_connected_model_for_table_name(self.table_name)
        return model_cls._default_manager.filter(id=self.record_id).first()
978499
def getInstance(self):
        
        try:
            return self._instance
        except AttributeError:
            self._instance = self._decorated()
            return self._instance
1233072
def from_pymc3(trace=None, *, prior=None, posterior_predictive=None, coords=None, dims=None):
    """"""
    return PyMC3Converter(
        trace=trace,
        prior=prior,
        posterior_predictive=posterior_predictive,
        coords=coords,
        dims=dims,
    ).to_inference_data()
815127
def get_model(self):
        '''
        
        '''
        class Model(object):
            def __init__(self, lstm_model):
                self.lstm_model = lstm_model
        return Model(self.__lstm_model)
1065103
def pandas(self):
        
        names,prior,posterior = [],[],[]
        for iname,name in enumerate(self.posterior_parameter.row_names):
            names.append(name)
            posterior.append(np.sqrt(float(
                self.posterior_parameter[iname, iname]. x)))
            iprior = self.parcov.row_names.index(name)
            prior.append(np.sqrt(float(self.parcov[iprior, iprior].x)))
        for pred_name, pred_var in self.posterior_prediction.items():
            names.append(pred_name)
            posterior.append(np.sqrt(pred_var))
            prior.append(self.prior_prediction[pred_name])
        return pd.DataFrame({"posterior": posterior, "prior": prior},
                                index=names)
1053764
def get_model(self):
        

        if self.maplesat and self.status == True:
            model = pysolvers.maplecm_model(self.maplesat)
            return model if model != None else []
1138867
def _model(self, t, theta, period, tmpid):
        """"""
        template = self.templates[tmpid]
        phase = (t / period - theta[2]) % 1
        return theta[0] + theta[1] * template(phase)