Python numpy.array_str() Examples

The following are 30 code examples of numpy.array_str(). 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 numpy , or try the search function .
Example #1
Source File: query_request.py    From ibeis with Apache License 2.0 6 votes vote down vote up
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 ---- 
Example #2
Source File: mnist_inference.py    From uai-sdk with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: arrayprint.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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, ' ', "") 
Example #4
Source File: dataset.py    From ektelo with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: classDefinitions.py    From pyMHT with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #6
Source File: model_based_rl.py    From me-trpo with MIT License 6 votes vote down vote up
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)) 
Example #7
Source File: formatting.py    From cupy with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: mnist_inference.py    From uai-sdk with Apache License 2.0 6 votes vote down vote up
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 
Example #9
Source File: variable.py    From chainer with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: local_frame.py    From pytim with GNU General Public License v3.0 6 votes vote down vote up
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.]]


        """
# 
Example #11
Source File: arrayprint.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
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, ' ', "") 
Example #12
Source File: arrayprint.py    From recruit with Apache License 2.0 6 votes vote down vote up
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, ' ', "") 
Example #13
Source File: trajectory.py    From FCGF with MIT License 5 votes vote down vote up
def __str__(self):
    return 'metadata : ' + ' '.join(map(str, self.metadata)) + '\n' + \
        "pose : " + "\n" + np.array_str(self.pose) 
Example #14
Source File: imdb.py    From mx-maskrcnn with Apache License 2.0 5 votes vote down vote up
def append_flipped_images(self, roidb):
        """
        append flipped images to an roidb
        flip boxes coordinates, images will be actually flipped when loading into network
        :param roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
        :return: roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
        """
        print 'append flipped images to roidb'
        assert self.num_images == len(roidb)
        for i in range(self.num_images):
            roi_rec = roidb[i]
            boxes = roi_rec['boxes'].copy()
            oldx1 = boxes[:, 0].copy()
            oldx2 = boxes[:, 2].copy()
            boxes[:, 0] = roi_rec['width'] - oldx2 - 1
            boxes[:, 2] = roi_rec['width'] - oldx1 - 1
            assert (boxes[:, 2] >= boxes[:, 0]).all(),\
                'img_name %s, width %d\n' % (roi_rec['image'], roi_rec['width']) + \
                np.array_str(roi_rec['boxes'], precision=3, suppress_small=True)
            entry = {'image': roi_rec['image'],
                     'height': roi_rec['height'],
                     'width': roi_rec['width'],
                     'boxes': boxes,
                     'gt_classes': roidb[i]['gt_classes'],
                     'gt_overlaps': roidb[i]['gt_overlaps'],
                     'max_classes': roidb[i]['max_classes'],
                     'max_overlaps': roidb[i]['max_overlaps'],
                     'flipped': True}
            roidb.append(entry)

        self.image_set_index *= 2
        return roidb 
Example #15
Source File: callback.py    From ST-MetaNet with MIT License 5 votes vote down vote up
def finish(self, metrics):
		output_str = ''
		if metrics is not None:
			for metric in metrics:
				result = metric.get_value()
				for k, v in result.items():
					v = np.array_str(v.asnumpy())
					output_str += '\t' + k + ': ' + v
		self.end = time.time()
		print('%s\tEpoch[%d]\tTime:%.2fs%s' % (self.title, self.epoch, self.end-self.start, output_str))
		self.reset() 
Example #16
Source File: callback.py    From ST-MetaNet with MIT License 5 votes vote down vote up
def log_metrics(self, nbatch, metrics):
		if nbatch % self.frequent == 0:
			output_str = ''
			if metrics is not None:
				for metric in metrics:
					result = metric.get_value()
					for k, v in result.items():
						v = np.array_str(v.asnumpy())
						output_str += '\t' + k + ': ' + v

			time_spent = time.time() - self.tic
			self.tic = time.time()
			speed = self.frequent / time_spent
			print('%s\tEpoch[%d]\tBatch[%d]\tTime spent:%.2fs\tSpeed: %.2fbatch/s%s' %
					(self.title, self.epoch, nbatch, time_spent, speed, output_str)) 
Example #17
Source File: test_remainder.py    From discrete_sieve with Apache License 2.0 5 votes vote down vote up
def test_invertibility():
    xs = np.random.randint(0, 5, 100)
    ys = xs / 2 + np.random.randint(0, 2, 100)
    g = re.Remainder(xs, ys, k_max=8)
    zs = g.transform(xs, ys)
    print 'mi, h', g.mi, g.h
    print zip(xs, ys, zs)
    print np.array_str(g.pz_xy, precision=2, suppress_small=True)
    predict_xs = g.predict(ys, zs)
    print zip(predict_xs, xs)
    assert np.all(xs == predict_xs), predict_xs
    assert g.h < 0.01, "%0.5f" % g.h
    assert g.mi < 0.1, "%0.5f" % g.mi 
Example #18
Source File: numeric.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
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 array2string(a, max_line_width, precision, suppress_small, ' ', "", str) 
Example #19
Source File: forecast.py    From anticipy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_df_fit_model(source, model, weights, actuals_x_range, freq,
                      is_fit, cost, aic_c, params, status):
    # Generate a metadata dataframe for the output of fit_model()
    if params is None:
        params = np.array([])
    df_result = (
        pd.DataFrame(
            columns=[
                'source',
                'model',
                'weights',
                'actuals_x_range',
                'freq',
                'is_fit',
                'cost',
                'aic_c',
                'params_str',
                'status',
                'source_long',
                'params'],
            data=[
                [
                    source,
                    model,
                    weights,
                    actuals_x_range,
                    freq,
                    is_fit,
                    cost,
                    aic_c,
                    np.array_str(
                        params,
                        precision=1),
                    status,
                    '{}:{}:{}:{}'.format(
                        source,
                        weights,
                        freq,
                        actuals_x_range),
                    params]]))
    return df_result 
Example #20
Source File: mnist_inference_json.py    From uai-sdk with Apache License 2.0 5 votes vote down vote up
def execute(self, data, batch_size):
    sess = self.output['sess']
    x = self.output['x']
    y_ = self.output['y_']

    ids = []
    imgs = []
    for i in range(batch_size):
      json_input = json.load(data[i])
      data_id = json_input['appid']
      img_data = json_input['img'].decode('base64')

      im = Image.open(StringIO.StringIO(img_data)).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)
      ids.append(data_id)

    imgs = np.array(imgs)
    print(imgs.shape)
    predict = sess.run(y_, feed_dict={x: imgs})
    ret = []
    for i in range(batch_size):
      ret_val = np.array_str(np.argmax(predict[i]))
      ret_item = json.dumps({ids[i]: ret_val})
      ret.append(ret_item)
    return ret 
Example #21
Source File: helpers.py    From iffse with MIT License 5 votes vote down vote up
def np_to_string(n):
    """
    Converts a one dimensional numpy array
    into a string format to be stored in db
    """

    # Squeeze out dims
    n = np.squeeze(n)

    return np.array_str(n)[1:-1] 
Example #22
Source File: test_regression.py    From pySINDy with MIT License 5 votes vote down vote up
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 
Example #23
Source File: test_formatting.py    From cupy with MIT License 5 votes vote down vote up
def test_array_str(self):
        a = testing.shaped_arange((2, 3, 4), cupy)
        b = testing.shaped_arange((2, 3, 4), numpy)
        self.assertEqual(cupy.array_str(a), numpy.array_str(b)) 
Example #24
Source File: distanceratioexperiment.py    From aurum-datadiscovery with MIT License 5 votes vote down vote up
def __vector_to_string(self, vector):
        """ Returns string representation of vector. """
        return numpy.array_str(vector) 
Example #25
Source File: recallprecisionexperiment.py    From aurum-datadiscovery with MIT License 5 votes vote down vote up
def __vector_to_string(self, vector):
        """ Returns string representation of vector. """
        return numpy.array_str(numpy.round(unitvec(vector), decimals=3)) 
Example #26
Source File: quaternion.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return np.array_str(self.data) 
Example #27
Source File: quaternion.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return np.array_str(self.data) 
Example #28
Source File: two_qubit_decompose.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        # FIXME: this is worth making prettier since it's very useful for debugging
        return ("{}\n{}\nUd({}, {}, {})\n{}\n{}\n".format(
            np.array_str(self.K1l),
            np.array_str(self.K1r),
            self.a, self.b, self.c,
            np.array_str(self.K2l),
            np.array_str(self.K2r))) 
Example #29
Source File: iqp.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def __init__(self, interactions: Union[List, np.array]) -> None:
        """Create IQP circuit.

        Args:
            interactions: input n-by-n symmetric matrix.

        Raises:
            CircuitError: if the inputs is not as symmetric matrix.
        """
        num_qubits = len(interactions)
        interactions = np.array(interactions)
        if not np.allclose(interactions, interactions.transpose()):
            raise CircuitError("The interactions matrix is not symmetric")

        a_str = np.array_str(interactions)
        a_str.replace('\n', ';')
        name = "iqp:" + a_str.replace('\n', ';')

        inner = QuantumCircuit(num_qubits, name=name)
        super().__init__(num_qubits, name=name)

        inner.h(range(num_qubits))
        for i in range(num_qubits):
            for j in range(i+1, num_qubits):
                if interactions[i][j] % 4 != 0:
                    inner.cu1(interactions[i][j] * np.pi / 2, i, j)

        for i in range(num_qubits):
            if interactions[i][i] % 8 != 0:
                inner.u1(interactions[i][i] * np.pi / 8, i)

        inner.h(range(num_qubits))
        all_qubits = self.qubits
        self.append(inner, all_qubits) 
Example #30
Source File: test_regression.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
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