Either argmax or random sampling.

  Args:
    logits: a Tensor.
    temperature: a float  0.0=argmax 1.0=random
    sampling_keep_top_k: If not -1, only sample from the top k logits.
  Returns:
    a Tensor with one fewer dimension than logits.
966553
def sample_with_temperature(logits, temperature, sampling_keep_top_k=-1):
  
  if temperature == 0.0:
    # TF argmax doesn't handle >5 dimensions, so we reshape here.
    logits_shape = shape_list(logits)
    argmax = tf.argmax(tf.reshape(logits, [-1, logits_shape[-1]]), axis=1)
    return tf.reshape(argmax, logits_shape[:-1])
  else:
    assert temperature > 0.0

    if sampling_keep_top_k != -1:
      if sampling_keep_top_k <= 0:
        raise ValueError("sampling_keep_top_k must either be -1 or positive.")

      vocab_size = shape_list(logits)[1]

      k_largest = tf.contrib.nn.nth_element(
          logits, n=sampling_keep_top_k, reverse=True)
      k_largest = tf.tile(tf.reshape(k_largest, [-1, 1]), [1, vocab_size])

      # Force every position that is not in the top k to have probability near
      # 0 by setting the logit to be very negative.
      logits = tf.where(tf.less_equal(logits, k_largest),
                        tf.ones_like(logits)*-1e6, logits)

    reshaped_logits = (
        tf.reshape(logits, [-1, shape_list(logits)[-1]]) / temperature)
    choices = tf.multinomial(reshaped_logits, 1)
    choices = tf.reshape(choices,
                         shape_list(logits)[:logits.get_shape().ndims - 1])
    return choices
641241
def argresample(a,**kwargs):
    '''
    
    '''
    
    dt=kwargs.get('dt',np.median(deriv(a)))
    
    h,_=np.histogram(a, bins=(a.max()-a.min())/dt + 1, range=[a.min()-dt/2.,a.max()+dt/2.])
    
    return h.astype(bool)
954688
def resample(self,N):
        
        return rand.random(size=N)*(self.maxval - self.minval) + self.minval
312432
def sample(self, num_samples=1):
        
        self.check_fit()
        return np.random.normal(self.mean, self.std, num_samples)
1146656
def logit_(x:Tensor)->Tensor:
    ""
    x.clamp_(1e-7, 1-1e-7)
    return (x.reciprocal_().sub_(1)).log_().neg_()
489804
def top_k_accuracy(input:Tensor, targs:Tensor, k:int=5)->Rank0Tensor:
    ""
    input = input.topk(k=k, dim=-1)[1]
    targs = targs.unsqueeze(dim=-1).expand_as(input)
    return (input == targs).max(dim=-1)[0].float().mean()
1304447
def sample_with_temperature(x, dim, temperature=1.0, dtype=tf.int32, name=None):
  
  dim = convert_to_dimension(dim)
  with tf.name_scope(name, default_name="sample_with_temperature"):
    if temperature != 0.0:
      # gumbel trick.
      # Note: we don't want to generate 0 or 1 because:
      # * -log(-log(0)) is -infinity
      # * -log(-log(1)) is +infinity.
      # np.finfo(x.dtype.as_numpy_dtype).tiny doesn't work on bfloat16
      tiny_val = 1e-9
      g = -log(-log(
          random_uniform(
              x.mesh,
              x.shape,
              minval=tiny_val,
              maxval=1.,
              dtype=x.dtype)))
      x += g * temperature
    return argmax(x, dim, dtype, name)
508930
def rargmax(x, eps=1e-8):
    
    idxs = np.where(abs(x - np.max(x, axis=0)) < eps)[0]
    return np.random.choice(idxs)
730891
def sample(self, nsample=None, **kwargs):
        
        if len(kwargs) > 0:
            self.update(**kwargs)
        return self.distribution.rvs(*self.args, size=len(self),
                                     loc=self.loc, scale=self.scale)
439303
def sample(self, rstate=None):
        

        if rstate is None:
            rstate = np.random

        return self.ctr + self.randoffset(rstate=rstate)
216929
def refresh(self)->None:
        ""
        if self._logit_px is not None:
            self._px = self._logit_px.sigmoid_()
            self._logit_px = None
        if self._affine_mat is not None or self._flow is not None:
            self._px = _grid_sample(self._px, self.flow, **self.sample_kwargs)
            self.sample_kwargs = {}
            self._flow = None
        return self
1107764
def rvs(self, *args, **kwargs):
        
        # TODO REVERSE THIS FUCK PYTHON2
        size = kwargs.pop('size', 1)
        random_state = kwargs.pop('size', None)
        # don't ask me why it uses `self._size`
        return self._kde.sample(n_samples=size, random_state=random_state)
1127767
def generate(self, x, **kwargs):
    
    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    labels, _nb_classes = self.get_or_guess_labels(x, kwargs)

    return fgm(
        x,
        self.model.get_logits(x),
        y=labels,
        eps=self.eps,
        ord=self.ord,
        clip_min=self.clip_min,
        clip_max=self.clip_max,
        targeted=(self.y_target is not None),
        sanity_checks=self.sanity_checks)
1327198
def entropy(self, logits):
        
        probs = torch.exp(logits)
        entropy = - torch.sum(probs * logits, dim=-1)
        return entropy
92004
def _sample_item(self, **kwargs):
        
        loc = np.random.choice(self._n_items, p = self._inst_pmf)
        weight = (1/self._n_items)/self._inst_pmf[loc]
        return loc, weight, {}
975334
def samples(self, nsamples, rstate=None):
        

        if rstate is None:
            rstate = np.random

        xs = np.array([self.sample(rstate=rstate) for i in range(nsamples)])

        return xs
1219515
def inv_logistic(y: Union[float, np.ndarray],
                 k: float,
                 theta: float) -> Optional[float]:
    

    """
    if y is None or k is None or theta is None:
        return None
    # noinspection PyUnresolvedReferences
    return (np.log((1 / y) - 1) / -k) + theta