python类Sized()的实例源码

_typecheck.py 文件源码 项目:DeepLearning_VirtualReality_BigData_Project 作者: rashmitripathi 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __instancecheck__(self, instance):
    return (isinstance(instance, collections.Iterable)
            and isinstance(instance, collections.Sized)
            and isinstance(instance, collections.Container)
            and all(isinstance(x, self._type) for x in instance))
lazyarray.py 文件源码 项目:lazyarray 作者: NeuralEnsemble 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, value, shape=None, dtype=None):
        """
        Create a new lazy array.

        `value` : may be an int, long, float, bool, NumPy array, iterator,
                  generator or a function, `f(i)` or `f(i,j)`, depending on the
                  dimensions of the array.

        `f(i,j)` should return a single number when `i` and `j` are integers,
        and a 1D array when either `i` or `j` or both is a NumPy array (in the
        latter case the two arrays must have equal lengths).
        """

        self.dtype = dtype
        self.operations = []
        if isinstance(value, basestring):
            raise TypeError("An larray cannot be created from a string")
        elif isinstance(value, larray):
            if shape is not None and value.shape is not None:
                assert shape == value.shape
            self._shape = shape or value.shape
            self.base_value = value.base_value
            self.dtype = dtype or value.dtype
            self.operations = value.operations  # should deepcopy?

        elif isinstance(value, collections.Sized):  # False for numbers, generators, functions, iterators
            if have_scipy and sparse.issparse(value):  # For sparse matrices
                self.dtype = dtype or value.dtype                           
            elif not isinstance(value, numpy.ndarray):  
                value = numpy.array(value, dtype=dtype)
            elif dtype is not None:
               assert numpy.can_cast(value.dtype, dtype, casting='safe')  # or could convert value to the provided dtype
            if shape and value.shape != shape:
                raise ValueError("Array has shape %s, value has shape %s" % (shape, value.shape))
            self._shape = value.shape
            self.base_value = value

        else:
            assert numpy.isreal(value)  # also True for callables, generators, iterators
            self._shape = shape
            if dtype is None or isinstance(value, dtype):
                self.base_value = value
            else:
                try:
                    self.base_value = dtype(value)
                except TypeError:
                    self.base_value = value
lazyarray.py 文件源码 项目:lazyarray 作者: NeuralEnsemble 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def check_bounds(self, addr):
        """
        Check whether the given address is within the array bounds.
        """
        def is_boolean_array(arr):
            return hasattr(arr, 'dtype') and arr.dtype == bool

        def check_axis(x, size):
            if isinstance(x, (int, long, numpy.integer)):
                lower = upper = x
            elif isinstance(x, slice):
                lower = x.start or 0
                upper = min(x.stop or size - 1, size - 1)  # slices are allowed to go past the bounds
            elif isinstance(x, collections.Sized):
                if is_boolean_array(x):
                    lower = 0
                    upper = x.size - 1
                else:
                    if len(x) == 0:
                        raise ValueError("Empty address component (address was %s)" % str(addr))
                    if hasattr(x, "min"):
                        lower = x.min()
                    else:
                        lower = min(x)
                    if hasattr(x, "max"):
                        upper = x.max()
                    else:
                        upper = max(x)
            else:
                raise TypeError("Invalid array address: %s (element of type %s)" % (str(addr), type(x)))
            if (lower < -size) or (upper >= size):
                raise IndexError("Index out of bounds")
        full_addr = self._full_address(addr)
        if isinstance(addr, numpy.ndarray) and addr.dtype == bool:
            if len(addr.shape) > len(self._shape):
                raise IndexError("Too many indices for array")
            for xmax, size in zip(addr.shape, self._shape):
                upper = xmax - 1
                if upper >= size:
                    raise IndexError("Index out of bounds")
        else:
            for i, size in zip(full_addr, self._shape):
                check_axis(i, size)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, iterable=None):
        r"""Create a new, empty Multiset object.

        And if given, initialize with elements from input iterable.
        Or, initialize from a mapping of elements to their multiplicity.

        Example:

        >>> ms = Multiset()                 # a new, empty multiset
        >>> ms = Multiset('abc')            # a new multiset from an iterable
        >>> ms = Multiset({'a': 4, 'b': 2}) # a new multiset from a mapping

        Args:
            iterable:
                An optional iterable of elements or mapping of elements to multiplicity to
                initialize the multiset from.
        """
        if isinstance(iterable, BaseMultiset):
            self._elements = iterable._elements.copy()
            self._total = iterable._total
        else:
            self._elements = _elements = defaultdict(int)
            _total = 0
            if iterable is not None:
                if isinstance(iterable, _sequence_types):
                    for element in iterable:
                        _elements[element] += 1
                    _total = len(iterable)
                elif isinstance(iterable, dict):
                    for element, multiplicity in iterable.items():
                        if multiplicity > 0:
                            _elements[element] = multiplicity
                            _total += multiplicity
                elif isinstance(iterable, _iter_types):
                    for element in iterable:
                        _elements[element] += 1
                        _total += 1
                elif isinstance(iterable, Mapping):
                    for element, multiplicity in iterable.items():
                        if multiplicity > 0:
                            _elements[element] = multiplicity
                            _total += multiplicity
                elif isinstance(iterable, Sized):
                    for element in iterable:
                        _elements[element] += 1
                    _total = len(iterable)
                else:
                    for element in iterable:
                        _elements[element] += 1
                        _total += 1
            self._total = _total
modifiedGridSearchCV.py 文件源码 项目:CerebralCortex-2.0-legacy 作者: MD2Korg 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def fit(self, X, y):
        """Actual fitting,  performing the search over parameters."""

        parameter_iterable = ParameterGrid(self.param_grid)

        estimator = self.estimator
        cv = self.cv

        n_samples = _num_samples(X)
        X, y = indexable(X, y)

        if y is not None:
            if len(y) != n_samples:
                raise ValueError('Target variable (y) has a different number '
                                 'of samples (%i) than data (X: %i samples)'
                                 % (len(y), n_samples))
        cv = check_cv(cv, X, y, classifier=is_classifier(estimator))

        if self.verbose > 0:
            if isinstance(parameter_iterable, Sized):
                n_candidates = len(parameter_iterable)
                print("Fitting {0} folds for each of {1} candidates, totalling"
                      " {2} fits".format(len(cv), n_candidates,
                                         n_candidates * len(cv)))

        base_estimator = clone(self.estimator)

        pre_dispatch = self.pre_dispatch

        out = Parallel(
            n_jobs=self.n_jobs, verbose=self.verbose,
            pre_dispatch=pre_dispatch
        )(delayed(cv_fit_and_score)(clone(base_estimator), X, y, self.scoring,
                                      parameters, cv=cv)
            for parameters in parameter_iterable)

        best = sorted(out, key=lambda x: x[0])[-1]
        self.best_params_ = best[1]
        self.best_score_ = best[0]

        if self.refit:
            # fit the best estimator using the entire dataset
            # clone first to work around broken estimators
            best_estimator = clone(base_estimator).set_params(
                **best[1])
            if y is not None:
                best_estimator.fit(X, y, **self.fit_params)
            else:
                best_estimator.fit(X, **self.fit_params)
            self.best_estimator_ = best_estimator

        return self
modifiedRandomizedSearchCV.py 文件源码 项目:CerebralCortex-2.0-legacy 作者: MD2Korg 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def fit(self, X, y):
        """Actual fitting,  performing the search over parameters."""

        parameter_iterable = ParameterSampler(self.param_distributions,
                                              self.n_iter,
                                              random_state=self.random_state)
        estimator = self.estimator
        cv = self.cv

        n_samples = _num_samples(X)
        X, y = indexable(X, y)

        if y is not None:
            if len(y) != n_samples:
                raise ValueError('Target variable (y) has a different number '
                                 'of samples (%i) than data (X: %i samples)'
                                 % (len(y), n_samples))
        cv = check_cv(cv, X, y, classifier=is_classifier(estimator))

        if self.verbose > 0:
            if isinstance(parameter_iterable, Sized):
                n_candidates = len(parameter_iterable)
                print("Fitting {0} folds for each of {1} candidates, totalling"
                      " {2} fits".format(len(cv), n_candidates,
                                         n_candidates * len(cv)))

        base_estimator = clone(self.estimator)

        pre_dispatch = self.pre_dispatch

        out = Parallel(
            n_jobs=self.n_jobs, verbose=self.verbose,
            pre_dispatch=pre_dispatch
        )(
            delayed(cv_fit_and_score)(clone(base_estimator), X, y, self.scoring,
                                      parameters, cv=cv)
            for parameters in parameter_iterable)

        best = sorted(out, reverse=True)[0]
        self.best_params_ = best[1]
        self.best_score_ = best[0]

        if self.refit:
            # fit the best estimator using the entire dataset
            # clone first to work around broken estimators
            best_estimator = clone(base_estimator).set_params(
                **best[1])
            if y is not None:
                best_estimator.fit(X, y, **self.fit_params)
            else:
                best_estimator.fit(X, **self.fit_params)
            self.best_estimator_ = best_estimator

        return self
transforms_nd.py 文件源码 项目:pyomo 作者: Pyomo 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __call__(self, x):
        """
        Evaluates the piecewise linear function using
        interpolation. This method supports vectorized
        function calls as the interpolation process can be
        expensive for high dimensional data.

        For the case when a single point is provided, the
        argument x should be a (D,) shaped numpy array or
        list, where D is the dimension of points in the
        triangulation.

        For the vectorized case, the argument x should be
        a (n,D)-shaped numpy array.
        """
        assert isinstance(x, collections.Sized)
        if isinstance(x, pyomo.core.kernel.component_piecewise.\
                      util.numpy.ndarray):
            if x.shape != self._tri.points.shape[1:]:
                multi = True
                assert x.shape[1:] == self._tri.points[0].shape, \
                    "%s[1] != %s" % (x.shape, self._tri.points[0].shape)
            else:
                multi = False
        else:
            multi = False
        _, ndim = self._tri.points.shape
        i = self._tri.find_simplex(x)
        if multi:
            Tinv = self._tri.transform[i,:ndim]
            r = self._tri.transform[i,ndim]
            b = pyomo.core.kernel.component_piecewise.util.\
                numpy.einsum('ijk,ik->ij', Tinv, x-r)
            b = pyomo.core.kernel.component_piecewise.util.\
                numpy.c_[b, 1 - b.sum(axis=1)]
            s = self._tri.simplices[i]
            return (b*self._values[s]).sum(axis=1)
        else:
            b = self._tri.transform[i,:ndim,:ndim].dot(
                x - self._tri.transform[i,ndim,:])
            s = self._tri.simplices[i]
            val = b.dot(self._values[s[:ndim]])
            val += (1-b.sum())*self._values[s[ndim]]
            return val


问题


面经


文章

微信
公众号

扫码关注公众号