Python numpy.moveaxis() Examples

The following are 30 code examples for showing how to use numpy.moveaxis(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: recruit   Author: Frank-qlu   File: nanfunctions.py    License: Apache License 2.0 6 votes vote down vote up
def _nanquantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
                              interpolation='linear'):
    """
    Private function that doesn't support extended axis or keepdims.
    These methods are extended to this function using _ureduce
    See nanpercentile for parameter usage
    """
    if axis is None or a.ndim == 1:
        part = a.ravel()
        result = _nanquantile_1d(part, q, overwrite_input, interpolation)
    else:
        result = np.apply_along_axis(_nanquantile_1d, axis, a, q,
                                     overwrite_input, interpolation)
        # apply_along_axis fills in collapsed axis with results.
        # Move that axis to the beginning to match percentile's
        # convention.
        if q.ndim != 0:
            result = np.moveaxis(result, axis, 0)

    if out is not None:
        out[...] = result
    return result 
Example 2
Project: DSFD-Pytorch-Inference   Author: hukkelas   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def _pre_process(self, image: np.ndarray, shrink: float) -> torch.Tensor:
        """Takes N RGB image and performs and returns a set of bounding boxes as
            detections
        Args:
            image (np.ndarray): shape [N, height, width, 3]
        Returns:
            torch.Tensor: shape [N, 3, height, width]
        """
        assert image.dtype == np.uint8
        height, width = image.shape[1:3]
        image = image.astype(np.float32) - self.mean
        image = np.moveaxis(image, -1, 1)
        image = torch.from_numpy(image)
        if self.max_resolution is not None:
            shrink_factor = self.max_resolution / max((height, width))
            if shrink_factor <= shrink:
                shrink = shrink_factor
        image = torch.nn.functional.interpolate(image, scale_factor=shrink)
        image = image.to(self.device)
        return image 
Example 3
Project: lambda-packs   Author: ryfeus   File: nanfunctions.py    License: MIT License 6 votes vote down vote up
def _nanquantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
                              interpolation='linear'):
    """
    Private function that doesn't support extended axis or keepdims.
    These methods are extended to this function using _ureduce
    See nanpercentile for parameter usage
    """
    if axis is None or a.ndim == 1:
        part = a.ravel()
        result = _nanquantile_1d(part, q, overwrite_input, interpolation)
    else:
        result = np.apply_along_axis(_nanquantile_1d, axis, a, q,
                                     overwrite_input, interpolation)
        # apply_along_axis fills in collapsed axis with results.
        # Move that axis to the beginning to match percentile's
        # convention.
        if q.ndim != 0:
            result = np.moveaxis(result, axis, 0)

    if out is not None:
        out[...] = result
    return result 
Example 4
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_numeric.py    License: MIT License 6 votes vote down vote up
def test_errors(self):
        x = np.random.randn(1, 2, 3)
        assert_raises_regex(ValueError, 'invalid axis .* `source`',
                            np.moveaxis, x, 3, 0)
        assert_raises_regex(ValueError, 'invalid axis .* `source`',
                            np.moveaxis, x, -4, 0)
        assert_raises_regex(ValueError, 'invalid axis .* `destination`',
                            np.moveaxis, x, 0, 5)
        assert_raises_regex(ValueError, 'repeated axis in `source`',
                            np.moveaxis, x, [0, 0], [0, 1])
        assert_raises_regex(ValueError, 'repeated axis in `destination`',
                            np.moveaxis, x, [0, 1], [1, 1])
        assert_raises_regex(ValueError, 'must have the same number',
                            np.moveaxis, x, 0, [0, 1])
        assert_raises_regex(ValueError, 'must have the same number',
                            np.moveaxis, x, [0, 1], [0]) 
Example 5
Project: discopy   Author: oxford-quantum-group   File: tensor.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *dim):
        """
        >>> Id(1)
        Tensor(dom=Dim(1), cod=Dim(1), array=[1])
        >>> list(Id(2).array.flatten())
        [1.0, 0.0, 0.0, 1.0]
        >>> Id(2).array.shape
        (2, 2)
        >>> list(Id(2, 2).array.flatten())[:8]
        [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]
        >>> list(Id(2, 2).array.flatten())[8:]
        [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]
        """
        dim = dim[0] if isinstance(dim[0], Dim) else Dim(*dim)
        array = functools.reduce(
            lambda a, x: np.tensordot(a, np.identity(x), 0)
            if a.shape else np.identity(x), dim, np.array(1))
        array = np.moveaxis(
            array, [2 * i for i in range(len(dim))], list(range(len(dim))))
        super().__init__(dim, dim, array) 
Example 6
Project: ocelot   Author: ocelot-collab   File: math_op.py    License: GNU General Public License v3.0 6 votes vote down vote up
def n_moment(x, counts, c, n):
    x = np.squeeze(x)
    if x.ndim is not 1:
        raise ValueError("scale of x should be 1-dimensional")
    if x.size not in counts.shape:
        raise ValueError("operands could not be broadcast together with shapes %s %s" %(str(x.shape), str(counts.shape)))
    
    if np.sum(counts)==0:
        return 0
    else:
        if x.ndim == 1 and counts.ndim == 1:
            return (np.sum((x-c)**n*counts) / np.sum(counts))**(1./n)
        else:
            
            if x.size in counts.shape:
                dim_ = [i for i, v in enumerate(counts.shape) if v == x.size]
                counts = np.moveaxis(counts, dim_, -1)
                return (np.sum((x-c)**n*counts, axis=-1) / np.sum(counts, axis=-1))**(1./n) 
Example 7
Project: vnpy_crypto   Author: birforce   File: nanfunctions.py    License: MIT License 6 votes vote down vote up
def _nanpercentile(a, q, axis=None, out=None, overwrite_input=False,
                   interpolation='linear'):
    """
    Private function that doesn't support extended axis or keepdims.
    These methods are extended to this function using _ureduce
    See nanpercentile for parameter usage

    """
    if axis is None or a.ndim == 1:
        part = a.ravel()
        result = _nanpercentile1d(part, q, overwrite_input, interpolation)
    else:
        result = np.apply_along_axis(_nanpercentile1d, axis, a, q,
                                     overwrite_input, interpolation)
        # apply_along_axis fills in collapsed axis with results.
        # Move that axis to the beginning to match percentile's
        # convention.
        if q.ndim != 0:
            result = np.moveaxis(result, axis, 0)

    if out is not None:
        out[...] = result
    return result 
Example 8
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: nanfunctions.py    License: MIT License 6 votes vote down vote up
def _nanquantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
                              interpolation='linear'):
    """
    Private function that doesn't support extended axis or keepdims.
    These methods are extended to this function using _ureduce
    See nanpercentile for parameter usage
    """
    if axis is None or a.ndim == 1:
        part = a.ravel()
        result = _nanquantile_1d(part, q, overwrite_input, interpolation)
    else:
        result = np.apply_along_axis(_nanquantile_1d, axis, a, q,
                                     overwrite_input, interpolation)
        # apply_along_axis fills in collapsed axis with results.
        # Move that axis to the beginning to match percentile's
        # convention.
        if q.ndim != 0:
            result = np.moveaxis(result, axis, 0)

    if out is not None:
        out[...] = result
    return result 
Example 9
Project: neural-pipeline   Author: toodef   File: img_segmentation.py    License: MIT License 5 votes vote down vote up
def augmentate_and_to_pytorch(item: {}):
    res = augmentate(item)
    return {'data': torch.from_numpy(np.moveaxis(res['data'].astype(np.float32) / 255., -1, 0)),
            'target': torch.from_numpy(np.expand_dims(res['target'].astype(np.float32) / 255, axis=0))} 
Example 10
Project: L3C-PyTorch   Author: fab-jul   File: figure_plotter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _render_to_rgb(figure, close):
    canvas = plt_backend_agg.FigureCanvasAgg(figure)
    canvas.draw()
    data = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8)
    w, h = figure.canvas.get_width_height()
    image_hwc = data.reshape([h, w, 4])[..., :3]
    image_chw = np.moveaxis(image_hwc, source=2, destination=0)
    if close:
        plt.close(figure)
    return image_chw 
Example 11
Project: pytorch-a3c   Author: ikostrikov   File: envs.py    License: MIT License 5 votes vote down vote up
def _process_frame42(frame):
    frame = frame[34:34 + 160, :160]
    # Resize by half, then down to 42x42 (essentially mipmapping). If
    # we resize directly we lose pixels that, when mapped to 42x42,
    # aren't close enough to the pixel boundary.
    frame = cv2.resize(frame, (80, 80))
    frame = cv2.resize(frame, (42, 42))
    frame = frame.mean(2, keepdims=True)
    frame = frame.astype(np.float32)
    frame *= (1.0 / 255.0)
    frame = np.moveaxis(frame, -1, 0)
    return frame 
Example 12
Project: recruit   Author: Frank-qlu   File: test_function_base.py    License: Apache License 2.0 5 votes vote down vote up
def test_extended_axis(self):
        o = np.random.normal(size=(71, 23))
        x = np.dstack([o] * 10)
        assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30))
        x = np.moveaxis(x, -1, 0)
        assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30))
        x = x.swapaxes(0, 1).copy()
        assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30))
        x = x.swapaxes(0, 1).copy()

        assert_equal(np.percentile(x, [25, 60], axis=(0, 1, 2)),
                     np.percentile(x, [25, 60], axis=None))
        assert_equal(np.percentile(x, [25, 60], axis=(0,)),
                     np.percentile(x, [25, 60], axis=0))

        d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
        np.random.shuffle(d.ravel())
        assert_equal(np.percentile(d, 25,  axis=(0, 1, 2))[0],
                     np.percentile(d[:,:,:, 0].flatten(), 25))
        assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1],
                     np.percentile(d[:,:, 1,:].flatten(), [10, 90]))
        assert_equal(np.percentile(d, 25, axis=(3, 1, -4))[2],
                     np.percentile(d[:,:, 2,:].flatten(), 25))
        assert_equal(np.percentile(d, 25, axis=(3, 1, 2))[2],
                     np.percentile(d[2,:,:,:].flatten(), 25))
        assert_equal(np.percentile(d, 25, axis=(3, 2))[2, 1],
                     np.percentile(d[2, 1,:,:].flatten(), 25))
        assert_equal(np.percentile(d, 25, axis=(1, -2))[2, 1],
                     np.percentile(d[2,:,:, 1].flatten(), 25))
        assert_equal(np.percentile(d, 25, axis=(1, 3))[2, 2],
                     np.percentile(d[2,:, 2,:].flatten(), 25)) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_function_base.py    License: Apache License 2.0 5 votes vote down vote up
def test_extended_axis(self):
        o = np.random.normal(size=(71, 23))
        x = np.dstack([o] * 10)
        assert_equal(np.median(x, axis=(0, 1)), np.median(o))
        x = np.moveaxis(x, -1, 0)
        assert_equal(np.median(x, axis=(-2, -1)), np.median(o))
        x = x.swapaxes(0, 1).copy()
        assert_equal(np.median(x, axis=(0, -1)), np.median(o))

        assert_equal(np.median(x, axis=(0, 1, 2)), np.median(x, axis=None))
        assert_equal(np.median(x, axis=(0, )), np.median(x, axis=0))
        assert_equal(np.median(x, axis=(-1, )), np.median(x, axis=-1))

        d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
        np.random.shuffle(d.ravel())
        assert_equal(np.median(d, axis=(0, 1, 2))[0],
                     np.median(d[:,:,:, 0].flatten()))
        assert_equal(np.median(d, axis=(0, 1, 3))[1],
                     np.median(d[:,:, 1,:].flatten()))
        assert_equal(np.median(d, axis=(3, 1, -4))[2],
                     np.median(d[:,:, 2,:].flatten()))
        assert_equal(np.median(d, axis=(3, 1, 2))[2],
                     np.median(d[2,:,:,:].flatten()))
        assert_equal(np.median(d, axis=(3, 2))[2, 1],
                     np.median(d[2, 1,:,:].flatten()))
        assert_equal(np.median(d, axis=(1, -2))[2, 1],
                     np.median(d[2,:,:, 1].flatten()))
        assert_equal(np.median(d, axis=(1, 3))[2, 2],
                     np.median(d[2,:, 2,:].flatten())) 
Example 14
Project: recruit   Author: Frank-qlu   File: test_shape_base.py    License: Apache License 2.0 5 votes vote down vote up
def test_exceptions(self):
        # test axis must be in bounds
        for ndim in [1, 2, 3]:
            a = np.ones((1,)*ndim)
            np.concatenate((a, a), axis=0)  # OK
            assert_raises(np.AxisError, np.concatenate, (a, a), axis=ndim)
            assert_raises(np.AxisError, np.concatenate, (a, a), axis=-(ndim + 1))

        # Scalars cannot be concatenated
        assert_raises(ValueError, concatenate, (0,))
        assert_raises(ValueError, concatenate, (np.array(0),))

        # test shapes must match except for concatenation axis
        a = np.ones((1, 2, 3))
        b = np.ones((2, 2, 3))
        axis = list(range(3))
        for i in range(3):
            np.concatenate((a, b), axis=axis[0])  # OK
            assert_raises(ValueError, np.concatenate, (a, b), axis=axis[1])
            assert_raises(ValueError, np.concatenate, (a, b), axis=axis[2])
            a = np.moveaxis(a, -1, 0)
            b = np.moveaxis(b, -1, 0)
            axis.append(axis.pop(0))

        # No arrays to concatenate raises ValueError
        assert_raises(ValueError, concatenate, ()) 
Example 15
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_move_to_end(self):
        x = np.random.randn(5, 6, 7)
        for source, expected in [(0, (6, 7, 5)),
                                 (1, (5, 7, 6)),
                                 (2, (5, 6, 7)),
                                 (-1, (5, 6, 7))]:
            actual = np.moveaxis(x, source, -1).shape
            assert_(actual, expected) 
Example 16
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_move_new_position(self):
        x = np.random.randn(1, 2, 3, 4)
        for source, destination, expected in [
                (0, 1, (2, 1, 3, 4)),
                (1, 2, (1, 3, 2, 4)),
                (1, -1, (1, 3, 4, 2)),
                ]:
            actual = np.moveaxis(x, source, destination).shape
            assert_(actual, expected) 
Example 17
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_preserve_order(self):
        x = np.zeros((1, 2, 3, 4))
        for source, destination in [
                (0, 0),
                (3, -1),
                (-1, 3),
                ([0, -1], [0, -1]),
                ([2, 0], [2, 0]),
                (range(4), range(4)),
                ]:
            actual = np.moveaxis(x, source, destination).shape
            assert_(actual, (1, 2, 3, 4)) 
Example 18
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_move_multiples(self):
        x = np.zeros((0, 1, 2, 3))
        for source, destination, expected in [
                ([0, 1], [2, 3], (2, 3, 0, 1)),
                ([2, 3], [0, 1], (2, 3, 0, 1)),
                ([0, 1, 2], [2, 3, 0], (2, 3, 0, 1)),
                ([3, 0], [1, 0], (0, 3, 1, 2)),
                ([0, 3], [0, 1], (0, 3, 1, 2)),
                ]:
            actual = np.moveaxis(x, source, destination).shape
            assert_(actual, expected) 
Example 19
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_array_likes(self):
        x = np.ma.zeros((1, 2, 3))
        result = np.moveaxis(x, 0, 0)
        assert_(x.shape, result.shape)
        assert_(isinstance(result, np.ma.MaskedArray))

        x = [1, 2, 3]
        result = np.moveaxis(x, 0, 0)
        assert_(x, list(result))
        assert_(isinstance(result, np.ndarray)) 
Example 20
Project: buzzard   Author: airware   File: _dataset_back_conversions.py    License: Apache License 2.0 5 votes vote down vote up
def _make_transfo(osr_transfo):
        """Wrap osr coordinate transformation input/output"""

        def _f(*args):
            nargs = len(args)

            if nargs == 1:
                # When coordinates in last dimension
                arr = np.asarray(args[0])
                assert arr.ndim >= 2
                ncoord = arr.shape[-1]
                assert 2 <= ncoord <= 3
                outshape = arr.shape

                arr = arr.reshape(int(arr.size / ncoord), ncoord)
                arr = osr_transfo(arr)
                arr = np.asarray(arr)
                arr = arr[:, 0:ncoord]
                arr = arr.reshape(outshape)
                return arr
            elif 2 <= nargs <= 3:
                # When coordinates in first dimension
                arr = np.asarray(args)
                assert arr.ndim == 2
                ncoord = nargs
                arr = np.moveaxis(arr, 0, 1)
                arr = osr_transfo(arr)
                arr = np.asarray(arr)
                arr = arr[:, 0:ncoord]
                arr = np.moveaxis(arr, 0, 1)
                return tuple(arr)
            else:
                assert False # pragma: no cover

        return _f 
Example 21
Project: graph_distillation   Author: google   File: visualize.py    License: Apache License 2.0 5 votes vote down vote up
def visualize_rgb(images):
  """Visualize RGB modality."""
  images = utils.to_numpy(images)

  mean = np.array([0.485, 0.456, 0.406])
  std = np.array([0.229, 0.224, 0.225])
  images = np.moveaxis(images, -3, -1)
  images = images*std+mean
  images = np.clip(images*255, 0, 255)
  images = images[..., ::-1].astype(np.uint8)
  images = images[0, 0]  # subsample

  imgproc.save_avi('/home/luoa/research/rgb.avi', images) 
Example 22
Project: graph_distillation   Author: google   File: visualize.py    License: Apache License 2.0 5 votes vote down vote up
def visualize_oflow(images):
  """Visualize optical flow modality."""
  images = utils.to_numpy(images)

  images = np.moveaxis(images, -3, -1)
  images = images[0, 0]  # subsample

  images = imgproc.proc_oflow(images)
  imgproc.save_avi('/home/luoa/research/oflow.avi', images) 
Example 23
Project: graph_distillation   Author: google   File: visualize.py    License: Apache License 2.0 5 votes vote down vote up
def visualize_warp(rgb, oflow):
  """TODO: add info."""
  rgb = utils.to_numpy(rgb)
  oflow = utils.to_numpy(oflow)

  mean = np.array([0.485, 0.456, 0.406])
  std = np.array([0.229, 0.224, 0.225])
  rgb = np.moveaxis(rgb, -3, -1)
  rgb = rgb*std+mean
  rgb = np.clip(rgb*255, 0, 255)
  bgr = rgb[..., ::-1].astype(np.uint8)
  bgr = bgr[0, 0]  # subsample
  print(bgr.shape, np.amin(bgr), np.amax(bgr), np.mean(bgr),
        np.mean(np.absolute(bgr)))

  oflow = np.moveaxis(oflow, -3, -1)
  oflow = oflow[0, 0]  # subsample
  print(oflow.shape, np.amin(oflow), np.amax(oflow), np.mean(oflow),
        np.mean(np.absolute(oflow)))

  warp = imgproc.warp(bgr[4], bgr[5], oflow[4])

  root = '/home/luoa/research'
  cv2.imwrite(os.path.join(root, 'bgr1.jpg'), bgr[4])
  cv2.imwrite(os.path.join(root, 'bgr2.jpg'), bgr[5])
  cv2.imwrite(os.path.join(root, 'warp.jpg'), warp) 
Example 24
Project: argus-tgs-salt   Author: lRomul   File: transforms.py    License: MIT License 5 votes vote down vote up
def __call__(self, image):
        image = np.moveaxis(image, -1, 0)
        image = image.astype(np.float32) / 255.0
        image = torch.from_numpy(image)
        if self.coord_channels:
            image = self.add_coord_channels(image)
        return image 
Example 25
Project: mars   Author: mars-project   File: test_core_execute.py    License: Apache License 2.0 5 votes vote down vote up
def testViewDataOnMoveaxis(self):
        data = np.random.rand(10, 20)
        a = tensor(data, chunk_size=6)
        b = moveaxis(a, 1, 0)
        a[0][1] = 10

        npa = data.copy()
        npb = np.moveaxis(npa, 1, 0)
        npa[0][1] = 10

        np.testing.assert_array_equal(b.execute(), npb)
        np.testing.assert_array_equal(a.execute(), npa) 
Example 26
Project: Qualia2.0   Author: Kashu7100   File: fimlp.py    License: MIT License 5 votes vote down vote up
def _load_data(self, path):
        if gpu:
            import numpy
            data = np.asarray(numpy.moveaxis(numpy.load(path+'/face_images.npz', 'r')['face_images'], -1, 0))
        else:
            data = np.moveaxis(np.load(path+'/face_images.npz', 'r')['face_images'], -1, 0) 
        data = data[self.data_mask]
        
        return data[:self.divide].reshape(-1,1,96,96), data[self.divide:].reshape(-1,1,96,96) 
Example 27
Project: lambda-packs   Author: ryfeus   File: numeric.py    License: MIT License 5 votes vote down vote up
def _move_axis_to_0(a, axis):
    return moveaxis(a, axis, 0) 
Example 28
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_move_to_end(self):
        x = np.random.randn(5, 6, 7)
        for source, expected in [(0, (6, 7, 5)),
                                 (1, (5, 7, 6)),
                                 (2, (5, 6, 7)),
                                 (-1, (5, 6, 7))]:
            actual = np.moveaxis(x, source, -1).shape
            assert_(actual, expected) 
Example 29
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_move_new_position(self):
        x = np.random.randn(1, 2, 3, 4)
        for source, destination, expected in [
                (0, 1, (2, 1, 3, 4)),
                (1, 2, (1, 3, 2, 4)),
                (1, -1, (1, 3, 4, 2)),
                ]:
            actual = np.moveaxis(x, source, destination).shape
            assert_(actual, expected) 
Example 30
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def test_preserve_order(self):
        x = np.zeros((1, 2, 3, 4))
        for source, destination in [
                (0, 0),
                (3, -1),
                (-1, 3),
                ([0, -1], [0, -1]),
                ([2, 0], [2, 0]),
                (range(4), range(4)),
                ]:
            actual = np.moveaxis(x, source, destination).shape
            assert_(actual, (1, 2, 3, 4))