numpy.int8

Here are the examples of the python api numpy.int8 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1125 Examples 7

3 Source : function_blocks.py
with MIT License
from adamsolomou

def invert(x): 
    # Change of sign 

    return np.logical_not(x).astype(np.int8)

def add(x,y,s_in,upscale=False,s_out=None):

3 Source : function_blocks.py
with MIT License
from adamsolomou

def non_lin_sat(x,d):
    """
    Approximates a non-linear block 
    """ 
    no_samples = x.size
    z = np.empty(no_samples,dtype=np.int8)

    for sample in range(no_samples):
        start_idx = sample
        end_idx = (sample+d-1)%no_samples

        if(popcount(x[start_idx:end_idx]) >= d/2):
            z[sample] = 1
        else:
            z[sample] = 0

    return z

def Stanh(x,N): 

3 Source : function_blocks.py
with MIT License
from adamsolomou

def vec_Srelu(x):
    """
    Vectorised form of Srelu 
    """
    (x_rows, x_cols, no_samples) = x.shape

    # Initialise the output 3D-array 
    z = np.empty((x_rows,x_cols,no_samples),dtype=np.int8)

    for row_idx in range(x_rows): 
        for col_idx in range(x_cols): 
            z[row_idx,col_idx,:] = Srelu(x[row_idx,col_idx,:])

    return z

3 Source : test_dtype.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_fields_by_index(self):
        dt = np.dtype([('a', np.int8), ('b', np.float32, 3)])
        assert_dtype_equal(dt[0], np.dtype(np.int8))
        assert_dtype_equal(dt[1], np.dtype((np.float32, 3)))
        assert_dtype_equal(dt[-1], dt[1])
        assert_dtype_equal(dt[-2], dt[0])
        assert_raises(IndexError, lambda: dt[-3])

        assert_raises(TypeError, operator.getitem, dt, 3.0)
        assert_raises(TypeError, operator.getitem, dt, [])

        assert_equal(dt[1], dt[np.int8(1)])


class TestSubarray(object):

3 Source : test_getlimits.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_basic(self):
        dts = list(zip(['i1', 'i2', 'i4', 'i8',
                   'u1', 'u2', 'u4', 'u8'],
                  [np.int8, np.int16, np.int32, np.int64,
                   np.uint8, np.uint16, np.uint32, np.uint64]))
        for dt1, dt2 in dts:
            for attr in ('bits', 'min', 'max'):
                assert_equal(getattr(iinfo(dt1), attr),
                             getattr(iinfo(dt2), attr), attr)
        assert_raises(ValueError, iinfo, 'f4')

    def test_unsigned_max(self):

3 Source : test_mem_overlap.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_shares_memory_api():
    x = np.zeros([4, 5, 6], dtype=np.int8)

    assert_equal(np.shares_memory(x, x), True)
    assert_equal(np.shares_memory(x, x.copy()), False)

    a = x[:,::2,::3]
    b = x[:,::3,::2]
    assert_equal(np.shares_memory(a, b), True)
    assert_equal(np.shares_memory(a, b, max_work=None), True)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=long(1))


def test_may_share_memory_bad_max_work():

3 Source : test_regression.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_recarray_tolist(self):
        # Ticket #793, changeset r5215
        # Comparisons fail for NaN, so we can't use random memory
        # for the test.
        buf = np.zeros(40, dtype=np.int8)
        a = np.recarray(2, formats="i4,f8,f8", names="id,x,y", buf=buf)
        b = a.tolist()
        assert_( a[0].tolist() == b[0])
        assert_( a[1].tolist() == b[1])

    def test_nonscalar_item_method(self):

3 Source : test_regression.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_lexsort_buffer_length(self):
        # Ticket #1217, don't segfault.
        a = np.ones(100, dtype=np.int8)
        b = np.ones(100, dtype=np.int32)
        i = np.lexsort((a[::-1], b))
        assert_equal(i, np.arange(100, dtype=int))

    def test_object_array_to_fixed_string(self):

3 Source : test_scalarmath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_lower_align(self):
        # check data that is not aligned to element size
        # i.e doubles are aligned to 4 bytes on i386
        d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
        o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
        assert_almost_equal(d + d, d * 2)
        np.add(d, d, out=o)
        np.add(np.ones_like(d), d, out=o)
        np.add(d, np.ones_like(d), out=o)
        np.add(np.ones_like(d), d)
        np.add(d, np.ones_like(d))


class TestPower(object):

3 Source : test_scalarmath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_small_types(self):
        for t in [np.int8, np.int16, np.float16]:
            a = t(3)
            b = a ** 4
            assert_(b == 81, "error with %r: got %r" % (t, b))

    def test_large_types(self):

3 Source : test_scalarmath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_mixed_types(self):
        typelist = [np.int8, np.int16, np.float16,
                    np.float32, np.float64, np.int8,
                    np.int16, np.int32, np.int64]
        for t1 in typelist:
            for t2 in typelist:
                a = t1(3)
                b = t2(2)
                result = a**b
                msg = ("error with %r and %r:"
                       "got %r, expected %r") % (t1, t2, result, 9)
                if np.issubdtype(np.dtype(result), np.integer):
                    assert_(result == 9, msg)
                else:
                    assert_almost_equal(result, 9, err_msg=msg)

    def test_modular_power(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_ldexp(self):
        # The default Python int type should work
        assert_almost_equal(ncu.ldexp(2., 3),  16.)
        # The following int types should all be accepted
        self._check_ldexp(np.int8)
        self._check_ldexp(np.int16)
        self._check_ldexp(np.int32)
        self._check_ldexp('i')
        self._check_ldexp('l')

    def test_ldexp_overflow(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_lower_align(self):
        # check data that is not aligned to element size
        # i.e doubles are aligned to 4 bytes on i386
        d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
        assert_equal(d.max(), d[0])
        assert_equal(d.min(), d[0])

    def test_reduce_warns(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_lower_align(self):
        # check data that is not aligned to element size
        # i.e doubles are aligned to 4 bytes on i386
        d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
        assert_equal(np.abs(d), d)
        assert_equal(np.negative(d), -d)
        np.negative(d, out=d)
        np.negative(np.ones_like(d), out=d)
        np.abs(d, out=d)
        np.abs(np.ones_like(d), out=d)


class TestPositive(object):

3 Source : test_twodim_base.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_dtypes(self):
        c = array([11, -12, 13], dtype=np.int8)
        v = vander(c)
        expected = np.array([[121, 11, 1],
                             [144, -12, 1],
                             [169, 13, 1]])
        yield (assert_array_equal, v, expected)

        c = array([1.0+1j, 1.0-1j])
        v = vander(c, N=3)
        expected = np.array([[2j, 1+1j, 1],
                             [-2j, 1-1j, 1]])
        # The data is floating point, but the values are small integers,
        # so assert_array_equal *should* be safe here (rather than, say,
        # assert_array_almost_equal).
        yield (assert_array_equal, v, expected)


if __name__ == "__main__":

3 Source : test_core.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_extremum_fill_value_subdtype(self):
        a = array(([2, 3, 4],), dtype=[('value', np.int8, 3)])

        test = minimum_fill_value(a)
        assert_equal(test.dtype, a.dtype)
        assert_equal(test[0], np.full(3, minimum_fill_value(a['value'])))

        test = maximum_fill_value(a)
        assert_equal(test.dtype, a.dtype)
        assert_equal(test[0], np.full(3, maximum_fill_value(a['value'])))

    def test_fillvalue_individual_fields(self):

3 Source : test_defmatrix.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_scalar_type_pow(self):
        m = matrix([[1, 2], [3, 4]])
        for scalar_t in [np.int8, np.uint8]:
            two = scalar_t(2)
            assert_array_almost_equal(m ** 2, m ** two)

    def test_notimplemented(self):

3 Source : test_multiarray.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_keywords(self):
        x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
        # We must be specific about the endianness here:
        y = x.view(dtype='  <  i2', type=np.matrix)
        assert_array_equal(y, [[513]])

        assert_(isinstance(y, np.matrix))
        assert_equal(y.dtype, np.dtype(' < i2'))

if __name__ == "__main__":

3 Source : stata.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def get_base_missing_value(cls, dtype):
        if dtype == np.int8:
            value = cls.BASE_MISSING_VALUES['int8']
        elif dtype == np.int16:
            value = cls.BASE_MISSING_VALUES['int16']
        elif dtype == np.int32:
            value = cls.BASE_MISSING_VALUES['int32']
        elif dtype == np.float32:
            value = cls.BASE_MISSING_VALUES['float32']
        elif dtype == np.float64:
            value = cls.BASE_MISSING_VALUES['float64']
        else:
            raise ValueError('Unsupported dtype')
        return value


class StataParser(object):

3 Source : test_api.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_recode_to_categories(self, codes, old, new, expected):
        codes = np.asanyarray(codes, dtype=np.int8)
        expected = np.asanyarray(expected, dtype=np.int8)
        old = Index(old)
        new = Index(new)
        result = _recode_for_categories(codes, old, new)
        tm.assert_numpy_array_equal(result, expected)

    def test_recode_to_categories_large(self):

3 Source : test_indexing.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_getitem(self):
        assert self.factor[0] == 'a'
        assert self.factor[-1] == 'c'

        subf = self.factor[[0, 1, 2]]
        tm.assert_numpy_array_equal(subf._codes,
                                    np.array([0, 1, 1], dtype=np.int8))

        subf = self.factor[np.asarray(self.factor) == 'c']
        tm.assert_numpy_array_equal(subf._codes,
                                    np.array([2, 2, 2], dtype=np.int8))

    def test_setitem(self):

3 Source : test_function.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_lower_int_prec_count():
    df = DataFrame({'a': np.array(
        [0, 1, 2, 100], np.int8),
        'b': np.array(
        [1, 2, 3, 6], np.uint32),
        'c': np.array(
        [4, 5, 6, 8], np.int16),
        'grp': list('ab' * 2)})
    result = df.groupby('grp').count()
    expected = DataFrame({'a': [2, 2],
                          'b': [2, 2],
                          'c': [2, 2]}, index=pd.Index(list('ab'),
                                                       name='grp'))
    tm.assert_frame_equal(result, expected)


def test_count_uses_size_on_exception():

3 Source : test_coercion.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_setitem_series_int8(self, val, exp_dtype):
        obj = pd.Series([1, 2, 3, 4], dtype=np.int8)
        assert obj.dtype == np.int8

        if exp_dtype is np.int16:
            exp = pd.Series([1, 0, 3, 4], dtype=np.int8)
            self._assert_setitem_series_conversion(obj, val, exp, np.int8)
            pytest.xfail("BUG: it must be Series([1, 1, 3, 4], dtype=np.int16")

        exp = pd.Series([1, val, 3, 4], dtype=np.int8)
        self._assert_setitem_series_conversion(obj, val, exp, exp_dtype)

    @pytest.mark.parametrize("val,exp_dtype", [

3 Source : test_stata.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_read_write_reread_dta15(self, file):

        expected = self.read_csv(self.csv15)
        expected['byte_'] = expected['byte_'].astype(np.int8)
        expected['int_'] = expected['int_'].astype(np.int16)
        expected['long_'] = expected['long_'].astype(np.int32)
        expected['float_'] = expected['float_'].astype(np.float32)
        expected['double_'] = expected['double_'].astype(np.float64)
        expected['date_td'] = expected['date_td'].apply(
            datetime.strptime, args=('%Y-%m-%d',))

        file = getattr(self, file)
        parsed = self.read_dta(file)

        tm.assert_frame_equal(expected, parsed)

    @pytest.mark.parametrize('version', [114, 117])

3 Source : test_interpolate.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_overflow_nearest(self):
        # Test that the x range doesn't overflow when given integers as input
        for kind in ('nearest', 'previous', 'next'):
            x = np.array([0, 50, 127], dtype=np.int8)
            ii = interp1d(x, x, kind=kind)
            assert_array_almost_equal(ii(x), x)

    def test_local_nans(self):

3 Source : test_measurements.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_sum11():
    labels = np.array([1, 2], np.int8)
    for type in types:
        input = np.array([[1, 2], [3, 4]], type)
        output = ndimage.sum(input, labels=labels,
                                       index=2)
        assert_almost_equal(output, 6.0)


def test_sum12():

3 Source : test_measurements.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_sum12():
    labels = np.array([[1, 2], [2, 4]], np.int8)
    for type in types:
        input = np.array([[1, 2], [3, 4]], type)
        output = ndimage.sum(input, labels=labels,
                                        index=[4, 8, 2])
        assert_array_almost_equal(output, [4.0, 0.0, 5.0])


def test_mean01():

3 Source : test_measurements.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_mean04():
    labels = np.array([[1, 2], [2, 4]], np.int8)
    olderr = np.seterr(all='ignore')
    try:
        for type in types:
            input = np.array([[1, 2], [3, 4]], type)
            output = ndimage.mean(input, labels=labels,
                                            index=[4, 8, 2])
            assert_array_almost_equal(output[[0,2]], [4.0, 2.5])
            assert_(np.isnan(output[1]))
    finally:
        np.seterr(**olderr)


def test_minimum01():

3 Source : test_ndimage.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def setup_method(self):
        # list of numarray data types
        self.integer_types = [
            numpy.int8, numpy.uint8, numpy.int16, numpy.uint16,
            numpy.int32, numpy.uint32, numpy.int64, numpy.uint64]

        self.float_types = [numpy.float32, numpy.float64]

        self.types = self.integer_types + self.float_types

        # list of boundary modes:
        self.modes = ['nearest', 'wrap', 'reflect', 'mirror', 'constant']

    def test_correlate01(self):

3 Source : test_base.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_constructor4(self):
        # regression test for gh-6292: bsr_matrix((data, indices, indptr)) was
        #  trying to compare an int to a None
        n = 8
        data = np.ones((n, n, 1), dtype=np.int8)
        indptr = np.array([0, n], dtype=np.int32)
        indices = np.arange(n, dtype=np.int32)
        bsr_matrix((data, indices, indptr), blocksize=(n, 1), copy=False)

    def test_eliminate_zeros(self):

3 Source : test_sparsetools.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_dia_matvec(self):
        # Check: huge dia_matrix _matvec
        n = self.n
        data = np.ones((n, n), dtype=np.int8)
        offsets = np.arange(n)
        m = dia_matrix((data, offsets), shape=(n, n))
        v = np.ones(m.shape[1], dtype=np.int8)
        r = m.dot(v)
        assert_equal(r[0], np.int8(n))
        del data, offsets, m, v, r
        gc.collect()

    _bsr_ops = [pytest.param("matmat", marks=pytest.mark.xslow),

3 Source : test_sparsetools.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def _check_bsr_matvecs(self, m):
        m = m()
        n = self.n

        # _matvecs
        r = m.dot(np.ones((n, 2), dtype=np.int8))
        assert_equal(r[0,0], np.int8(n))

    def _check_bsr_matvec(self, m):

3 Source : test_sparsetools.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def _check_bsr_matvec(self, m):
        m = m()
        n = self.n

        # _matvec
        r = m.dot(np.ones((n,), dtype=np.int8))
        assert_equal(r[0], np.int8(n))

    def _check_bsr_diagonal(self, m):

3 Source : test_sparsetools.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def _check_bsr_matmat(self, m):
        m = m()
        n = self.n

        # _bsr_matmat
        m2 = bsr_matrix(np.ones((n, 2), dtype=np.int8), blocksize=(m.blocksize[1], 2))
        m.dot(m2)  # shouldn't SIGSEGV
        del m2

        # _bsr_matmat
        m2 = bsr_matrix(np.ones((2, n), dtype=np.int8), blocksize=(2, m.blocksize[0]))
        m2.dot(m)  # shouldn't SIGSEGV


@pytest.mark.skip(reason="64-bit indices in sparse matrices not available")

3 Source : quantized.py
with MIT License
from alibaba

    def parse(self, node, attrs, args, graph_converter):
        super().parse(node, attrs, args, graph_converter)

        self.run(node)

        # Only int8 kernel is supported
        if self.q_type == np.int8:
            self.elementwise_unary(tfl.EluOperator, graph_converter)
        else:
            ops = []

            inputs = [self.find_or_create_input(0, graph_converter)]
            outputs = self.to_tfl_tensors(self.output_names, self.output_tensors)

            ops.append(tfl.EluOperator(inputs, outputs))
            ops = self.wrap_ops_with_dequant_quants(ops)

            for op in ops:
                graph_converter.add_operator(op)

3 Source : vta.py
with MIT License
from alipay

def zero_runs(a):
    # Create an array that is 1 where a is 0, and pad each end with an extra 0.
    iszero = np.concatenate(([0], np.equal(a, 0).view(np.int8), [0]))
    absdiff = np.abs(np.diff(iszero))
    # Runs start and end where absdiff is 1.
    ranges = np.where(absdiff == 1)[0].reshape(-1, 2)
    return ranges


def cut_path(path: np.ndarray, diagonal_thres):

3 Source : test_twodim_base.py
with MIT License
from alvarobartt

    def test_dtypes(self):
        c = array([11, -12, 13], dtype=np.int8)
        v = vander(c)
        expected = np.array([[121, 11, 1],
                             [144, -12, 1],
                             [169, 13, 1]])
        assert_array_equal(v, expected)

        c = array([1.0+1j, 1.0-1j])
        v = vander(c, N=3)
        expected = np.array([[2j, 1+1j, 1],
                             [-2j, 1-1j, 1]])
        # The data is floating point, but the values are small integers,
        # so assert_array_equal *should* be safe here (rather than, say,
        # assert_array_almost_equal).
        assert_array_equal(v, expected)

3 Source : test_multiarray.py
with MIT License
from alvarobartt

    def test_keywords(self):
        x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
        # We must be specific about the endianness here:
        y = x.view(dtype='  <  i2', type=np.matrix)
        assert_array_equal(y, [[513]])

        assert_(isinstance(y, np.matrix))
        assert_equal(y.dtype, np.dtype(' < i2'))

3 Source : gotenna_sink.py
with GNU General Public License v3.0
from argilo

    def __init__(self):
        gr.sync_block.__init__(
            self,
            name="Gotenna decoder",
            in_sig=[np.int8],
            out_sig=None
        )
        # if an attribute with the same name as a parameter is found,
        # a callback is registered (properties work, too).
        self.prefix = "10"*16 + "0010110111010100"
        self.bits = ""

    def work(self, input_items, output_items):

3 Source : common.py
with Apache License 2.0
from artemis-analytics

def get_random_ascii(n, seed=42):
    """
    Get a random ASCII-only unicode string of size *n*.
    """
    arr = np.frombuffer(get_random_bytes(n, seed=seed), dtype=np.int8) & 0x7F
    result, _ = codecs.ascii_decode(arr)
    assert isinstance(result, str)
    assert len(result) == n
    return result


def _random_unicode_letters(n, seed=42):

3 Source : imagenet_torch_preprocess.py
with Apache License 2.0
from Ascend

def gen_input_bin(mode_type, file_batches, batch):
    i = 0
    for file in file_batches[batch]:
        i = i + 1
        print("batch", batch, file, "===", i)

        # RGBA to RGB
        image = Image.open(os.path.join(src_path, file)).convert('RGB')
        image = resize(image, model_config[mode_type]['resize']) # Resize
        image = center_crop(image, model_config[mode_type]['centercrop']) # CenterCrop
        img = np.array(image, dtype=np.int8)
        img.tofile(os.path.join(save_path, file.split('.')[0] + ".bin"))


def preprocess(mode_type, src_path, save_path):

3 Source : imagenet_torch_preprocess.py
with Apache License 2.0
from Ascend

def gen_input_bin(mode_type, file_batches, batch):
    i = 0
    for file in file_batches[batch]:
        i = i + 1
        print("batch", batch, file, "===", i)

        # RGBA to RGB
        image = Image.open(os.path.join(src_path, file)).convert('RGB')
        image = resize(image, model_config[mode_type]['resize']) # Resize
        image = center_crop(image, model_config[mode_type]['centercrop']) # CenterCrop
        img = np.array(image, dtype=np.int8)

        img.tofile(os.path.join(save_path, file.split('.')[0] + ".bin"))


def preprocess(mode_type, src_path, save_path):

3 Source : pytorch_transfer.py
with Apache License 2.0
from Ascend

def preprocess(mode_type, src_path, save_path):
    files = os.listdir(src_path)
    i = 0
    for file in files:
        if not file.lower().endswith(".jpeg"):
            continue
        print("start to process image {}....".format(file))
        i = i + 1
        print("file", file, "===", i)
        path_image = os.path.join(src_path, file)
        # RGBA to RGB
        image = Image.open(path_image).convert('RGB')
        image = resize(image, model_config[mode_type]['resize']) # Resize
        image = center_crop(image, model_config[mode_type]['centercrop']) # CenterCrop
        img = np.array(image, dtype=np.int8)
        img.tofile(os.path.join(save_path, file.split('.')[0] + ".bin"))


if __name__ == '__main__':

3 Source : imagenet_torch_preprocess.py
with Apache License 2.0
from Ascend

def gen_input_bin(mode_type, file_batches, batch):
    i = 0
    for file in file_batches[batch]:
        i = i + 1
        print("batch", batch, file, "===", i)

        # RGBA to RGB
        image = Image.open(os.path.join(src_path, file)).convert('RGB')
        image = resize(image, model_config[mode_type]['resize']) # Resize
        image = center_crop(image, model_config[mode_type]['centercrop']) # CenterCrop
        img = np.array(image, dtype=np.int8)
        img.tofile(os.path.join(save_path, file.split('.')[0] + ".bin"))

def preprocess_s(mode_type, src_path, save_path):

3 Source : imagenet_torch_preprocess.py
with Apache License 2.0
from Ascend

def preprocess_s(mode_type, src_path, save_path):
    files = os.listdir(src_path)
    i = 0
    for file in files:
        if not file.endswith(".jpeg"):
            continue
        print("start to process image {}....".format(file))
        i = i + 1
        print("file", file, "===", i)
        path_image = os.path.join(src_path, file)
        # RGBA to RGB
        image = Image.open(path_image).convert('RGB')
        image = resize(image, model_config[mode_type]['resize']) # Resize
        image = center_crop(image, model_config[mode_type]['centercrop']) # CenterCrop
        img = np.array(image, dtype=np.int8)
        img.tofile(os.path.join(save_path, file.split('.')[0] + ".bin"))

def preprocess(mode_type, src_path, save_path):

3 Source : deeplabv3.py
with Apache License 2.0
from Ascend

def preprocess(picPath):
    """preprocess"""
    #read img
    bgr_img = cv.imread(picPath)
    #get img shape
    orig_shape = bgr_img.shape[:2]
    #resize img
    img = cv.resize(bgr_img, (MODEL_WIDTH, MODEL_HEIGHT)).astype(np.int8)
    # save memory C_CONTIGUOUS mode
    if not img.flags['C_CONTIGUOUS']:
        img = np.ascontiguousarray(img)
    return orig_shape, img

def postprocess(result_list, pic, orig_shape, pic_path):

3 Source : utils.py
with Apache License 2.0
from AstraZeneca

def get_features(smiles: str):
    """Get a morgan fingerprint vector for the given molecule."""
    molecule = rdkit.Chem.MolFromSmiles(smiles)
    features = AllChem.GetHashedMorganFingerprint(molecule, 2, nBits=256)
    array = np.zeros((0,), dtype=np.int8)
    DataStructs.ConvertToNumpyArray(features, array)
    return array.tolist()


def write_drugs_json(drugs_raw: Mapping[str, str], output_directory: Path) -> Path:

3 Source : gym_wrapper_test.py
with MIT License
from awilliea

  def test_spec_from_gym_space_multi_binary(self):
    multi_binary_space = gym.spaces.MultiBinary(4)
    spec = gym_wrapper.spec_from_gym_space(multi_binary_space)

    self.assertEqual((4,), spec.shape)
    self.assertEqual(np.int8, spec.dtype)
    np.testing.assert_array_equal(np.array([0], dtype=np.int), spec.minimum)
    np.testing.assert_array_equal(np.array([1], dtype=np.int), spec.maximum)

  def test_spec_from_gym_space_box_scalars(self):

3 Source : test_umath.py
with Apache License 2.0
from aws-samples

    def test_lower_align(self):
        # check data that is not aligned to element size
        # i.e doubles are aligned to 4 bytes on i386
        d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
        assert_equal(d.max(), d[0])
        assert_equal(d.min(), d[0])

    def test_reduce_reorder(self):

3 Source : category.py
with Apache License 2.0
from aws-samples

    def _engine_type(self):
        # self.codes can have dtype int8, int16, int32 or int64, so we need
        # to return the corresponding engine type (libindex.Int8Engine, etc.).
        return {np.int8: libindex.Int8Engine,
                np.int16: libindex.Int16Engine,
                np.int32: libindex.Int32Engine,
                np.int64: libindex.Int64Engine,
                }[self.codes.dtype.type]

    _attributes = ['name']

See More Examples