Python collections.Sequence() Examples

The following are 30 code examples of collections.Sequence(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module collections , or try the search function .
Example #1
Source File: aggregated_classifier.py    From Attention-Gated-Networks with MIT License 6 votes vote down vote up
def aggregate_output(self):
        """Given a list of predictions from net, make a decision based on aggreagation rule"""
        if isinstance(self.predictions, collections.Sequence):
            logits = []
            for pred in self.predictions:
                logit = self.net.apply_argmax_softmax(pred).unsqueeze(0)
                logits.append(logit)

            logits = torch.cat(logits, 0)
            if self.aggregation == 'max':
                self.pred = logits.data.max(0)[0].max(1)
            elif self.aggregation == 'mean':
                self.pred = logits.data.mean(0).max(1)
            elif self.aggregation == 'weighted_mean':
                self.pred = (self.aggregation_weight.expand_as(logits) * logits).data.mean(0).max(1)
            elif self.aggregation == 'idx':
                self.pred = logits[self.aggregation_param].data.max(1)
        else:
            # Apply a softmax and return a segmentation map
            self.logits = self.net.apply_argmax_softmax(self.predictions)
            self.pred = self.logits.data.max(1) 
Example #2
Source File: myImageTransformations.py    From Attention-Gated-Networks with MIT License 6 votes vote down vote up
def __call__(self, image):
        if isinstance(self.sigma, collections.Sequence):
            sigma = random_num_generator(
                self.sigma, random_state=self.random_state)
        else:
            sigma = self.sigma
        if isinstance(self.mean, collections.Sequence):
            mean = random_num_generator(
                self.mean, random_state=self.random_state)
        else:
            mean = self.mean
        row, col, ch = image.shape
        gauss = self.random_state.normal(mean, sigma, (row, col, ch))
        gauss = gauss.reshape(row, col, ch)
        image += image * gauss
        return image 
Example #3
Source File: myImageTransformations.py    From Attention-Gated-Networks with MIT License 6 votes vote down vote up
def __call__(self, img):
        for t in self.transforms:
            if isinstance(t, collections.Sequence):
                assert isinstance(img, collections.Sequence) and len(img) == len(
                    t), "size of image group and transform group does not fit"
                tmp_ = []
                for i, im_ in enumerate(img):
                    if callable(t[i]):
                        tmp_.append(t[i](im_))
                    else:
                        tmp_.append(im_)
                img = tmp_
            elif callable(t):
                img = t(img)
            elif t is None:
                continue
            else:
                raise Exception('unexpected type')
        return img 
Example #4
Source File: utils.py    From AerialDetection with Apache License 2.0 6 votes vote down vote up
def to_tensor(data):
    """Convert objects of various python types to :obj:`torch.Tensor`.

    Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
    :class:`Sequence`, :class:`int` and :class:`float`.
    """
    if isinstance(data, torch.Tensor):
        return data
    elif isinstance(data, np.ndarray):
        return torch.from_numpy(data)
    elif isinstance(data, Sequence) and not mmcv.is_str(data):
        return torch.tensor(data)
    elif isinstance(data, int):
        return torch.LongTensor([data])
    elif isinstance(data, float):
        return torch.FloatTensor([data])
    else:
        raise TypeError('type {} cannot be converted to tensor.'.format(
            type(data))) 
Example #5
Source File: functional.py    From opencv_transforms with MIT License 6 votes vote down vote up
def normalize(tensor, mean, std):
    """Normalize a tensor image with mean and standard deviation.
    .. note::
        This transform acts in-place, i.e., it mutates the input tensor.
    See :class:`~torchvision.transforms.Normalize` for more details.
    Args:
        tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channely.
    Returns:
        Tensor: Normalized Tensor image.
    """
    if not _is_tensor_image(tensor):
        raise TypeError('tensor is not a torch image.')

    # This is faster than using broadcasting, don't change without benchmarking
    for t, m, s in zip(tensor, mean, std):
        t.sub_(m).div_(s)
    return tensor 
Example #6
Source File: pyparsing.py    From vulscan with MIT License 6 votes vote down vote up
def __init__( self, exprs, savelist = False ):
        super(ParseExpression,self).__init__(savelist)
        if isinstance( exprs, _generatorType ):
            exprs = list(exprs)

        if isinstance( exprs, basestring ):
            self.exprs = [ Literal( exprs ) ]
        elif isinstance( exprs, collections.Sequence ):
            # if sequence of strings provided, wrap with Literal
            if all(isinstance(expr, basestring) for expr in exprs):
                exprs = map(Literal, exprs)
            self.exprs = list(exprs)
        else:
            try:
                self.exprs = list( exprs )
            except TypeError:
                self.exprs = [ exprs ]
        self.callPreparse = False 
Example #7
Source File: hierarchical_encoders.py    From Counterfactual-StoryRW with MIT License 6 votes vote down vote up
def flatten(x):
        """Flattens a cell state by concatenating a sequence of cell
        states along the last dimension. If the cell states are
        :tf_main:`LSTMStateTuple <contrib/rnn/LSTMStateTuple>`, only the
        hidden `LSTMStateTuple.h` is used.

        This process is used by default if :attr:`medium` is not provided
        to :meth:`_build`.
        """
        if isinstance(x, LSTMStateTuple):
            return x.h
        if isinstance(x, collections.Sequence):
            return tf.concat(
                [HierarchicalRNNEncoder.flatten(v) for v in x], -1)
        else:
            return x 
Example #8
Source File: dataset.py    From speaksee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def collate_fn(self):
        def collate(batch):
            if len(self.fields) == 1:
                batch = [batch, ]
            else:
                batch = list(zip(*batch))

            tensors = []
            for field, data in zip(self.fields.values(), batch):
                tensor = field.process(data)
                if isinstance(tensor, collections.Sequence) and any(isinstance(t, torch.Tensor) for t in tensor):
                    tensors.extend(tensor)
                else:
                    tensors.append(tensor)

            if len(tensors) > 1:
                return tensors
            else:
                return tensors[0]

        return collate 
Example #9
Source File: data_parallel.py    From EMANet with GNU General Public License v3.0 6 votes vote down vote up
def dict_gather(outputs, target_device, dim=0):
    """
    Gathers variables from different GPUs on a specified device
      (-1 means the CPU), with dictionary support.
    """
    def gather_map(outputs):
        out = outputs[0]
        if isinstance(out, Variable):
            # MJY(20180330) HACK:: force nr_dims > 0
            if out.dim() == 0:
                outputs = [o.unsqueeze(0) for o in outputs]
            return Gather.apply(target_device, dim, *outputs)
        elif out is None:
            return None
        elif isinstance(out, collections.Mapping):
            return {k: gather_map([o[k] for o in outputs]) for k in out}
        elif isinstance(out, collections.Sequence):
            return type(out)(map(gather_map, zip(*outputs)))
    return gather_map(outputs) 
Example #10
Source File: layers.py    From deepchem with MIT License 6 votes vote down vote up
def build(self, input_shape):
    if isinstance(input_shape, collections.Sequence):
      input_shape = input_shape[0]
    out_channels = input_shape[1]

    if self.weights_initializer is None:
      weights_initializer = tf.keras.initializers.VarianceScaling
    else:
      weights_initializer = self.weights_initializer

    self.dense_H = tf.keras.layers.Dense(
        out_channels,
        activation=self.activation_fn,
        bias_initializer=self.biases_initializer,
        kernel_initializer=weights_initializer)
    self.dense_T = tf.keras.layers.Dense(
        out_channels,
        activation=tf.nn.sigmoid,
        bias_initializer=tf.constant_initializer(-1),
        kernel_initializer=weights_initializer)
    self.built = True 
Example #11
Source File: opencv_functional.py    From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def normalize(tensor, mean, std):
    """Normalize a tensor image with mean and standard deviation.
    .. note::
        This transform acts in-place, i.e., it mutates the input tensor.
    See :class:`~torchvision.transforms.Normalize` for more details.
    Args:
        tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channely.
    Returns:
        Tensor: Normalized Tensor image.
    """
    if not _is_tensor_image(tensor):
        raise TypeError('tensor is not a torch image.')

    # This is faster than using broadcasting, don't change without benchmarking
    for t, m, s in zip(tensor, mean, std):
        t.sub_(m).div_(s)
    return tensor 
Example #12
Source File: pyparsing.py    From jbox with MIT License 6 votes vote down vote up
def __init__( self, exprs, savelist = False ):
        super(ParseExpression,self).__init__(savelist)
        if isinstance( exprs, _generatorType ):
            exprs = list(exprs)

        if isinstance( exprs, basestring ):
            self.exprs = [ Literal( exprs ) ]
        elif isinstance( exprs, collections.Sequence ):
            # if sequence of strings provided, wrap with Literal
            if all(isinstance(expr, basestring) for expr in exprs):
                exprs = map(Literal, exprs)
            self.exprs = list(exprs)
        else:
            try:
                self.exprs = list( exprs )
            except TypeError:
                self.exprs = [ exprs ]
        self.callPreparse = False 
Example #13
Source File: pyparsing.py    From jbox with MIT License 6 votes vote down vote up
def __init__( self, exprs, savelist = False ):
        super(ParseExpression,self).__init__(savelist)
        if isinstance( exprs, _generatorType ):
            exprs = list(exprs)

        if isinstance( exprs, basestring ):
            self.exprs = [ Literal( exprs ) ]
        elif isinstance( exprs, collections.Sequence ):
            # if sequence of strings provided, wrap with Literal
            if all(isinstance(expr, basestring) for expr in exprs):
                exprs = map(Literal, exprs)
            self.exprs = list(exprs)
        else:
            try:
                self.exprs = list( exprs )
            except TypeError:
                self.exprs = [ exprs ]
        self.callPreparse = False 
Example #14
Source File: messages.py    From tattle with Mozilla Public License 2.0 6 votes vote down vote up
def _serialize_internal(cls, msg):
        # insert the name of the class
        data = [msg.__class__.__name__]

        # get list of fields
        fields = msg.__class__.get_fields()
        for field_name, field_type in fields:
            attr = getattr(msg, field_name)
            if field_type is not None and attr is not None:
                # if attr has a field type defined deserialize that field
                data.extend(cls._serialize_internal(attr))
            else:
                if isinstance(attr, str) or isinstance(attr, bytes):
                    data.append(attr)
                elif isinstance(attr, collections.Sequence):
                    data.append([cls._serialize_internal(i) for i in attr])
                elif isinstance(attr, collections.Mapping):
                    data.append({k: cls._serialize_internal(v) for k, v in attr.items()})
                else:
                    data.append(attr)
        return data 
Example #15
Source File: state.py    From tattle with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self, config, queue, events, loop=None):
        """
        Initialize instance of the NodeManager class

        :param config: config object
        :param queue: broadcast queue
        :type config: tattle.config.Configuration
        :type events: tattle.event.EventManager
        :type queue: tattle.queue.BroadcastQueue
        """
        self.config = config
        self._queue = queue
        self._events = events
        self._loop = loop or asyncio.get_event_loop()
        self._leaving = False
        self._nodes = list()
        self._nodes_map = dict()
        self._nodes_lock = asyncio.Lock()
        self._suspect_nodes = dict()
        self._local_node_name = None
        self._local_node_seq = sequence.Sequence() 
Example #16
Source File: brain_fstrings.py    From python-netsurv with MIT License 6 votes vote down vote up
def _clone_node_with_lineno(node, parent, lineno):
    cls = node.__class__
    other_fields = node._other_fields
    _astroid_fields = node._astroid_fields
    init_params = {"lineno": lineno, "col_offset": node.col_offset, "parent": parent}
    postinit_params = {param: getattr(node, param) for param in _astroid_fields}
    if other_fields:
        init_params.update({param: getattr(node, param) for param in other_fields})
    new_node = cls(**init_params)
    if hasattr(node, "postinit") and _astroid_fields:
        for param, child in postinit_params.items():
            if child and not isinstance(child, collections.Sequence):
                cloned_child = _clone_node_with_lineno(
                    node=child, lineno=new_node.lineno, parent=new_node
                )
                postinit_params[param] = cloned_child
        new_node.postinit(**postinit_params)
    return new_node 
Example #17
Source File: brain_fstrings.py    From python-netsurv with MIT License 6 votes vote down vote up
def _clone_node_with_lineno(node, parent, lineno):
    cls = node.__class__
    other_fields = node._other_fields
    _astroid_fields = node._astroid_fields
    init_params = {"lineno": lineno, "col_offset": node.col_offset, "parent": parent}
    postinit_params = {param: getattr(node, param) for param in _astroid_fields}
    if other_fields:
        init_params.update({param: getattr(node, param) for param in other_fields})
    new_node = cls(**init_params)
    if hasattr(node, "postinit") and _astroid_fields:
        for param, child in postinit_params.items():
            if child and not isinstance(child, collections.Sequence):
                cloned_child = _clone_node_with_lineno(
                    node=child, lineno=new_node.lineno, parent=new_node
                )
                postinit_params[param] = cloned_child
        new_node.postinit(**postinit_params)
    return new_node 
Example #18
Source File: nest.py    From lambda-packs with MIT License 6 votes vote down vote up
def _sequence_like(instance, args):
  """Converts the sequence `args` to the same type as `instance`.

  Args:
    instance: an instance of `tuple`, `list`, or a `namedtuple` class.
    args: elements to be converted to a sequence.

  Returns:
    `args` with the type of `instance`.
  """
  if (isinstance(instance, tuple) and
      hasattr(instance, "_fields") and
      isinstance(instance._fields, collections.Sequence) and
      all(isinstance(f, six.string_types) for f in instance._fields)):
    # This is a namedtuple
    return type(instance)(*args)
  else:
    # Not a namedtuple
    return type(instance)(args) 
Example #19
Source File: config.py    From pyshgp with MIT License 5 votes vote down vote up
def constrain_collection(config: PushConfig, coll: Sequence) -> Sequence:
    """Constrains the collection to a size that is safe for Push program execution."""
    if len(coll) > config.collection_size_cap:
        return coll[:config.collection_size_cap]
    return coll 
Example #20
Source File: typing_.py    From uplink with MIT License 5 votes vote down vote up
def convert(self, value):
        if isinstance(value, collections.Sequence):
            return list(map(self._elem_converter, value))
        else:
            # TODO: Handle the case where the value is not an sequence.
            return [self._elem_converter(value)] 
Example #21
Source File: typing_.py    From uplink with MIT License 5 votes vote down vote up
def _base_converter(self, type_):
        if isinstance(type_, BaseTypeConverter.Builder):
            return type_.build()
        elif self._check_typing(type_):
            if issubclass(type_.__origin__, self.typing.Sequence):
                return ListConverter(*type_.__args__)
            elif issubclass(type_.__origin__, self.typing.Mapping):
                return DictConverter(*type_.__args__) 
Example #22
Source File: types.py    From py-solc with MIT License 5 votes vote down vote up
def is_list_like(obj):
    return not is_string(obj) and isinstance(obj, collections.Sequence) 
Example #23
Source File: exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _to_primitive(cls, obj):
        """ recursive to_primitive for basic data types. """
        if isinstance(obj, string_type):
            return obj
        if isinstance(obj, Sequence):
            return [cls._to_primitive(e) for e in obj]
        elif isinstance(obj, Mapping):
            return dict(
                (k, cls._to_primitive(v)) for k, v in obj.items()
            )
        else:
            return str(obj) 
Example #24
Source File: util.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def listify(value):
    if isinstance(value, list):
        return value
    elif value is None:
        return []
    elif isinstance(value, string_type):
        return [value]
    elif isinstance(value, collections.Sequence):
        return list(value)
    else:
        return [value] 
Example #25
Source File: compound.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _coerce(self, value):
        if isinstance(value, list):
            return value
        elif isinstance(value, (string_type, Mapping)): # unacceptable iterables
            pass
        elif isinstance(value, Sequence):
            return value
        elif isinstance(value, Iterable):
            return value
        raise ConversionError(_('Could not interpret the value as a list')) 
Example #26
Source File: sortedlist.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __make_cmp(seq_op, symbol, doc):
        "Make comparator method."
        def comparer(self, other):
            "Compare method for sorted list and sequence."
            if not isinstance(other, Sequence):
                return NotImplemented

            self_len = self._len
            len_other = len(other)

            if self_len != len_other:
                if seq_op is eq:
                    return False
                if seq_op is ne:
                    return True

            for alpha, beta in zip(self, other):
                if alpha != beta:
                    return seq_op(alpha, beta)

            return seq_op(self_len, len_other)

        seq_op_name = seq_op.__name__
        comparer.__name__ = '__{0}__'.format(seq_op_name)
        doc_str = """Return true if and only if sorted list is {0} `other`.

        ``sl.__{1}__(other)`` <==> ``sl {2} other``

        Comparisons use lexicographical order as with sequences.

        Runtime complexity: `O(n)`

        :param other: `other` sequence
        :return: true if sorted list is {0} `other`

        """
        comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
        return comparer 
Example #27
Source File: sortedlist.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __make_cmp(seq_op, symbol, doc):
        "Make comparator method."
        def comparer(self, other):
            "Compare method for sorted list and sequence."
            if not isinstance(other, Sequence):
                return NotImplemented

            self_len = self._len
            len_other = len(other)

            if self_len != len_other:
                if seq_op is eq:
                    return False
                if seq_op is ne:
                    return True

            for alpha, beta in zip(self, other):
                if alpha != beta:
                    return seq_op(alpha, beta)

            return seq_op(self_len, len_other)

        seq_op_name = seq_op.__name__
        comparer.__name__ = '__{0}__'.format(seq_op_name)
        doc_str = """Return true if and only if sorted list is {0} `other`.

        ``sl.__{1}__(other)`` <==> ``sl {2} other``

        Comparisons use lexicographical order as with sequences.

        Runtime complexity: `O(n)`

        :param other: `other` sequence
        :return: true if sorted list is {0} `other`

        """
        comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
        return comparer 
Example #28
Source File: util.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def listify(value):
    if isinstance(value, list):
        return value
    elif value is None:
        return []
    elif isinstance(value, string_type):
        return [value]
    elif isinstance(value, collections.Sequence):
        return list(value)
    else:
        return [value] 
Example #29
Source File: compound.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _coerce(self, value):
        if isinstance(value, list):
            return value
        elif isinstance(value, (string_type, Mapping)): # unacceptable iterables
            pass
        elif isinstance(value, Sequence):
            return value
        elif isinstance(value, Iterable):
            return value
        raise ConversionError(_('Could not interpret the value as a list')) 
Example #30
Source File: sortedlist.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __make_cmp(seq_op, symbol, doc):
        "Make comparator method."
        def comparer(self, other):
            "Compare method for sorted list and sequence."
            if not isinstance(other, Sequence):
                return NotImplemented

            self_len = self._len
            len_other = len(other)

            if self_len != len_other:
                if seq_op is eq:
                    return False
                if seq_op is ne:
                    return True

            for alpha, beta in zip(self, other):
                if alpha != beta:
                    return seq_op(alpha, beta)

            return seq_op(self_len, len_other)

        seq_op_name = seq_op.__name__
        comparer.__name__ = '__{0}__'.format(seq_op_name)
        doc_str = """Return true if and only if sorted list is {0} `other`.

        ``sl.__{1}__(other)`` <==> ``sl {2} other``

        Comparisons use lexicographical order as with sequences.

        Runtime complexity: `O(n)`

        :param other: `other` sequence
        :return: true if sorted list is {0} `other`

        """
        comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
        return comparer