Logarithm of probability of given sample
544486
def logprob(self, actions, action_logits):
        
        neg_log_prob = F.nll_loss(action_logits, actions, reduction='none')
        return -neg_log_prob
52361
def random_samples(self, n):
        
        samples = self.samples
        inds = rand.randint(len(samples),size=int(n))

        newsamples = samples.iloc[inds]
        newsamples.reset_index(inplace=True)
        return newsamples
1321910
def sampled_logs(self, logs_limit=-1):
        
        logs_count = len(self.logs)
        if logs_limit == -1 or logs_count <= logs_limit:
            return self.logs
        elif logs_limit == 0:
            return []
        elif logs_limit == 1:
            return [self.logs[-1]]
        else:
            def get_sampled_log(idx):
                # always include the first and last element of `self.logs`
                return self.logs[idx * (logs_count - 1) // (logs_limit - 1)]
            return [get_sampled_log(i) for i in range(logs_limit)]
743085
public static Distribution guessNumberOfBins(DataSet data)
    {
        if(data.size() < 20)
            return new UniformDiscrete(2, data.size()-1);
        else if(data.size() >= 1000000)
            return new LogUniform(50, 1000);
        int sqrt = (int) Math.sqrt(data.size());
        return new UniformDiscrete(Math.max(sqrt/3, 2), Math.min(sqrt*3, data.size()-1));
    }
851071
def data_log_likelihood(self, successes, trials, beta):
        ''''''
        return binom.logpmf(successes, trials, 1.0 / (1 + np.exp(-beta))).sum()
1295563
def loglikelihood(self, x, previous=False):
        """"""
        # testing of original fct: MC integrate must be one: mean(p(x_i)) * volume(where x_i are uniformely sampled)
        # for i in xrange(3): print mean([cma.likelihood(20*r-10, dim * [0], None, 3) for r in rand(10000,dim)]) * 20**dim
        # TODO: test this!!
        # c=cma.fmin...
        # c[3]['cma'].loglikelihood(...)

        if previous and hasattr(self, 'lastiter'):
            sigma = self.lastiter.sigma
            Crootinv = self.lastiter._Crootinv
            xmean = self.lastiter.mean
            D = self.lastiter.D
        elif previous and self.countiter > 1:
            raise _Error('no previous distribution parameters stored, check options importance_mixing')
        else:
            sigma = self.sigma
            Crootinv = self._Crootinv
            xmean = self.mean
            D = self.D

        dx = array(x) - xmean  # array(x) - array(m)
        n = self.N
        logs2pi = n * log(2 * np.pi) / 2.
        logdetC = 2 * sum(log(D))
        dx = np.dot(Crootinv, dx)
        res = -sum(dx**2) / sigma**2 / 2 - logs2pi - logdetC / 2 - n * log(sigma)
        if 1 < 3:  # testing
            s2pi = (2 * np.pi)**(n / 2.)
            detC = np.prod(D)**2
            res2 = -sum(dx**2) / sigma**2 / 2 - log(s2pi * abs(detC)**0.5 * sigma**n)
            assert res2 < res + 1e-8 or res2 > res - 1e-8
        return res
485897
function randnBM() {
  const u = 1 - Math.random() // Subtraction to flip [0, 1) to (0, 1].
  const v = 1 - Math.random()
  return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v)
}
913300
def log_likelihood(C, T):
    
    C = C.tocsr()
    T = T.tocsr()
    ind = scipy.nonzero(C)
    relT = np.array(T[ind])[0, :]
    relT = np.log(relT)
    relC = np.array(C[ind])[0, :]

    return relT.dot(relC)
954688
def resample(self,N):
        
        return rand.random(size=N)*(self.maxval - self.minval) + self.minval
1256683
def _num_samples(x):
    """"""
    if hasattr(x, 'fit'):
        # Don't get num_samples from an ensembles length!
        raise TypeError('Expected sequence or array-like, got '
                        'estimator %s' % x)
    if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
        if hasattr(x, '__array__'):
            x = np.asarray(x)
        else:
            raise TypeError("Expected sequence or array-like, got %s" %
                            type(x))
    if hasattr(x, 'shape'):
        if len(x.shape) == 0:
            raise TypeError("Singleton array %r cannot be considered"
                            " a valid collection." % x)
        return x.shape[0]
    else:
        return len(x)
985675
def _init_parameters_random(self, X_bin):
        

        _, n_features = X_bin.shape

        # The parameter class_log_prior_ has shape (2,). The values represent
        # 'match' and 'non-match'.
        rand_vals = np.random.rand(2)
        class_prior = rand_vals / np.sum(rand_vals)

        # make empty array of feature log probs
        # dimensions 2xn_features
        feature_prob = np.zeros((2, n_features))

        feat_i = 0

        for i, bin in enumerate(self._binarizers):

            bin_len = bin.classes_.shape[0]

            rand_vals_0 = np.random.rand(bin_len)
            feature_prob[0, feat_i:feat_i + bin_len] = \
                rand_vals_0 / np.sum(rand_vals_0)

            rand_vals_1 = np.random.rand(bin_len)
            feature_prob[1, feat_i:feat_i + bin_len] = \
                rand_vals_1 / np.sum(rand_vals_1)

            feat_i += bin_len

        return np.log(class_prior), np.log(feature_prob)
1035077
def _sample(self, position, stepsize):
        

        # Re-sampling momentum
        momentum = np.random.normal(0, 1, len(position))

        # Initializations
        depth = 0
        position_backward, position_forward = position, position
        momentum_backward, momentum_forward = momentum, momentum
        candidate_set_size = accept_set_bool = 1
        _, log_pdf = self.grad_log_pdf(position, self.model).get_gradient_log_pdf()

        # Resample slice variable `u`
        slice_var = np.random.uniform(0, np.exp(log_pdf - 0.5 * np.dot(momentum, momentum)))

        while accept_set_bool == 1:
            direction = np.random.choice([-1, 1], p=[0.5, 0.5])
            if direction == -1:
                # Build a tree in backward direction
                (position_backward, momentum_backward, _, _, position_bar,
                 candidate_set_size2, accept_set_bool2) = self._build_tree(position_backward, momentum_backward,
                                                                           slice_var, direction, depth, stepsize)
            else:
                # Build tree in forward direction
                (_, _, position_forward, momentum_forward, position_bar,
                 candidate_set_size2, accept_set_bool2) = self._build_tree(position_forward, momentum_forward,
                                                                           slice_var, direction, depth, stepsize)
            if accept_set_bool2 == 1:
                if np.random.rand() < candidate_set_size2 / candidate_set_size:
                    position = position_bar.copy()

            accept_set_bool, candidate_set_size = self._update_acceptance_criteria(position_forward, position_backward,
                                                                                   momentum_forward, momentum_backward,
                                                                                   accept_set_bool2, candidate_set_size,
                                                                                   candidate_set_size2)
            depth += 1

        return position
595792
function randn() {
  var u, v, s;
  do {
    u = Math.random() * 2 - 1;
    v = Math.random() * 2 - 1;
    s = u * u + v * v;
  } while (s >= 1 || s == 0);
  s = Math.sqrt(-2 * Math.log(s) / s);
  return u * s;
}
309994
private double logLikelihood(int[] contingencyTable) {
        // Rename for short-hand convenience
        int[] t = contingencyTable;
        int col1sum = t[0] + t[2];
        int col2sum = t[1] + t[3];
        int row1sum = t[0] + t[1];
        int row2sum = t[2] + t[3];
        double sum = row1sum + row2sum;
        
        // Calculate the expected values for a, b, c, d
        double aExp = (row1sum / sum) * col1sum;
        double bExp = (row1sum / sum) * col2sum;
        double cExp = (row2sum / sum) * col1sum;
        double dExp = (row2sum / sum) * col2sum;

        return 2 *
            ((t[0] * Math.log(t[0] - aExp))  +
             (t[1] * Math.log(t[1] - bExp))  +
             (t[2] * Math.log(t[2] - cExp))  +
             (t[3] * Math.log(t[3] - dExp)));
    }
511775
def shannon_entropy(p):
    
    return -np.sum(np.where(p!=0, p * np.log2(p), 0))
865639
def sample_number_of_occurrences(self, n=1):
        
        # compute cdf from pmf
        cdf = numpy.cumsum(self.probs_occur)
        n_occ = numpy.digitize(numpy.random.random(n), cdf)
        return n_occ
269029
def sample(self, logits, argmax_sampling=False):
        
        if argmax_sampling:
            return torch.argmax(logits, dim=-1)
        else:
            u = torch.rand_like(logits)
            return torch.argmax(logits - torch.log(-torch.log(u)), dim=-1)