當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。