Simple semi-supervised classification, by assigning unlabeled vertices
    the label of nearest labeled vertex.

    partial_labels: (n,) array of integer labels, -1 for unlabeled.
542195
def classify_nearest(self, partial_labels):
    '''
    '''
    labels = np.array(partial_labels, copy=True)
    unlabeled = labels == -1
    # compute geodesic distances from unlabeled vertices
    D_unlabeled = self.shortest_path(weighted=True)[unlabeled]
    # set distances to other unlabeled vertices to infinity
    D_unlabeled[:,unlabeled] = np.inf
    # find shortest distances to labeled vertices
    idx = D_unlabeled.argmin(axis=1)
    # apply the label of the closest vertex
    labels[unlabeled] = labels[idx]
    return labels
926601
def _compute_labels(self, element, data, mapping):
        
        if element.vdims:
            edges = Dataset(element)[element[element.vdims[0].name]>0]
            nodes = list(np.unique([edges.dimension_values(i) for i in range(2)]))
            nodes = element.nodes.select(**{element.nodes.kdims[2].name: nodes})
        else:
            nodes = element

        label_dim = nodes.get_dimension(self.label_index)
        labels = self.labels
        if label_dim and labels:
            if self.label_index not in [2, None]:
                self.param.warning(
                    "Cannot declare style mapping for 'labels' option "
                    "and declare a label_index; ignoring the label_index.")
        elif label_dim:
            labels = label_dim
        if isinstance(labels, basestring):
            labels = element.nodes.get_dimension(labels)

        if labels is None:
            text = []
        if isinstance(labels, dim):
            text = labels.apply(element, flat=True)
        else:
            text = element.nodes.dimension_values(labels)
            text = [labels.pprint_value(v) for v in text]

        value_dim = element.vdims[0]
        text_labels = []
        for i, node in enumerate(element._sankey['nodes']):
            if len(text):
                label = text[i]
            else:
                label = ''
            if self.show_values:
                value = value_dim.pprint_value(node['value'])
                if label:
                    label = '%s - %s' % (label, value)
                else:
                    label = value
            if value_dim.unit:
                label += ' %s' % value_dim.unit
            if label:
                text_labels.append(label)

        ys = nodes.dimension_values(1)
        nodes = element._sankey['nodes']
        if nodes:
            offset = (nodes[0]['x1']-nodes[0]['x0'])/4.
        else:
            offset = 0
        if self.label_position == 'right':
            xs = np.array([node['x1'] for node in nodes])+offset
        else:
            xs = np.array([node['x0'] for node in nodes])-offset
        data['text_1'] = dict(x=xs, y=ys, text=[str(l) for l in text_labels])
        align = 'left' if self.label_position == 'right' else 'right'
        mapping['text_1'] = dict(text='text', x='x', y='y', text_baseline='middle', text_align=align)
1018667
def relabel(self, i):
        '''
        
        '''
        min_distance = 2*len(self.get_node_list()) + 1
        for j in self.get_neighbors(i):
            if (self.get_node_attr(j, 'distance') < min_distance and
                (self.get_edge_attr(i, j, 'flow') <
                 self.get_edge_attr(i, j, 'capacity'))):
                min_distance = self.get_node_attr(j, 'distance')
        for j in self.get_in_neighbors(i):
            if (self.get_node_attr(j, 'distance') < min_distance and
                self.get_edge_attr(j, i, 'flow') > 0):
                min_distance = self.get_node_attr(j, 'distance')
        self.set_node_attr(i, 'distance', min_distance + 1)
1358079
def _stmt_graph_annotate_edges(self, edges_to_annotate, **new_labels):
        

        graph = self.graph

        for src, dst in edges_to_annotate:

            if src not in graph:
                continue
            if dst not in graph[src]:
                continue

            data = graph[src][dst]

            for k, v in new_labels.items():
                if k in data:
                    if v not in data[k]:
                        data[k] = data[k] + (v,)
                else:
                    # Construct a tuple
                    data[k] = (v,)
1244762
def check_label_shapes(labels, preds, shape=0):
    """"""

    if shape == 0:
        label_shape, pred_shape = len(labels), len(preds)
    else:
        label_shape, pred_shape = labels.shape, preds.shape

    if label_shape != pred_shape:
        raise ValueError("Shape of labels {} does not match shape of "
                         "predictions {}".format(label_shape, pred_shape))
644830
def from_labels(labels):
        
        labels = labels.astype(int)

        areas = scipy.ndimage.measurements.sum(labels != 0, labels, list(range(1, numpy.max(labels) + 1)))

        existing_labels = [i for (i, a) in enumerate(areas, 1) if a > 0]

        existing_areas = [a for a in areas if a > 0]

        existing_centers = scipy.ndimage.measurements.center_of_mass(labels != 0, labels, existing_labels)

        zipped = zip(existing_labels, existing_centers, existing_areas)

        features = [CellFeatures(c, a, i, labels.shape)
                    for i, c, a in zipped if a != 0]

        return features
229407
def connected_subgraphs(self, directed=True, ordered=False):
    '''
    '''
    num_ccs, labels = self.connected_components(directed=directed)
    # check the trivial case first
    if num_ccs == 1:
      yield self
      raise StopIteration
    if ordered:
      # sort by descending size (num vertices)
      order = np.argsort(np.bincount(labels))[::-1]
    else:
      order = range(num_ccs)

    # don't use self.subgraph() here, because we can reuse adj
    adj = self.matrix('dense', 'csr', 'csc')
    for c in order:
      mask = labels == c
      sub_adj = adj[mask][:,mask]
      yield self.__class__.from_adj_matrix(sub_adj)
642182
def train(self, input, label):
        

        assert self._mode == MpsGraphMode.Train
        assert input.shape == self._ishape
        assert label.shape == self._oshape

        input_array = MpsFloatArray(input)
        label_array = MpsFloatArray(label)
        result_handle = _ctypes.c_void_p()
        status_code = self._LIB.TCMPSTrainGraph(
            self.handle, input_array.handle, label_array.handle,
            _ctypes.byref(result_handle))

        assert status_code == 0, "Error calling TCMPSTrainGraph"
        assert result_handle, "TCMPSTrainGraph unexpectedly returned NULL pointer"

        result = MpsFloatArray(result_handle)

        # Output from training should be a one-dimensional array of loss values,
        # one per example in the batch.
        assert result.shape() == (self._oshape[0],)

        return result
1284992
function connectedComponents_dense(cells, vertex_count) {
  var labels = new UnionFind(vertex_count)
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      for(var k=j+1; k<c.length; ++k) {
        labels.link(c[j], c[k])
      }
    }
  }
  var components = []
    , component_labels = labels.ranks
  for(var i=0; i<component_labels.length; ++i) {
    component_labels[i] = -1
  }
  for(var i=0; i<cells.length; ++i) {
    var l = labels.find(cells[i][0])
    if(component_labels[l] < 0) {
      component_labels[l] = components.length
      components.push([cells[i].slice(0)])
    } else {
      components[component_labels[l]].push(cells[i].slice(0))
    }
  }
  return components
}
1180346
def missing_labels(self):
        

        return np.array(sorted(set(range(0, self.max_label + 1)).
                               difference(np.insert(self.labels, 0, 0))))
366920
def _extract_mnist_labels(filename, num_labels):
  
  with gzip.open(filename) as bytestream:
    bytestream.read(8)
    buf = bytestream.read(num_labels)
    labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)
  return labels
826979
def sample(self, labels):
        

        # neg_samples = torch.empty(0).long()
        n_sample = self.n_sample
        n_tries = 2 * n_sample

        with torch.no_grad():
            neg_samples = torch.multinomial(self.dist, n_tries, replacement=True).unique()
            device = labels.device
            neg_samples = neg_samples.to(device)
            true_log_probs = self.log_q[labels].to(device)
            samp_log_probs = self.log_q[neg_samples].to(device)
            return true_log_probs, samp_log_probs, neg_samples
925196
def index_labels_to_array(labels, dtype=None):
    
    if isinstance(labels, (str, tuple)):
        labels = [labels]

    if not isinstance(labels, (list, np.ndarray)):
        try:
            labels = list(labels)
        except TypeError:  # non-iterable
            labels = [labels]

    labels = asarray_tuplesafe(labels, dtype=dtype)

    return labels
656121
def partial_shape(addr, full_shape):
    
    def size(x, max):
        if isinstance(x, (int, long, numpy.integer)):
            return None
        elif isinstance(x, slice):
            y = min(max, x.stop or max)  # slice limits can go past the bounds
            return 1 + (y - (x.start or 0) - 1) // (x.step or 1)
        elif isinstance(x, collections.Sized):
            if hasattr(x, 'dtype') and x.dtype == bool:
                return x.sum()
            else:
                return len(x)
        else:
            raise TypeError("Unsupported index type %s" % type(x))

    addr = full_address(addr, full_shape)
    if isinstance(addr, numpy.ndarray) and addr.dtype == bool:
        return (addr.sum(),)
    elif all(isinstance(x, collections.Sized) for x in addr):
        return (len(addr[0]),)
    else:
        shape = [size(x, max) for (x, max) in zip(addr, full_shape)]
        return tuple([x for x in shape if x is not None])
891029
def createLabels2D(self):
        
        logger.debug("  Creating 2D labels...")
        self.zmax = np.argmax(self.values,axis=1)
        self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax]

        kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside,
                    threshold=self.threshold,xsize=self.xsize)
        labels,nlabels = CandidateSearch.labelHealpix(**kwargs)
        self.nlabels = nlabels
        self.labels = np.repeat(labels,len(self.distances)).reshape(len(labels),len(self.distances))
        return self.labels, self.nlabels
275012
def label(self, input_grid):
        
        marked = self.find_local_maxima(input_grid)
        marked = np.where(marked >= 0, 1, 0)
        # splabel returns two things in a tuple: an array and an integer
        # assign the first thing (array) to markers
        markers = splabel(marked)[0]
        return markers
353179
def _get_labels_and_weights(self, content, comments):
        
        # extract content and comments
        if 'content' in self.to_extract and 'comments' in self.to_extract:
            labels = np.logical_or(content[0], comments[0]).astype(int)
            weights = content[1],
        # extract content only
        elif 'content' in self.to_extract:
            labels = content[0]
            weights = content[1]
        # extract comments only
        else:
            labels = comments[0]
            weights = comments[1]
        if self.max_block_weight is None:
            weights = np.minimum(weights, self.max_block_weight)

        return labels, weights