Transform numeric labels into onehot_labels.

  Args:
    labels: [batch_size] target labels.
    num_classes: total number of classes.
    scope: Optional scope for name_scope.
  Returns:
    one hot encoding of the labels.
186024
def one_hot_encoding(labels, num_classes, scope=None):
  
  with tf.name_scope(scope, 'OneHotEncoding', [labels]):
    batch_size = labels.get_shape()[0]
    indices = tf.expand_dims(tf.range(0, batch_size), 1)
    labels = tf.cast(tf.expand_dims(labels, 1), indices.dtype)
    concated = tf.concat(axis=1, values=[indices, labels])
    onehot_labels = tf.sparse_to_dense(
        concated, tf.stack([batch_size, num_classes]), 1.0, 0.0)
    onehot_labels.set_shape([batch_size, num_classes])
    return onehot_labels
872245
def dense_to_one_hot(labels_dense, num_classes):
        """"""
        num_labels = labels_dense.shape[0]
        index_offset = np.arange(num_labels) * num_classes
        labels_one_hot = np.zeros((num_labels, num_classes))
        labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
        return labels_one_hot
765336
def __set_labels(self, labels):
        
        with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), 'w') \
                as file_desc:
            for label in labels:
                file_desc.write("%s,%s\n" % (label.name,
                                             label.get_color_str()))
412325
def provide_label(self):
        """"""
        return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
1204933
def label_from_lists(self, train_labels:Iterator, valid_labels:Iterator, label_cls:Callable=None, **kwargs)->'LabelList':
        ""
        label_cls = self.train.get_label_cls(train_labels, label_cls)
        self.train = self.train._label_list(x=self.train, y=label_cls(train_labels, **kwargs))
        self.valid = self.valid._label_list(x=self.valid, y=self.train.y.new(valid_labels, **kwargs))
        self.__class__ = LabelLists
        self.process()
        return self
674471
def extract_labels(filename):
    """"""
    with gzip.open(filename) as bytestream:
        magic = _read32(bytestream)
        if magic != 2049:
            raise ValueError(
                'Invalid magic number %d in MNIST label file: %s' %
                (magic, filename))
        num_items = _read32(bytestream)
        buf = bytestream.read(num_items)
        labels = numpy.frombuffer(buf, dtype=numpy.uint8)
        return labels
949150
function labelForScope(scope) {
        if (scope) {
            return StringUtils.format(
                Strings.FIND_IN_FILES_SCOPED,
                StringUtils.breakableUrl(
                    ProjectManager.makeProjectRelativeIfPossible(scope.fullPath)
                )
            );
        } else {
            return Strings.FIND_IN_FILES_NO_SCOPE;
        }
    }
896880
def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:
    

    return {index: label for index, label in
            enumerate(["pad"] + sorted(list(labels)))}
1176778
def _get_constrained_labels(self,remove_dimensions=False,**kwargs):
        
        new_labels = []
        for label_no,label in enumerate(self.labels):
            new_label = LabelDimension(label)
            remove = False
            for k in kwargs:
                if k == label.name:
                    new_label.max = kwargs[k]
                    new_label.min = kwargs[k]
                    remove = True
                if k == label.name+'__lt':
                    if new_label.units == '1':
                        new_label.max = np.min([new_label.max,kwargs[k]-1]) # is this right?
                    else:
                        new_label.max = np.min([new_label.max,kwargs[k]])
                    #remove = True
                if k == label.name+'__lte':
                    new_label.max = np.min([new_label.max,kwargs[k]])
                    #remove = True
                if k == label.name+'__gt':
                    if new_label.units == '1':
                        new_label.min = np.max([new_label.min,kwargs[k]+1])
                    else:
                        new_label.min = np.max([new_label.min,kwargs[k]])
                    #remove = True
                if k == label.name+'__gte':
                    new_label.min = np.max([new_label.min,kwargs[k]])
                    #remove = True
                if k == label.name+'__evals':
                    remove = True
            if remove_dimensions:
                if remove:
                    # skipping removed labels
                    continue
            new_labels.append(new_label)
        return new_labels
698959
def label_set(self):
        """"""
        label_set = list()
        for class_ in self.class_set:
            samples_in_class = self.sample_ids_in_class(class_)
            label_set.append(self.labels[samples_in_class[0]])

        return label_set
271649
def build_label(self, ident, cls):
        
        ident_w_label = ident + ':' + cls.__label__
        self._ast['match'].append('({0})'.format(ident_w_label))
        self._ast['return'] = ident
        self._ast['result_class'] = cls
        return ident
977283
def resp_set_label(self, resp, label=None):
        
        if label:
            self.label=label
        elif resp:
            self.label=resp.label.decode().replace("\x00", "")
1037276
def labels(self):
        
        return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label]
17419
def render_label(content, label_for=None, label_class=None, label_title=""):
    
    attrs = {}
    if label_for:
        attrs["for"] = label_for
    if label_class:
        attrs["class"] = label_class
    if label_title:
        attrs["title"] = label_title
    return render_tag("label", attrs=attrs, content=content)
521707
def softmax_max_pooling_class_label_top(body_output,
                                        targets,
                                        model_hparams,
                                        vocab_size):
  """"""
  del targets  # unused arg
  with tf.variable_scope(
      "softmax_max_pooling_onehot_class_label_modality_%d_%d" % (
          vocab_size, model_hparams.hidden_size)):
    x = body_output
    x = tf.reduce_max(x, axis=1, keepdims=True)
    return tf.layers.dense(x, vocab_size)
576105
def _label_from_list(self, labels:Iterator, label_cls:Callable=None, from_item_lists:bool=False, **kwargs)->'LabelList':
        ""
        if not from_item_lists:
            raise Exception("Your data isn't split, if you don't want a validation set, please use `split_none`.")
        labels = array(labels, dtype=object)
        label_cls = self.get_label_cls(labels, label_cls=label_cls, **kwargs)
        y = label_cls(labels, path=self.path, **kwargs)
        res = self._label_list(x=self, y=y)
        return res
1039009
def get_labels(filename, logger=None):
    
    labeldict = {}
    if filename is not None:
        if logger:
            logger.info("Reading labels from %s", filename)
        with open(filename, "r") as ifh:
            count = 0
            for line in ifh.readlines():
                count += 1
                try:
                    key, label = line.strip().split("\t")
                except ValueError:
                    if logger:
                        logger.warning("Problem with class file: %s", filename)
                        logger.warning("%d: %s", (count, line.strip()))
                        logger.warning("(skipping line)")
                    continue
                else:
                    labeldict[key] = label
    return labeldict