Python numpy.floating() Examples

The following are 30 code examples of numpy.floating(). 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: VizDataAdapter.py    From scattertext with Apache License 2.0 6 votes vote down vote up
def default(self, obj):
		if isinstance(obj, np.integer):
			return int(obj)
		elif isinstance(obj, np.floating):
			return float(obj)
		elif isinstance(obj, np.ndarray):
			return obj.tolist()
		elif isinstance(obj, WhitespaceNLP.Doc):
			return repr(obj)
		elif isinstance(obj, AsianNLP.Doc):
			return repr(obj)
		elif 'spacy' in sys.modules:
			import spacy
			if isinstance(obj, spacy.tokens.doc.Doc):
				return repr(obj)
		else:
			return super(MyEncoder, self).default(obj) 
Example #2
Source File: test_linalg.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example #3
Source File: sql.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _handle_date_column(col, utc=None, format=None):
    if isinstance(format, dict):
        return to_datetime(col, errors='ignore', **format)
    else:
        # Allow passing of formatting string for integers
        # GH17855
        if format is None and (issubclass(col.dtype.type, np.floating) or
                               issubclass(col.dtype.type, np.integer)):
            format = 's'
        if format in ['D', 'd', 'h', 'm', 's', 'ms', 'us', 'ns']:
            return to_datetime(col, errors='coerce', unit=format, utc=utc)
        elif is_datetime64tz_dtype(col):
            # coerce to UTC timezone
            # GH11216
            return to_datetime(col, utc=True)
        else:
            return to_datetime(col, errors='coerce', format=format, utc=utc) 
Example #4
Source File: test_linalg.py    From lambda-packs with MIT License 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example #5
Source File: array.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def fillna(self, value, downcast=None):
        if downcast is not None:
            raise NotImplementedError

        if issubclass(self.dtype.type, np.floating):
            value = float(value)

        new_values = np.where(isna(self.sp_values), value, self.sp_values)
        fill_value = value if self._null_fill_value else self.fill_value

        return self._simple_new(new_values, self.sp_index,
                                fill_value=fill_value) 
Example #6
Source File: dopamine_connector.py    From tensor2tensor with Apache License 2.0 5 votes vote down vote up
def add(self, observation, action, reward, terminal, priority):
    """Infer artificial_done and call parent method."""
    # If this will be a problem for maintenance, we could probably override
    # DQNAgent.add() method instead.
    if not isinstance(priority, (float, np.floating)):
      raise ValueError("priority should be float, got type {}"
                       .format(type(priority)))
    artificial_done = self._artificial_done and terminal
    return super(_OutOfGraphPrioritizedReplayBuffer, self).add(
        observation, action, reward, terminal, artificial_done, priority
    ) 
Example #7
Source File: test_numerictypes.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_subclass(self):
        # note we cannot promote floating to a dtype, as it would turn into a
        # concrete type
        for w in self.wrappers:
            assert_(np.issubdtype(w(np.float32), np.floating))
            assert_(np.issubdtype(w(np.float64), np.floating)) 
Example #8
Source File: images.py    From neuropythy with GNU Affero General Public License v3.0 5 votes vote down vote up
def parse_type(self, hdat, dataobj=None):
        dtype = super(MGHImageType, self).parse_type(hdat, dataobj=dataobj)
        if   np.issubdtype(dtype, np.floating): dtype = np.float32
        elif np.issubdtype(dtype, np.int8):     dtype = np.int8
        elif np.issubdtype(dtype, np.int16):    dtype = np.int16
        elif np.issubdtype(dtype, np.integer):  dtype = np.int32
        else: raise ValueError('Could not deduce appropriate MGH type for dtype %s' % dtype)
        return dtype 
Example #9
Source File: common.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def is_floating_dtype(arr_or_dtype):
    """Check whether the provided array or dtype is an instance of
    numpy's float dtype.

    .. deprecated:: 0.20.0

    Unlike, `is_float_dtype`, this check is a lot stricter, as it requires
    `isinstance` of `np.floating` and not `issubclass`.
    """

    if arr_or_dtype is None:
        return False
    tipo = _get_dtype_type(arr_or_dtype)
    return isinstance(tipo, np.floating) 
Example #10
Source File: common.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def is_float_dtype(arr_or_dtype):
    """
    Check whether the provided array or dtype is of a float dtype.

    Parameters
    ----------
    arr_or_dtype : array-like
        The array or dtype to check.

    Returns
    -------
    boolean : Whether or not the array or dtype is of a float dtype.

    Examples
    --------
    >>> is_float_dtype(str)
    False
    >>> is_float_dtype(int)
    False
    >>> is_float_dtype(float)
    True
    >>> is_float_dtype(np.array(['a', 'b']))
    False
    >>> is_float_dtype(pd.Series([1, 2]))
    False
    >>> is_float_dtype(pd.Index([1, 2.]))
    True
    """

    if arr_or_dtype is None:
        return False
    tipo = _get_dtype_type(arr_or_dtype)
    return issubclass(tipo, np.floating) 
Example #11
Source File: test_function_base.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_bin_edge_cases(self):
        # Ensure that floating-point computations correctly place edge cases.
        arr = np.array([337, 404, 739, 806, 1007, 1811, 2012])
        hist, edges = np.histogram(arr, bins=8296, range=(2, 2280))
        mask = hist > 0
        left_edges = edges[:-1][mask]
        right_edges = edges[1:][mask]
        for x, left, right in zip(arr, left_edges, right_edges):
            assert_(x >= left)
            assert_(x < right) 
Example #12
Source File: test_sql.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_default_type_conversion(self):
        df = sql.read_sql_table("types_test_data", self.conn)

        assert issubclass(df.FloatCol.dtype.type, np.floating)
        assert issubclass(df.IntCol.dtype.type, np.integer)

        # MySQL has no real BOOL type (it's an alias for TINYINT)
        assert issubclass(df.BoolCol.dtype.type, np.integer)

        # Int column with NA values stays as float
        assert issubclass(df.IntColWithNull.dtype.type, np.floating)

        # Bool column with NA = int column with NA values => becomes float
        assert issubclass(df.BoolColWithNull.dtype.type, np.floating) 
Example #13
Source File: test_sql.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_default_type_conversion(self):
        df = sql.read_sql_table("types_test_data", self.conn)

        assert issubclass(df.FloatCol.dtype.type, np.floating)
        assert issubclass(df.IntCol.dtype.type, np.integer)

        # sqlite has no boolean type, so integer type is returned
        assert issubclass(df.BoolCol.dtype.type, np.integer)

        # Int column with NA values stays as float
        assert issubclass(df.IntColWithNull.dtype.type, np.floating)

        # Non-native Bool column with NA values stays as float
        assert issubclass(df.BoolColWithNull.dtype.type, np.floating) 
Example #14
Source File: test_sql.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_default_type_conversion(self):
        df = sql.read_sql_table("types_test_data", self.conn)

        assert issubclass(df.FloatCol.dtype.type, np.floating)
        assert issubclass(df.IntCol.dtype.type, np.integer)
        assert issubclass(df.BoolCol.dtype.type, np.bool_)

        # Int column with NA values stays as float
        assert issubclass(df.IntColWithNull.dtype.type, np.floating)
        # Bool column with NA values becomes object
        assert issubclass(df.BoolColWithNull.dtype.type, np.object) 
Example #15
Source File: test_sql.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _check_iris_loaded_frame(self, iris_frame):
        pytype = iris_frame.dtypes[0].type
        row = iris_frame.iloc[0]

        assert issubclass(pytype, np.floating)
        tm.equalContents(row.values, [5.1, 3.5, 1.4, 0.2, 'Iris-setosa']) 
Example #16
Source File: test_nanops.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _skew_kurt_wrap(self, values, axis=None, func=None):
        if not isinstance(values.dtype.type, np.floating):
            values = values.astype('f8')
        result = func(values, axis=axis, bias=False)
        # fix for handling cases where all elements in an axis are the same
        if isinstance(result, np.ndarray):
            result[np.max(values, axis=axis) == np.min(values, axis=axis)] = 0
            return result
        elif np.max(values) == np.min(values):
            return 0.
        return result 
Example #17
Source File: utils.py    From strax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        try:
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return [self.default(item) for item in iterable]
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj) 
Example #18
Source File: dtypes.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def is_floating(self):
    """Returns whether this is a (non-quantized, real) floating point type."""
    return self.is_numpy_compatible and issubclass(self.as_numpy_dtype,
                                                   np.floating) 
Example #19
Source File: test_linalg.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_vector_return_type(self):
        a = np.array([1, 0, 1])

        exact_types = np.typecodes['AllInteger']
        inexact_types = np.typecodes['AllFloat']

        all_types = exact_types + inexact_types

        for each_inexact_types in all_types:
            at = a.astype(each_inexact_types)

            an = norm(at, -np.inf)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, 0.0)

            with warnings.catch_warnings():
                warnings.simplefilter("ignore", RuntimeWarning)
                an = norm(at, -1)
                assert_(issubclass(an.dtype.type, np.floating))
                assert_almost_equal(an, 0.0)

            an = norm(at, 0)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, 2)

            an = norm(at, 1)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, 2.0)

            an = norm(at, 2)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/2.0))

            an = norm(at, 4)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/4.0))

            an = norm(at, np.inf)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, 1.0) 
Example #20
Source File: npyio.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def _getconv(dtype):
    """ Find the correct dtype converter. Adapted from matplotlib """

    def floatconv(x):
        x.lower()
        if b'0x' in x:
            return float.fromhex(asstr(x))
        return float(x)

    typ = dtype.type
    if issubclass(typ, np.bool_):
        return lambda x: bool(int(x))
    if issubclass(typ, np.uint64):
        return np.uint64
    if issubclass(typ, np.int64):
        return np.int64
    if issubclass(typ, np.integer):
        return lambda x: int(float(x))
    elif issubclass(typ, np.longdouble):
        return np.longdouble
    elif issubclass(typ, np.floating):
        return floatconv
    elif issubclass(typ, np.complex):
        return lambda x: complex(asstr(x))
    elif issubclass(typ, np.bytes_):
        return bytes
    else:
        return str 
Example #21
Source File: audio.py    From audiomate with MIT License 5 votes vote down vote up
def append(self, key, samples, sampling_rate):
        """
        Append the given samples to the data that already exists
        in the container for the given key.

        Args:
            key (str): A key to store the data for.
            samples (numpy.ndarray): 1-D array of audio samples (int-16).
            sampling_rate (int): The sampling-rate of the audio samples.

        Note:
            The container has to be opened in advance.
            For appending to existing data the HDF5-Dataset has to be chunked,
            so it is not allowed to first add data via ``set``.
        """
        if not np.issubdtype(samples.dtype, np.floating):
            raise ValueError('Samples are required as np.float32!')

        if len(samples.shape) > 1:
            raise ValueError('Only single channel supported!')

        existing = self.get(key, mem_map=True)
        samples = (samples * MAX_INT16_VALUE).astype(np.int16)

        if existing is not None:
            existing_samples, existing_sr = existing

            if existing_sr != sampling_rate:
                raise ValueError('Different sampling-rate than existing data!')

            num_existing = existing_samples.shape[0]
            self._file[key].resize(num_existing + samples.shape[0], 0)
            self._file[key][num_existing:] = samples
        else:
            dset = self._file.create_dataset(key, data=samples,
                                             chunks=True, maxshape=(None,))

            dset.attrs[SAMPLING_RATE_ATTR] = sampling_rate 
Example #22
Source File: audio.py    From audiomate with MIT License 5 votes vote down vote up
def set(self, key, samples, sampling_rate):
        """
        Set the samples and sampling-rate for the given key.
        Existing data will be overwritten.
        The samples have to have ``np.float32`` datatype and values in
        the range of -1.0 and 1.0.

        Args:
            key (str): A key to store the data for.
            samples (numpy.ndarray): 1-D array of audio samples (np.float32).
            sampling_rate (int): The sampling-rate of the audio samples.

        Note:
            The container has to be opened in advance.
        """
        if not np.issubdtype(samples.dtype, np.floating):
            raise ValueError('Samples are required as np.float32!')

        if len(samples.shape) > 1:
            raise ValueError('Only single channel supported!')

        self.raise_error_if_not_open()

        if key in self._file:
            del self._file[key]

        samples = (samples * MAX_INT16_VALUE).astype(np.int16)

        dset = self._file.create_dataset(key, data=samples)
        dset.attrs[SAMPLING_RATE_ATTR] = sampling_rate

    # skipcq: PYL-W0221 
Example #23
Source File: test_linalg.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_vector_return_type(self):
        a = np.array([1, 0, 1])

        exact_types = np.typecodes['AllInteger']
        inexact_types = np.typecodes['AllFloat']

        all_types = exact_types + inexact_types

        for each_inexact_types in all_types:
            at = a.astype(each_inexact_types)

            an = norm(at, -np.inf)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, 0.0)

            with suppress_warnings() as sup:
                sup.filter(RuntimeWarning, "divide by zero encountered")
                an = norm(at, -1)
                assert_(issubclass(an.dtype.type, np.floating))
                assert_almost_equal(an, 0.0)

            an = norm(at, 0)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, 2)

            an = norm(at, 1)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, 2.0)

            an = norm(at, 2)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/2.0))

            an = norm(at, 4)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/4.0))

            an = norm(at, np.inf)
            assert_(issubclass(an.dtype.type, np.floating))
            assert_almost_equal(an, 1.0) 
Example #24
Source File: npyio.py    From lambda-packs with MIT License 5 votes vote down vote up
def _getconv(dtype):
    """ Find the correct dtype converter. Adapted from matplotlib """

    def floatconv(x):
        x.lower()
        if b'0x' in x:
            return float.fromhex(asstr(x))
        return float(x)

    typ = dtype.type
    if issubclass(typ, np.bool_):
        return lambda x: bool(int(x))
    if issubclass(typ, np.uint64):
        return np.uint64
    if issubclass(typ, np.int64):
        return np.int64
    if issubclass(typ, np.integer):
        return lambda x: int(float(x))
    elif issubclass(typ, np.longdouble):
        return np.longdouble
    elif issubclass(typ, np.floating):
        return floatconv
    elif issubclass(typ, np.complex):
        return lambda x: complex(asstr(x))
    elif issubclass(typ, np.bytes_):
        return bytes
    else:
        return str 
Example #25
Source File: dtypes.py    From lambda-packs with MIT License 5 votes vote down vote up
def is_complex(self):
    """Returns whether this is a complex floating point type."""
    return self.base_dtype in (complex64, complex128) 
Example #26
Source File: compat.py    From lambda-packs with MIT License 5 votes vote down vote up
def json_default_with_numpy(obj):
    """Convert numpy classes to JSON serializable objects."""
    if isinstance(obj, (np.integer, np.floating, np.bool_)):
        return obj.item()
    elif isinstance(obj, np.ndarray):
        return obj.tolist()
    else:
        return obj 
Example #27
Source File: arrayprint.py    From lambda-packs with MIT License 5 votes vote down vote up
def _get_format_function(data, **options):
    """
    find the right formatting function for the dtype_
    """
    dtype_ = data.dtype
    dtypeobj = dtype_.type
    formatdict = _get_formatdict(data, **options)
    if issubclass(dtypeobj, _nt.bool_):
        return formatdict['bool']()
    elif issubclass(dtypeobj, _nt.integer):
        if issubclass(dtypeobj, _nt.timedelta64):
            return formatdict['timedelta']()
        else:
            return formatdict['int']()
    elif issubclass(dtypeobj, _nt.floating):
        if issubclass(dtypeobj, _nt.longfloat):
            return formatdict['longfloat']()
        else:
            return formatdict['float']()
    elif issubclass(dtypeobj, _nt.complexfloating):
        if issubclass(dtypeobj, _nt.clongfloat):
            return formatdict['longcomplexfloat']()
        else:
            return formatdict['complexfloat']()
    elif issubclass(dtypeobj, (_nt.unicode_, _nt.string_)):
        return formatdict['numpystr']()
    elif issubclass(dtypeobj, _nt.datetime64):
        return formatdict['datetime']()
    elif issubclass(dtypeobj, _nt.object_):
        return formatdict['object']()
    elif issubclass(dtypeobj, _nt.void):
        if dtype_.names is not None:
            return StructuredVoidFormat.from_data(data, **options)
        else:
            return formatdict['void']()
    else:
        return formatdict['numpystr']() 
Example #28
Source File: npyio.py    From lambda-packs with MIT License 5 votes vote down vote up
def _getconv(dtype):
    """ Find the correct dtype converter. Adapted from matplotlib """

    def floatconv(x):
        x.lower()
        if '0x' in x:
            return float.fromhex(x)
        return float(x)

    typ = dtype.type
    if issubclass(typ, np.bool_):
        return lambda x: bool(int(x))
    if issubclass(typ, np.uint64):
        return np.uint64
    if issubclass(typ, np.int64):
        return np.int64
    if issubclass(typ, np.integer):
        return lambda x: int(float(x))
    elif issubclass(typ, np.longdouble):
        return np.longdouble
    elif issubclass(typ, np.floating):
        return floatconv
    elif issubclass(typ, complex):
        return lambda x: complex(asstr(x).replace('+-', '-'))
    elif issubclass(typ, np.bytes_):
        return asbytes
    elif issubclass(typ, np.unicode_):
        return asunicode
    else:
        return asstr

# amount of lines loadtxt reads in one chunk, can be overridden for testing 
Example #29
Source File: save_images.py    From improved_wgan_training with MIT License 5 votes vote down vote up
def save_images(X, save_path):
    # [0, 1] -> [0,255]
    if isinstance(X.flatten()[0], np.floating):
        X = (255.99*X).astype('uint8')

    n_samples = X.shape[0]
    rows = int(np.sqrt(n_samples))
    while n_samples % rows != 0:
        rows -= 1

    nh, nw = rows, n_samples/rows

    if X.ndim == 2:
        X = np.reshape(X, (X.shape[0], int(np.sqrt(X.shape[1])), int(np.sqrt(X.shape[1]))))

    if X.ndim == 4:
        # BCHW -> BHWC
        X = X.transpose(0,2,3,1)
        h, w = X[0].shape[:2]
        img = np.zeros((h*nh, w*nw, 3))
    elif X.ndim == 3:
        h, w = X[0].shape[:2]
        img = np.zeros((h*nh, w*nw))

    for n, x in enumerate(X):
        j = n/nw
        i = n%nw
        img[j*h:j*h+h, i*w:i*w+w] = x

    imsave(save_path, img) 
Example #30
Source File: extmath.py    From mars with Apache License 2.0 5 votes vote down vote up
def _safe_accumulator_op(op, x, *args, **kwargs):
    """
    This function provides numpy accumulator functions with a float64 dtype
    when used on a floating point input. This prevents accumulator overflow on
    smaller floating point dtypes.

    Parameters
    ----------
    op : function
        A accumulator function such as np.mean or np.sum
    x : numpy array
        A tensor to apply the accumulator function
    *args : positional arguments
        Positional arguments passed to the accumulator function after the
        input x
    **kwargs : keyword arguments
        Keyword arguments passed to the accumulator function

    Returns
    -------
    result : The output of the accumulator function passed to this function
    """
    if np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize < 8:
        result = op(x, *args, **kwargs, dtype=np.float64)
    else:
        result = op(x, *args, **kwargs)
    return result