• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python exc.reraise_as函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pylearn2.utils.exc.reraise_as函数的典型用法代码示例。如果您正苦于以下问题:Python reraise_as函数的具体用法?Python reraise_as怎么用?Python reraise_as使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了reraise_as函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: wrapped_func

    def wrapped_func(*args, **kwargs):
        """
        .. todo::

            WRITEME
        """
        try:
            func(*args, **kwargs)
        except TypeError:
            argnames, varargs, keywords, defaults = inspect.getargspec(func)
            posargs = dict(zip(argnames, args))
            bad_keywords = []
            for keyword in kwargs:
                if keyword not in argnames:
                    bad_keywords.append(keyword)

            if len(bad_keywords) > 0:
                bad = ', '.join(bad_keywords)
                reraise_as(TypeError('%s() does not support the following '
                                     'keywords: %s' % (str(func.func_name),
                                                       bad)))
            allargsgot = set(list(kwargs.keys()) + list(posargs.keys()))
            numrequired = len(argnames) - len(defaults)
            diff = list(set(argnames[:numrequired]) - allargsgot)
            if len(diff) > 0:
                reraise_as(TypeError('%s() did not get required args: %s' %
                                     (str(func.func_name), ', '.join(diff))))
            raise
开发者ID:123fengye741,项目名称:pylearn2,代码行数:28,代码来源:call_check.py


示例2: construct_mapping

def construct_mapping(node, deep=False):
    # This is a modified version of yaml.BaseConstructor.construct_mapping
    # in which a repeated key raises a ConstructorError
    if not isinstance(node, yaml.nodes.MappingNode):
        const = yaml.constructor
        message = "expected a mapping node, but found"
        raise const.ConstructorError(None, None,
                                     "%s %s " % (message, node.id),
                                     node.start_mark)
    mapping = {}
    constructor = yaml.constructor.BaseConstructor()
    for key_node, value_node in node.value:
        key = constructor.construct_object(key_node, deep=False)
        try:
            hash(key)
        except TypeError, exc:
            const = yaml.constructor
            reraise_as(const.ConstructorError("while constructing a mapping",
                                              node.start_mark,
                                              "found unacceptable key (%s)" %
                                              (exc, key_node.start_mark)))
        if key in mapping:
            const = yaml.constructor
            raise const.ConstructorError("while constructing a mapping",
                                         node.start_mark,
                                         "found duplicate key (%s)" % key)
        value = constructor.construct_object(value_node, deep=False)
        mapping[key] = value
开发者ID:AlexArgus,项目名称:pylearn2,代码行数:28,代码来源:yaml_parse.py


示例3: write

def write(f, mat):
    """ Write a ndarray to tensorfile.

    Parameters
    ----------
    f : file
        Open file to write into
    mat : ndarray
        Array to save
    """
    def _write_int32(f, i):
        i_array = numpy.asarray(i, dtype='int32')
        if 0:
            logger.debug('writing int32 {0} {1}'.format(i, i_array))
        i_array.tofile(f)

    try:
        _write_int32(f, _dtype_magic[str(mat.dtype)])
    except KeyError:
        reraise_as(TypeError('Invalid ndarray dtype for filetensor format', mat.dtype))

    _write_int32(f, len(mat.shape))
    shape = mat.shape
    if len(shape) < 3:
        shape = list(shape) + [1] * (3 - len(shape))
    if 0:
        logger.debug('writing shape = {0}'.format(shape))
    for sh in shape:
        _write_int32(f, sh)
    mat.tofile(f)
开发者ID:janchorowski,项目名称:pylearn2,代码行数:30,代码来源:filetensor.py


示例4: get_monitoring_channels

    def get_monitoring_channels(self, model, data, ** kwargs):
        self.get_data_specs(model)[0].validate(data)
        rval = OrderedDict()
        composite_specs, mapping = self.get_composite_specs_and_mapping(model)
        nested_data = mapping.nest(data)

        for i, cost in enumerate(self.costs):
            cost_data = nested_data[i]
            try:
                channels = cost.get_monitoring_channels(model, cost_data,
                                                        **kwargs)
                rval.update(channels)
            except TypeError:
                reraise_as(Exception('SumOfCosts.get_monitoring_channels '
                                     'encountered TypeError while calling {0}'
                                     '.get_monitoring_channels'.format(
                                         type(cost))))

            value = cost.expr(model, cost_data, ** kwargs)
            if value is not None:
                name = ''
                if hasattr(value, 'name') and value.name is not None:
                    name = '_' + value.name
                rval['term_' + str(i) + name] = value

        return rval
开发者ID:nitbix,项目名称:pylearn2,代码行数:26,代码来源:cost.py


示例5: register_names_to_del

    def register_names_to_del(self, names):
        """
        Register names of fields that should not be pickled.

        Parameters
        ----------
        names : iterable
            A collection of strings indicating names of fields on ts
            object that should not be pickled.

        Notes
        -----
        All names registered will be deleted from the dictionary returned
        by the model's `__getstate__` method (unless a particular model
        overrides this method).
        """
        if isinstance(names, six.string_types):
            names = [names]
        try:
            assert all(isinstance(n, six.string_types) for n in iter(names))
        except (TypeError, AssertionError):
            reraise_as(ValueError('Invalid names argument'))
        # Quick check in case __init__ was never called, e.g. by a derived
        # class.
        if not hasattr(self, 'names_to_del'):
            self.names_to_del = set()
        self.names_to_del = self.names_to_del.union(names)
开发者ID:julius506,项目名称:pylearn2,代码行数:27,代码来源:model.py


示例6: get_gradients

    def get_gradients(self, model, data, ** kwargs):
        """
        Provides the gradients of the cost function with respect to the model
        parameters.

        These are not necessarily those obtained by theano.tensor.grad
        --you may wish to use approximate or even intentionally incorrect
        gradients in some cases.

        Parameters
        ----------
        model : a pylearn2 Model instance
        data : a batch in cost.get_data_specs() form
        kwargs : dict
            Optional extra arguments, not used by the base class.

        Returns
        -------
        gradients : OrderedDict
            a dictionary mapping from the model's parameters
            to their gradients
            The default implementation is to compute the gradients
            using T.grad applied to the value returned by expr.
            However, subclasses may return other values for the gradient.
            For example, an intractable cost may return a sampling-based
            approximation to its gradient.
        updates : OrderedDict
            a dictionary mapping shared variables to updates that must
            be applied to them each time these gradients are computed.
            This is to facilitate computation of sampling-based approximate
            gradients.
            The parameters should never appear in the updates dictionary.
            This would imply that computing their gradient changes
            their value, thus making the gradient value outdated.
        """

        try:
            cost,mask = self.expr(model=model, data=data, **kwargs)
        except TypeError:
            # If anybody knows how to add type(self) to the exception message
            # but still preserve the stack trace, please do so
            # The current code does neither
            message = "Error while calling " + str(type(self)) + ".expr"
            reraise_as(TypeError(message))

        if cost is None:
            raise NotImplementedError(str(type(self)) +
                                      " represents an intractable cost and "
                                      "does not provide a gradient "
                                      "approximation scheme.")

        params = list(model.get_params())

        grads = T.grad(cost, params, disconnected_inputs='ignore')

        gradients = OrderedDict(izip(params, grads))

        updates = OrderedDict()

        return gradients, updates
开发者ID:nitbix,项目名称:pylearn2,代码行数:60,代码来源:cost.py


示例7: fn

 def fn(batch, dspace=dspace, sp=sp):
     try:
           return dspace.np_format_as(batch, sp)
     except ValueError as e:
         msg = str(e) + '\nMake sure that the model and '\
                        'dataset have been initialized with '\
                        'correct values.'
         reraise_as(ValueError(msg))
开发者ID:capybaralet,项目名称:pylearn2,代码行数:8,代码来源:iteration.py


示例8: wrapped_layer_cost

 def wrapped_layer_cost(layer, coef):
     try:
         return layer.get_weight_decay(coeff)
     except NotImplementedError:
         if coef==0.:
             return 0.
         else:
             reraise_as(NotImplementedError(str(type(layer)) +
                        " does not implement get_weight_decay."))
开发者ID:AlexArgus,项目名称:pylearn2,代码行数:9,代码来源:__init__.py


示例9: next

    def next(self):
        """
        .. todo::

            WRITEME
        """
        indx = self.subset_iterator.next()
        try:
            mini_batch = self.X[indx]
        except IndexError, e:
            reraise_as(ValueError("Index out of range"+str(e)))
开发者ID:AlexArgus,项目名称:pylearn2,代码行数:11,代码来源:sparse_dataset.py


示例10: resolve

def resolve(d):
    """ given a dictionary d, returns the object described by the dictionary """

    tag = get_tag(d)

    try:
        resolver = resolvers[tag]
    except KeyError:
        reraise_as(TypeError('config does not know of any object type "'+tag+'"'))

    return resolver(d)
开发者ID:123fengye741,项目名称:pylearn2,代码行数:11,代码来源:old_config.py


示例11: _validate_shape

 def _validate_shape(shape, param_name):
     try:
         shape = tuple(shape)
         [int(val) for val in shape]
     except (ValueError, TypeError):
         try:
             shape = (int(shape),)
         except TypeError:
             reraise_as(TypeError("%s must be int or int tuple"
                                  % param_name))
     return shape
开发者ID:123fengye741,项目名称:pylearn2,代码行数:11,代码来源:pooling.py


示例12: load

def load(filepath, rescale_image=True, dtype='float64'):
    """
    .. todo::

        WRITEME
    """
    assert type(filepath) == str

    if rescale_image == False and dtype == 'uint8':
        ensure_Image()
        rval = np.asarray(Image.open(filepath))
        # print 'image.load: ' + str((rval.min(), rval.max()))
        assert rval.dtype == 'uint8'
        return rval

    s = 1.0
    if rescale_image:
        s = 255.
    try:
        ensure_Image()
        rval = Image.open(filepath)
    except Exception:
        reraise_as(Exception("Could not open " + filepath))

    numpy_rval = np.array(rval)

    if numpy_rval.ndim not in [2,3]:
        logger.error(dir(rval))
        logger.error(rval)
        logger.error(rval.size)
        rval.show()
        raise AssertionError("Tried to load an image, got an array with " +
                str(numpy_rval.ndim)+" dimensions. Expected 2 or 3."
                "This may indicate a mildly corrupted image file. Try "
                "converting it to a different image format with a different "
                "editor like gimp or imagemagic. Sometimes these programs are "
                "more robust to minor corruption than PIL and will emit a "
                "correctly formatted image in the new format."
                )
    rval = numpy_rval

    rval = np.cast[dtype](rval) / s

    if rval.ndim == 2:
        rval = rval.reshape(rval.shape[0], rval.shape[1], 1)

    if rval.ndim != 3:
        raise AssertionError("Something went wrong opening " +
                             filepath + '. Resulting shape is ' +
                             str(rval.shape) +
                             " (it's meant to have 3 dimensions by now)")

    return rval
开发者ID:mqyqlx,项目名称:pylearn2,代码行数:53,代码来源:image.py


示例13: on_monitor

    def on_monitor(self, model, dataset, algorithm):
        """
        Adjusts the learning rate based on the contents of model.monitor

        Parameters
        ----------
        model : a Model instance
        dataset : Dataset
        algorithm : WRITEME
        """
        model = algorithm.model
        lr = algorithm.learning_rate
        current_learning_rate = lr.get_value()
        assert hasattr(model, 'monitor'), ("no monitor associated with "
                                           + str(model))
        monitor = model.monitor
        monitor_channel_specified = True

        try:
            v = monitor.channels[self.channel_name].val_record
        except KeyError:
            err_input = ''
            err_input = 'The channel_name \'' + str(
                self.channel_name) + '\' is not valid.'
            err_message = 'There is no monitoring channel named \'' + \
                str(self.channel_name) + '\'. You probably need to ' + \
                'specify a valid monitoring channel by using either ' + \
                'dataset_name or channel_name in the ' + \
                'MonitorBasedLRDecay constructor. ' + err_input
            reraise_as(ValueError(err_message))

        if len(v) == 1:
            #only the initial monitoring has happened
            #no learning has happened, so we can't adjust the learning rate yet
            #just do nothing
            self._min_v = v[0]
            return

        rval = current_learning_rate
        log.info("monitoring channel is {0}".format(self.channel_name))

        if v[-1] < self._min_v:
            self._min_v = v[-1]
            self._count = 0
        else:
            self._count += 1

        if self._count > self.nb_epoch:
            self._count = 0
            rval = self.shrink_lr * rval

        rval = max(self.min_lr, rval)
        lr.set_value(np.cast[lr.dtype](rval))
开发者ID:ballasn,项目名称:facedet,代码行数:53,代码来源:sgd.py


示例14: next

    def next(self):
        """
        .. todo::

            WRITEME
        """
        indx = self.subset_iterator.next()
        try:
            mini_batch = self.X[indx]
        except IndexError as e:
            reraise_as(ValueError("Index out of range" + str(e)))
            # the ind of minibatch goes beyond the boundary
        return mini_batch
开发者ID:123fengye741,项目名称:pylearn2,代码行数:13,代码来源:sparse_dataset.py


示例15: test_multi_constructor_obj

def test_multi_constructor_obj():
    """
    Tests whether multi_constructor_obj throws an exception when
    the keys in mapping are None.
    """
    try:
        load("a: !obj:decimal.Decimal { 1 }")
    except TypeError as e:
        assert str(e) == "Received non string object (1) as key in mapping."
        pass
    except Exception as e:
        error_msg = "Got the unexpected error: %s" % (e)
        reraise_as(ValueError(error_msg))
开发者ID:MarCnu,项目名称:pylearn2,代码行数:13,代码来源:test_yaml_parse.py


示例16: read_bin_lush_matrix

def read_bin_lush_matrix(filepath):
    """
    Reads a binary matrix saved by the lush library.

    Parameters
    ----------
    filepath : str
        The path to the file.

    Returns
    -------
    matrix : ndarray
        A NumPy version of the stored matrix.
    """
    f = open(filepath, 'rb')
    try:
        magic = read_int(f)
    except ValueError:
        reraise_as("Couldn't read magic number")
    ndim = read_int(f)

    if ndim == 0:
        shape = ()
    else:
        shape = read_int(f, max(3, ndim))

    total_elems = 1
    for dim in shape:
        total_elems *= dim

    try:
        dtype = lush_magic[magic]
    except KeyError:
        reraise_as(ValueError('Unrecognized lush magic number ' + str(magic)))

    rval = np.fromfile(file=f, dtype=dtype, count=total_elems)

    excess = f.read(-1)

    if excess:
        raise ValueError(str(len(excess)) +
                         ' extra bytes found at end of file.'
                         ' This indicates  mismatch between header '
                         'and content')

    rval = rval.reshape(*shape)

    f.close()

    return rval
开发者ID:123fengye741,项目名称:pylearn2,代码行数:50,代码来源:serial.py


示例17: get

    def get(self, sources, indexes):
        """
        Retrieves the requested elements from the dataset.

        Parameter
        ---------
        sources : tuple
            A tuple of source identifiers
        indexes : slice or list
            A slice or a list of indexes

        Return
        ------
        rval : tuple
            A tuple of batches, one for each source
        """
        assert (
            isinstance(sources, (tuple, list)) and len(sources) > 0
        ), "sources should be an instance of tuple and not empty"
        assert all([isinstance(el, string_types) for el in sources]), "sources elements should be strings"
        assert isinstance(
            indexes, (tuple, list, slice, py_integer_types)
        ), "indexes should be either an int, a slice or a tuple/list of ints"
        if isinstance(indexes, (tuple, list)):
            assert len(indexes) > 0 and all(
                [isinstance(i, py_integer_types) for i in indexes]
            ), "indexes elements should be ints"

        rval = []
        for s in sources:
            try:
                sdata = self.data[s]
            except ValueError as e:
                reraise_as(ValueError("The requested source %s is not part of the dataset" % sources[s], *e.args))
            if isinstance(indexes, (slice, py_integer_types)) or len(indexes) == 1:
                rval.append(sdata[indexes])
            else:
                warnings.warn(
                    "Accessing non sequential elements of an "
                    "HDF5 file will be at best VERY slow. Avoid "
                    "using iteration schemes that access "
                    "random/shuffled data with hdf5 datasets!!"
                )
                val = []
                [val.append(sdata[idx]) for idx in indexes]
                rval.append(val)
        return tuple(rval)
开发者ID:CandyPythonFlow,项目名称:pylearn2,代码行数:47,代码来源:hdf5.py


示例18: resolve

def resolve(d):
    """
    .. todo::

        WRITEME
    """
    tag = pylearn2.config.get_tag(d)

    if tag != 'dataset':
        raise TypeError('pylearn2.datasets.config asked to resolve a config dictionary with tag "'+tag+'"')

    t = pylearn2.config.get_str(d,'typename')

    try:
        resolver = resolvers[t]
    except KeyError:
        reraise_as(TypeError('pylearn2.datasets does not know of a dataset type "'+t+'"'))

    return resolver(d)
开发者ID:AlexArgus,项目名称:pylearn2,代码行数:19,代码来源:config.py


示例19: __init__

 def __init__(self, max_labels, dtype=None):
     """
     Initializes the formatter given the number of max labels.
     """
     try:
         np.empty(max_labels)
     except (ValueError, TypeError):
         reraise_as(ValueError("%s got bad max_labels argument '%s'" %
                               (self.__class__.__name__, str(max_labels))))
     self._max_labels = max_labels
     if dtype is None:
         self._dtype = config.floatX
     else:
         try:
             np.dtype(dtype)
         except TypeError:
             reraise_as(TypeError("%s got bad dtype identifier %s" %
                                  (self.__class__.__name__, str(dtype))))
         self._dtype = dtype
开发者ID:123fengye741,项目名称:pylearn2,代码行数:19,代码来源:target_format.py


示例20: try_to_import

def try_to_import(tag_suffix):
    """
    .. todo::

        WRITEME
    """
    components = tag_suffix.split('.')
    modulename = '.'.join(components[:-1])
    try:
        exec('import %s' % modulename)
    except ImportError, e:
        # We know it's an ImportError, but is it an ImportError related to
        # this path,
        # or did the module we're importing have an unrelated ImportError?
        # and yes, this test can still have false positives, feel free to
        # improve it
        pieces = modulename.split('.')
        str_e = str(e)
        found = True in [piece.find(str(e)) != -1 for piece in pieces]

        if found:
            # The yaml file is probably to blame.
            # Report the problem with the full module path from the YAML
            # file
            reraise_as(ImportError("Could not import %s; ImportError was %s" %
                                   (modulename, str_e)))
        else:

            pcomponents = components[:-1]
            assert len(pcomponents) >= 1
            j = 1
            while j <= len(pcomponents):
                modulename = '.'.join(pcomponents[:j])
                try:
                    exec('import %s' % modulename)
                except Exception:
                    base_msg = 'Could not import %s' % modulename
                    if j > 1:
                        modulename = '.'.join(pcomponents[:j - 1])
                        base_msg += ' but could import %s' % modulename
                    reraise_as(ImportError(base_msg + '. Original exception: '
                                           + str(e)))
                j += 1
开发者ID:AlexArgus,项目名称:pylearn2,代码行数:43,代码来源:yaml_parse.py



注:本文中的pylearn2.utils.exc.reraise_as函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python iteration.is_stochastic函数代码示例发布时间:2022-05-25
下一篇:
Python data_specs.DataSpecsMapping类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap