当前位置: 首页>>代码示例>>Python>>正文


Python numpy.array_str方法代码示例

本文整理汇总了Python中numpy.array_str方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.array_str方法的具体用法?Python numpy.array_str怎么用?Python numpy.array_str使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


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

示例1: _array_str_implementation

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def _array_str_implementation(
        a, max_line_width=None, precision=None, suppress_small=None,
        array2string=array2string):
    """Internal version of array_str() that allows overriding array2string."""
    if (_format_options['legacy'] == '1.13' and
            a.shape == () and not a.dtype.names):
        return str(a.item())

    # the str of 0d arrays is a special case: It should appear like a scalar,
    # so floats are not truncated by `precision`, and strings are not wrapped
    # in quotes. So we return the str of the scalar value.
    if a.shape == ():
        # obtain a scalar and call str on it, avoiding problems for subclasses
        # for which indexing with () returns a 0d instead of a scalar by using
        # ndarray's getindex. Also guard against recursive 0d object arrays.
        return _guarded_str(np.ndarray.__getitem__(a, ()))

    return array2string(a, max_line_width, precision, suppress_small, ' ', "") 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:20,代码来源:arrayprint.py

示例2: _

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def _():
        """ additional tests

        here we generate a paraboloid (x^2+y^2) and a hyperbolic paraboloid
        (x^2-y^2) to check that the curvature code gives the right answers for
        the Gaussian (4, -4) and mean (2, 0) curvatures

        >>> import pytim
        >>> x,y=np.mgrid[-5:5,-5:5.]/2.
        >>> p = np.asarray(list(zip(x.flatten(),y.flatten())))
        >>> z1 = p[:,0]**2+p[:,1]**2
        >>> z2 = p[:,0]**2-p[:,1]**2
        >>>
        >>> for z in [z1, z2]:
        ...     pp = np.asarray(list(zip(x.flatten()+5,y.flatten()+5,z)))
        ...     curv = pytim.observables.Curvature(cutoff=1.,warning=False).compute(pp)
        ...     val =  (curv[np.logical_and(p[:,0]==0,p[:,1]==0)])
        ...     # add and subtract 1e3 to be sure to have -0 -> 0
        ...     print(np.array_str((val+1e3)-1e3, precision=2, suppress_small=True))
        [[4. 2.]]
        [[-4.  0.]]


        """
# 
开发者ID:Marcello-Sega,项目名称:pytim,代码行数:27,代码来源:local_frame.py

示例3: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def __init__(self, hist, reduce_to_domain_shape=None, dist=None):
        """
            Any instances with equal key() values should have equal hash() values
            domain_shape will be result of regular grid partition
        """
        if isinstance(reduce_to_domain_shape, int): # allow for integers in 1D, instead of shape tuples
            reduce_to_domain_shape = (reduce_to_domain_shape, )

        if dist is not None:
            self._dist_str = numpy.array_str(numpy.array(dist))
        else:
            self._dist_str = ''

        self._hist = hist
        self._reduce_to_domain_shape = reduce_to_domain_shape if hist.shape != reduce_to_domain_shape else None
        self._dist = dist
        self._payload = None

        self._compiled = False 
开发者ID:ektelo,项目名称:ektelo,代码行数:21,代码来源:dataset.py

示例4: set_external_qaid_mask

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def set_external_qaid_mask(qreq_, masked_qaid_list):
        r"""
        Args:
            qaid_list (list):

        CommandLine:
            python -m ibeis.algo.hots.query_request --test-set_external_qaid_mask

        Example:
            >>> # ENABLE_DOCTEST
            >>> from ibeis.algo.hots.query_request import *  # NOQA
            >>> import ibeis
            >>> ibs = ibeis.opendb(db='testdb1')
            >>> qaid_list = [1, 2, 3, 4, 5]
            >>> daid_list = [1, 2, 3, 4, 5]
            >>> qreq_ = ibs.new_query_request(qaid_list, daid_list)
            >>> masked_qaid_list = [2, 4, 5]
            >>> qreq_.set_external_qaid_mask(masked_qaid_list)
            >>> result = np.array_str(qreq_.qaids)
            >>> print(result)
            [1 3]
        """
        qreq_.set_internal_masked_qaids(masked_qaid_list)

    # --- Internal Annotation ID Masks ---- 
开发者ID:Erotemic,项目名称:ibeis,代码行数:27,代码来源:query_request.py

示例5: predictAisMeasurements

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def predictAisMeasurements(self, scanTime, aisMeasurements):
        import pymht.models.pv as model
        import pymht.utils.kalman as kalman
        assert len(aisMeasurements) > 0
        aisPredictions = AisMessageList(scanTime)
        scanTimeString = datetime.datetime.fromtimestamp(scanTime).strftime("%H:%M:%S.%f")
        for measurement in aisMeasurements:
            aisTimeString = datetime.datetime.fromtimestamp(measurement.time).strftime("%H:%M:%S.%f")
            log.debug("Predicting AIS (" + str(measurement.mmsi) + ") from " + aisTimeString + " to " + scanTimeString)
            dT = scanTime - measurement.time
            assert dT >= 0
            state = measurement.state
            A = model.Phi(dT)
            Q = model.Q(dT)
            x_bar, P_bar = kalman.predict(A, Q, np.array(state, ndmin=2),
                                          np.array(measurement.covariance, ndmin=3))
            aisPredictions.measurements.append(
                AIS_prediction(model.C_RADAR.dot(x_bar[0]),
                               model.C_RADAR.dot(P_bar[0]).dot(model.C_RADAR.T), measurement.mmsi))
            log.debug(np.array_str(state) + "=>" + np.array_str(x_bar[0]))
            aisPredictions.aisMessages.append(measurement)
        assert len(aisPredictions.measurements) == len(aisMeasurements)
        return aisPredictions 
开发者ID:erikliland,项目名称:pyMHT,代码行数:25,代码来源:classDefinitions.py

示例6: variable_str

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def variable_str(var):
    """Return the string representation of a variable.

    Args:
        var (~chainer.Variable): Input Variable.
    .. seealso:: numpy.array_str
    """
    arr = _cpu._to_cpu(var.array)

    if var.name:
        prefix = 'variable ' + var.name
    else:
        prefix = 'variable'

    if arr is None:
        lst = 'None'
    else:
        lst = numpy.array2string(arr, None, None, None, ' ', prefix + '(')

    return '%s(%s)' % (prefix, lst) 
开发者ID:chainer,项目名称:chainer,代码行数:22,代码来源:variable.py

示例7: array_str

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def array_str(arr, max_line_width=None, precision=None, suppress_small=None):
    """Returns the string representation of the content of an array.

    Args:
        arr (array_like): Input array. It should be able to feed to
            :func:`cupy.asnumpy`.
        max_line_width (int): The maximum number of line lengths.
        precision (int): Floating point precision. It uses the current printing
            precision of NumPy.
        suppress_small (bool): If ``True``, very small number are printed as
            zeros.

    .. seealso:: :func:`numpy.array_str`

    """
    return numpy.array_str(cupy.asnumpy(arr), max_line_width, precision,
                           suppress_small) 
开发者ID:cupy,项目名称:cupy,代码行数:19,代码来源:formatting.py

示例8: execute

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def execute(self, data, batch_size):
        BATCH = namedtuple('BATCH', ['data', 'label'])
        self.model.bind(data_shapes=[('data', (batch_size, 1, 28, 28))],
                        label_shapes=[('softmax_label', (batch_size, 10))],
                        for_training=False)
        self.model.set_params(self.arg_params, self.aux_params)

        ret = []
        for i in range(batch_size):
            im = Image.open(data[i]).resize((28, 28))
            im = np.array(im) / 255.0
            im = im.reshape(-1, 1, 28, 28)
            self.model.forward(BATCH([mx.nd.array(im)], None))
            predict_values = self.model.get_outputs()[0].asnumpy()

            val = predict_values[0]
            ret_val = np.array_str(np.argmax(val)) + '\n'
            ret.append(ret_val)
        return ret 
开发者ID:ucloud,项目名称:uai-sdk,代码行数:21,代码来源:mnist_inference.py

示例9: execute

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def execute(self, data, batch_size):
    sess = self.output['sess']
    x = self.output['x']
    y_ = self.output['y_']

    imgs = []
    for i in range(batch_size):
      im = Image.open(data[i]).resize((28, 28)).convert('L')
      im = np.array(im)
      im = im.reshape(784)
      im = im.astype(np.float32)
      im = np.multiply(im, 1.0 / 255.0)
      imgs.append(im)

    imgs = np.array(imgs)
    predict_values = sess.run(y_, feed_dict={x: imgs})
    print(predict_values)

    ret = []
    for val in predict_values:
      ret_val = np.array_str(np.argmax(val)) + '\n'
      ret.append(ret_val)
    return ret 
开发者ID:ucloud,项目名称:uai-sdk,代码行数:25,代码来源:mnist_inference.py

示例10: log_dictionary

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def log_dictionary(mode_order, validation_costs, min_validation_costs, logger, first_n=5):
    for mode in mode_order:
        if mode in validation_costs:
            costs = validation_costs[mode]
            if hasattr(costs, '__iter__'):
                assert 'estimated' in mode
                msg = np.array_str(costs[:first_n], max_line_width=50, precision=2)
                logger.info('\t%.5s_validation_cost:\t%s' %
                            (mode, msg))
                logger.info('\t\tavg=%.2f, increase_ratio=%.2f' % (
                    np.mean(costs),
                    np.mean(costs > min_validation_costs[mode])
                ))
                logger.info('\t\tmode=%.2f, std=%.2f, min=%.2f, max=%.2f' %
                            (np.median(costs),
                             np.std(costs),
                             np.min(costs),
                             np.max(costs)))
            else:
                logger.info('\t%.5s_validation_cost:\t%.3f' %
                            (mode, costs)) 
开发者ID:thanard,项目名称:me-trpo,代码行数:23,代码来源:model_based_rl.py

示例11: __str__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def __str__(self):
        return (("%s:\n"
                 " * Coefficients: %s\n"
                 " * Intercept = %.5f\n") %
                (self.__class__.__name__,
                 np.array_str(self.coef_, precision=4),
                 self.intercept_)) 
开发者ID:ceholden,项目名称:yatsm,代码行数:9,代码来源:robust_fit.py

示例12: array_str

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def array_str(a, max_line_width=None, precision=None, suppress_small=None):
    """
    Return a string representation of the data in an array.

    The data in the array is returned as a single string.  This function is
    similar to `array_repr`, the difference being that `array_repr` also
    returns information on the kind of array and its data type.

    Parameters
    ----------
    a : ndarray
        Input array.
    max_line_width : int, optional
        Inserts newlines if text is longer than `max_line_width`.  The
        default is, indirectly, 75.
    precision : int, optional
        Floating point precision.  Default is the current printing precision
        (usually 8), which can be altered using `set_printoptions`.
    suppress_small : bool, optional
        Represent numbers "very close" to zero as zero; default is False.
        Very close is defined by precision: if the precision is 8, e.g.,
        numbers smaller (in absolute value) than 5e-9 are represented as
        zero.

    See Also
    --------
    array2string, array_repr, set_printoptions

    Examples
    --------
    >>> np.array_str(np.arange(3))
    '[0 1 2]'

    """
    return _array_str_implementation(
        a, max_line_width, precision, suppress_small)


# needed if __array_function__ is disabled 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:41,代码来源:arrayprint.py

示例13: test_array_str_64bit

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def test_array_str_64bit(self):
        # Ticket #501
        s = np.array([1, np.nan], dtype=np.float64)
        with np.errstate(all='raise'):
            np.array_str(s)  # Should succeed 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:7,代码来源:test_regression.py

示例14: make_wordvectors

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def make_wordvectors():
    global lcode
    import gensim # In case you have difficulties installing gensim, you need to consider installing conda.
    import cPickle as pickle
     
    print "Making sentences as list..."
    sents = []
    with codecs.open('data/{}.txt'.format(lcode), 'r', 'utf-8') as fin:
        while 1:
            line = fin.readline()
            if not line: break
             
            words = line.split()
            sents.append(words)

    print "Making word vectors..."   
    min_count = get_min_count(sents)
    model = gensim.models.Word2Vec(sents, size=vector_size, min_count=min_count,
                                   negative=num_negative, 
                                   window=window_size)
    
    model.save('data/{}.bin'.format(lcode))
    
    # Save to file
    with codecs.open('data/{}.tsv'.format(lcode), 'w', 'utf-8') as fout:
        for i, word in enumerate(model.index2word):
            fout.write(u"{}\t{}\t{}\n".format(str(i), word.encode('utf8').decode('utf8'),
                                              np.array_str(model[word])
                                              )) 
开发者ID:Kyubyong,项目名称:wordvectors,代码行数:31,代码来源:make_wordvectors.py

示例15: test_array_str_64bit

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array_str [as 别名]
def test_array_str_64bit(self, level=rlevel):
        # Ticket #501
        s = np.array([1, np.nan], dtype=np.float64)
        with np.errstate(all='raise'):
            np.array_str(s)  # Should succeed 
开发者ID:abhisuri97,项目名称:auto-alt-text-lambda-api,代码行数:7,代码来源:test_regression.py


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