Python numpy.ndim() Examples
The following are 30
code examples of numpy.ndim().
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: grad_cam.py From face_classification with MIT License | 6 votes |
def deprocess_image(x): """ Same normalization as in: https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py """ if np.ndim(x) > 3: x = np.squeeze(x) # normalize tensor: center on 0., ensure std is 0.1 x = x - x.mean() x = x / (x.std() + 1e-5) x = x * 0.1 # clip to [0, 1] x = x + 0.5 x = np.clip(x, 0, 1) # convert to RGB array x = x * 255 if K.image_dim_ordering() == 'th': x = x.transpose((1, 2, 0)) x = np.clip(x, 0, 255).astype('uint8') return x
Example #2
Source File: _pick_info.py From mplcursors with MIT License | 6 votes |
def _format_scalarmappable_value(artist, idx): # matplotlib/matplotlib#12473. data = artist.get_array()[idx] if np.ndim(data) == 0: if not artist.colorbar: fig = Figure() ax = fig.subplots() artist.colorbar = fig.colorbar(artist, cax=ax) # This hack updates the ticks without actually paying the cost of # drawing (RendererBase.draw_path raises NotImplementedError). try: ax.yaxis.draw(RendererBase()) except NotImplementedError: pass fmt = artist.colorbar.formatter.format_data_short return "[" + _strip_math(fmt(data).strip()) + "]" else: return artist.format_cursor_data(data) # Includes brackets.
Example #3
Source File: fromnumeric.py From lambda-packs with MIT License | 6 votes |
def rank(a): """ Return the number of dimensions of an array. .. note:: This function is deprecated in NumPy 1.9 to avoid confusion with `numpy.linalg.matrix_rank`. The ``ndim`` attribute or function should be used instead. See Also -------- ndim : equivalent non-deprecated function Notes ----- In the old Numeric package, `rank` was the term used for the number of dimensions, but in NumPy `ndim` is used instead. """ # 2014-04-12, 1.9 warnings.warn( "`rank` is deprecated; use the `ndim` attribute or function instead. " "To find the rank of a matrix see `numpy.linalg.matrix_rank`.", VisibleDeprecationWarning, stacklevel=2) return ndim(a)
Example #4
Source File: core.py From feets with MIT License | 6 votes |
def __repr__(self): """x.__repr__() <==> repr(x).""" if not hasattr(self, "__repr"): params = self.params or {} parsed_params = [] for k, v in params.items(): sk = str(k) if np.ndim(v) != 0 and np.size(v) > MAX_VALUES_TO_REPR: tv = type(v) sv = f"<{tv.__module__}.{tv.__name__}>" else: sv = str(v) parsed_params.append(f"{sk}={sv}") str_params = ", ".join(parsed_params) self.__repr = f"{self.name}({str_params})" return self.__repr
Example #5
Source File: fromnumeric.py From recruit with Apache License 2.0 | 6 votes |
def rank(a): """ Return the number of dimensions of an array. .. note:: This function is deprecated in NumPy 1.9 to avoid confusion with `numpy.linalg.matrix_rank`. The ``ndim`` attribute or function should be used instead. See Also -------- ndim : equivalent non-deprecated function Notes ----- In the old Numeric package, `rank` was the term used for the number of dimensions, but in NumPy `ndim` is used instead. """ # 2014-04-12, 1.9 warnings.warn( "`rank` is deprecated; use the `ndim` attribute or function instead. " "To find the rank of a matrix see `numpy.linalg.matrix_rank`.", VisibleDeprecationWarning, stacklevel=2) return ndim(a)
Example #6
Source File: dataset_augmentor.py From chainer-stylegan with MIT License | 6 votes |
def augment(self, image, isArray=False): if isArray: # if the input is a numpy array, convert back to PIL image = Image.fromarray(image) image = self.transform(image) image = np.asarray(image).astype('f') w, h = image.shape[0], image.shape[1] if np.ndim(image) == 2: ch = 1 else: ch = np.shape(image)[2] image = image.reshape(w, h, ch) image = image.transpose((2, 0, 1)) if self.scaling == 'none': return image elif self.scaling == 'sigmoid': return self._scaling_sigmoid(image) elif self.scaling == 'tanh': return self._scaling_tanh(image) else: raise NotImplementedError
Example #7
Source File: test_core.py From lambda-packs with MIT License | 5 votes |
def test_count(self): # test np.ma.count specially d = np.arange(24.0).reshape((2,3,4)) m = np.zeros(24, dtype=bool).reshape((2,3,4)) m[:,0,:] = True a = np.ma.array(d, mask=m) assert_equal(count(a), 16) assert_equal(count(a, axis=1), 2*ones((2,4))) assert_equal(count(a, axis=(0,1)), 4*ones((4,))) assert_equal(count(a, keepdims=True), 16*ones((1,1,1))) assert_equal(count(a, axis=1, keepdims=True), 2*ones((2,1,4))) assert_equal(count(a, axis=(0,1), keepdims=True), 4*ones((1,1,4))) assert_equal(count(a, axis=-2), 2*ones((2,4))) assert_raises(ValueError, count, a, axis=(1,1)) assert_raises(ValueError, count, a, axis=3) # check the 'nomask' path a = np.ma.array(d, mask=nomask) assert_equal(count(a), 24) assert_equal(count(a, axis=1), 3*ones((2,4))) assert_equal(count(a, axis=(0,1)), 6*ones((4,))) assert_equal(count(a, keepdims=True), 24*ones((1,1,1))) assert_equal(np.ndim(count(a, keepdims=True)), 3) assert_equal(count(a, axis=1, keepdims=True), 3*ones((2,1,4))) assert_equal(count(a, axis=(0,1), keepdims=True), 6*ones((1,1,4))) assert_equal(count(a, axis=-2), 3*ones((2,4))) assert_raises(ValueError, count, a, axis=(1,1)) assert_raises(ValueError, count, a, axis=3) # check the 'masked' singleton assert_equal(count(np.ma.masked), 0) # check 0-d arrays do not allow axis > 0 assert_raises(ValueError, count, np.ma.array(1), axis=1)
Example #8
Source File: function_base.py From lambda-packs with MIT License | 5 votes |
def _parse_input_dimensions(args, input_core_dims): """ Parse broadcast and core dimensions for vectorize with a signature. Arguments --------- args : Tuple[ndarray, ...] Tuple of input arguments to examine. input_core_dims : List[Tuple[str, ...]] List of core dimensions corresponding to each input. Returns ------- broadcast_shape : Tuple[int, ...] Common shape to broadcast all non-core dimensions to. dim_sizes : Dict[str, int] Common sizes for named core dimensions. """ broadcast_args = [] dim_sizes = {} for arg, core_dims in zip(args, input_core_dims): _update_dim_sizes(dim_sizes, arg, core_dims) ndim = arg.ndim - len(core_dims) dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim]) broadcast_args.append(dummy_array) broadcast_shape = np.lib.stride_tricks._broadcast_shape(*broadcast_args) return broadcast_shape, dim_sizes
Example #9
Source File: fromnumeric.py From lambda-packs with MIT License | 5 votes |
def ndim(a): """ Return the number of dimensions of an array. Parameters ---------- a : array_like Input array. If it is not already an ndarray, a conversion is attempted. Returns ------- number_of_dimensions : int The number of dimensions in `a`. Scalars are zero-dimensional. See Also -------- ndarray.ndim : equivalent method shape : dimensions of array ndarray.shape : dimensions of array Examples -------- >>> np.ndim([[1,2,3],[4,5,6]]) 2 >>> np.ndim(np.array([[1,2,3],[4,5,6]])) 2 >>> np.ndim(1) 0 """ try: return a.ndim except AttributeError: return asarray(a).ndim
Example #10
Source File: test_core.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_fillvalue_exotic_dtype(self): # Tests yet more exotic flexible dtypes _check_fill_value = np.ma.core._check_fill_value ndtype = [('i', int), ('s', '|S8'), ('f', float)] control = np.array((default_fill_value(0), default_fill_value('0'), default_fill_value(0.),), dtype=ndtype) assert_equal(_check_fill_value(None, ndtype), control) # The shape shouldn't matter ndtype = [('f0', float, (2, 2))] control = np.array((default_fill_value(0.),), dtype=[('f0', float)]).astype(ndtype) assert_equal(_check_fill_value(None, ndtype), control) control = np.array((0,), dtype=[('f0', float)]).astype(ndtype) assert_equal(_check_fill_value(0, ndtype), control) ndtype = np.dtype("int, (2,3)float, float") control = np.array((default_fill_value(0), default_fill_value(0.), default_fill_value(0.),), dtype="int, float, float").astype(ndtype) test = _check_fill_value(None, ndtype) assert_equal(test, control) control = np.array((0, 0, 0), dtype="int, float, float").astype(ndtype) assert_equal(_check_fill_value(0, ndtype), control) # but when indexing, fill value should become scalar not tuple # See issue #6723 M = masked_array(control) assert_equal(M["f1"].fill_value.ndim, 0)
Example #11
Source File: test_core.py From lambda-packs with MIT License | 5 votes |
def test_compressed(self): # Test ma.compressed function. # Address gh-4026 a = np.ma.array([1, 2]) test = np.ma.compressed(a) assert_(type(test) is np.ndarray) # Test case when input data is ndarray subclass class A(np.ndarray): pass a = np.ma.array(A(shape=0)) test = np.ma.compressed(a) assert_(type(test) is A) # Test that compress flattens test = np.ma.compressed([[1],[2]]) assert_equal(test.ndim, 1) test = np.ma.compressed([[[[[1]]]]]) assert_equal(test.ndim, 1) # Test case when input is MaskedArray subclass class M(MaskedArray): pass test = np.ma.compressed(M(shape=(0,1,2))) assert_equal(test.ndim, 1) # with .compressed() overridden class M(MaskedArray): def compressed(self): return 42 test = np.ma.compressed(M(shape=(0,1,2))) assert_equal(test, 42)
Example #12
Source File: test_core.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_compressed(self): # Test ma.compressed function. # Address gh-4026 a = np.ma.array([1, 2]) test = np.ma.compressed(a) assert_(type(test) is np.ndarray) # Test case when input data is ndarray subclass class A(np.ndarray): pass a = np.ma.array(A(shape=0)) test = np.ma.compressed(a) assert_(type(test) is A) # Test that compress flattens test = np.ma.compressed([[1],[2]]) assert_equal(test.ndim, 1) test = np.ma.compressed([[[[[1]]]]]) assert_equal(test.ndim, 1) # Test case when input is MaskedArray subclass class M(MaskedArray): pass test = np.ma.compressed(M(shape=(0,1,2))) assert_equal(test.ndim, 1) # with .compessed() overriden class M(MaskedArray): def compressed(self): return 42 test = np.ma.compressed(M(shape=(0,1,2))) assert_equal(test, 42)
Example #13
Source File: meters.py From fairseq with MIT License | 5 votes |
def safe_round(number, ndigits): if hasattr(number, '__round__'): return round(number, ndigits) elif torch is not None and torch.is_tensor(number) and number.numel() == 1: return safe_round(number.item(), ndigits) elif np is not None and np.ndim(number) == 0 and hasattr(number, 'item'): return safe_round(number.item(), ndigits) else: return number
Example #14
Source File: test_core.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_basicattributes(self): # Tests some basic array attributes. a = array([1, 3, 2]) b = array([1, 3, 2], mask=[1, 0, 1]) assert_equal(a.ndim, 1) assert_equal(b.ndim, 1) assert_equal(a.size, 3) assert_equal(b.size, 3) assert_equal(a.shape, (3,)) assert_equal(b.shape, (3,))
Example #15
Source File: test_core.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_count(self): # test np.ma.count specially d = np.arange(24.0).reshape((2,3,4)) m = np.zeros(24, dtype=bool).reshape((2,3,4)) m[:,0,:] = True a = np.ma.array(d, mask=m) assert_equal(count(a), 16) assert_equal(count(a, axis=1), 2*ones((2,4))) assert_equal(count(a, axis=(0,1)), 4*ones((4,))) assert_equal(count(a, keepdims=True), 16*ones((1,1,1))) assert_equal(count(a, axis=1, keepdims=True), 2*ones((2,1,4))) assert_equal(count(a, axis=(0,1), keepdims=True), 4*ones((1,1,4))) assert_equal(count(a, axis=-2), 2*ones((2,4))) assert_raises(ValueError, count, a, axis=(1,1)) assert_raises(ValueError, count, a, axis=3) # check the 'nomask' path a = np.ma.array(d, mask=nomask) assert_equal(count(a), 24) assert_equal(count(a, axis=1), 3*ones((2,4))) assert_equal(count(a, axis=(0,1)), 6*ones((4,))) assert_equal(count(a, keepdims=True), 24*ones((1,1,1))) assert_equal(np.ndim(count(a, keepdims=True)), 3) assert_equal(count(a, axis=1, keepdims=True), 3*ones((2,1,4))) assert_equal(count(a, axis=(0,1), keepdims=True), 6*ones((1,1,4))) assert_equal(count(a, axis=-2), 3*ones((2,4))) assert_raises(ValueError, count, a, axis=(1,1)) assert_raises(ValueError, count, a, axis=3) # check the 'masked' singleton assert_equal(count(np.ma.masked), 0) # check 0-d arrays do not allow axis > 0 assert_raises(ValueError, count, np.ma.array(1), axis=1)
Example #16
Source File: fromnumeric.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def ndim(a): """ Return the number of dimensions of an array. Parameters ---------- a : array_like Input array. If it is not already an ndarray, a conversion is attempted. Returns ------- number_of_dimensions : int The number of dimensions in `a`. Scalars are zero-dimensional. See Also -------- ndarray.ndim : equivalent method shape : dimensions of array ndarray.shape : dimensions of array Examples -------- >>> np.ndim([[1,2,3],[4,5,6]]) 2 >>> np.ndim(np.array([[1,2,3],[4,5,6]])) 2 >>> np.ndim(1) 0 """ try: return a.ndim except AttributeError: return asarray(a).ndim
Example #17
Source File: test_core.py From lambda-packs with MIT License | 5 votes |
def test_fillvalue_exotic_dtype(self): # Tests yet more exotic flexible dtypes _check_fill_value = np.ma.core._check_fill_value ndtype = [('i', int), ('s', '|S8'), ('f', float)] control = np.array((default_fill_value(0), default_fill_value('0'), default_fill_value(0.),), dtype=ndtype) assert_equal(_check_fill_value(None, ndtype), control) # The shape shouldn't matter ndtype = [('f0', float, (2, 2))] control = np.array((default_fill_value(0.),), dtype=[('f0', float)]).astype(ndtype) assert_equal(_check_fill_value(None, ndtype), control) control = np.array((0,), dtype=[('f0', float)]).astype(ndtype) assert_equal(_check_fill_value(0, ndtype), control) ndtype = np.dtype("int, (2,3)float, float") control = np.array((default_fill_value(0), default_fill_value(0.), default_fill_value(0.),), dtype="int, float, float").astype(ndtype) test = _check_fill_value(None, ndtype) assert_equal(test, control) control = np.array((0, 0, 0), dtype="int, float, float").astype(ndtype) assert_equal(_check_fill_value(0, ndtype), control) # but when indexing, fill value should become scalar not tuple # See issue #6723 M = masked_array(control) assert_equal(M["f1"].fill_value.ndim, 0)
Example #18
Source File: sputils.py From lambda-packs with MIT License | 5 votes |
def isscalarlike(x): """Is x either a scalar, an array scalar, or a 0-dim array?""" return np.isscalar(x) or (isdense(x) and x.ndim == 0)
Example #19
Source File: function_base.py From lambda-packs with MIT License | 5 votes |
def _update_dim_sizes(dim_sizes, arg, core_dims): """ Incrementally check and update core dimension sizes for a single argument. Arguments --------- dim_sizes : Dict[str, int] Sizes of existing core dimensions. Will be updated in-place. arg : ndarray Argument to examine. core_dims : Tuple[str, ...] Core dimensions for this argument. """ if not core_dims: return num_core_dims = len(core_dims) if arg.ndim < num_core_dims: raise ValueError( '%d-dimensional argument does not have enough ' 'dimensions for all core dimensions %r' % (arg.ndim, core_dims)) core_shape = arg.shape[-num_core_dims:] for dim, size in zip(core_dims, core_shape): if dim in dim_sizes: if size != dim_sizes[dim]: raise ValueError( 'inconsistent size for core dimension %r: %r vs %r' % (dim, size, dim_sizes[dim])) else: dim_sizes[dim] = size
Example #20
Source File: seglink.py From seglink with GNU General Public License v3.0 | 5 votes |
def bboxes_to_xys(bboxes, image_shape): """Convert Seglink bboxes to xys, i.e., eight points The `image_shape` is used to to make sure all points return are valid, i.e., within image area """ if len(bboxes) == 0: return [] assert np.ndim(bboxes) == 2 and np.shape(bboxes)[-1] == 5, 'invalid `bboxes` param with shape = ' + str(np.shape(bboxes)) h, w = image_shape[0:2] def get_valid_x(x): if x < 0: return 0 if x >= w: return w - 1 return x def get_valid_y(y): if y < 0: return 0 if y >= h: return h - 1 return y xys = np.zeros((len(bboxes), 8)) for bbox_idx, bbox in enumerate(bboxes): bbox = ((bbox[0], bbox[1]), (bbox[2], bbox[3]), bbox[4]) points = cv2.cv.BoxPoints(bbox) points = np.int0(points) for i_xy, (x, y) in enumerate(points): x = get_valid_x(x) y = get_valid_y(y) points[i_xy, :] = [x, y] points = np.reshape(points, -1) xys[bbox_idx, :] = points return xys
Example #21
Source File: pcanet.py From MNIST-baselines with MIT License | 5 votes |
def process_input(self, images): assert(np.ndim(images) >= 3) assert(images.shape[1:3] == self.image_shape) if np.ndim(images) == 3: # forcibly convert to multi-channel images images = atleast_4d(images) images = to_channels_first(images) return images
Example #22
Source File: pcanet.py From MNIST-baselines with MIT License | 5 votes |
def atleast_4d(images): """Regard gray-scale images as 1-channel images""" assert(np.ndim(images) == 3) n, h, w = images.shape return images.reshape(n, h, w, 1)
Example #23
Source File: pcanet.py From MNIST-baselines with MIT License | 5 votes |
def __init__(self, image, filter_shape, step_shape): assert(image.ndim == 2) # should be either numpy.ndarray or cupy.ndarray self.ndarray = type(image) self.image = image self.filter_shape = filter_shape self.ys, self.xs = steps(image.shape[0:2], filter_shape, step_shape)
Example #24
Source File: actor_critic.py From cloudml-samples with Apache License 2.0 | 5 votes |
def get_target_qval(self, obs, action): if np.ndim(obs) == 1: obs = np.expand_dims(obs, axis=0) if np.ndim(action) == 1: action = np.expand_dims(action, axis=0) return self.sess.run(self.target_q_value, feed_dict={ self.target_obs: obs, self.target_action: action })
Example #25
Source File: actor_critic.py From cloudml-samples with Apache License 2.0 | 5 votes |
def get_qval(self, obs, action): if np.ndim(obs) == 1: obs = np.expand_dims(obs, axis=0) if np.ndim(action) == 1: action = np.expand_dims(action, axis=0) return self.sess.run(self.q_value, feed_dict={ self.obs: obs, self.action: action })
Example #26
Source File: actor_critic.py From cloudml-samples with Apache License 2.0 | 5 votes |
def get_target_action(self, obs): if np.ndim(obs) == 1: obs = np.expand_dims(obs, axis=0) return self.sess.run(self.target_action, feed_dict={self.target_obs: obs})
Example #27
Source File: actor_critic.py From cloudml-samples with Apache License 2.0 | 5 votes |
def get_action(self, obs): if np.ndim(obs) == 1: obs = np.expand_dims(obs, axis=0) return self.sess.run(self.action, feed_dict={self.obs: obs})
Example #28
Source File: beam_search.py From AIX360 with Apache License 2.0 | 5 votes |
def compute_LB(self, lambda1): """Compute lower bound on higher-order solutions""" Rp0 = self.rp.sum() if np.ndim(lambda1): self.LB = np.array([]) else: self.LB = np.minimum(np.cumsum(np.sort(self.Rp)[::-1])[1:], Rp0) self.LB += np.sort(self.Rn)[-2::-1] self.LB -= lambda1 * np.arange(2, len(self.Rp)+1) self.LB = self.v0 - self.LB # Lower bound specific to each singleton solution self.LB1 = self.v1 + self.Rp - Rp0 + lambda1 if len(self.LB): self.LB1[self.LB1 < self.LB.min()] = self.LB.min()
Example #29
Source File: ranges.py From formulas with European Union Public License 1.1 | 5 votes |
def set_value(self, rng, value=sh.EMPTY): self._value = sh.NONE self.ranges += rng, if value is not sh.EMPTY: if not isinstance(value, Array): if not np.ndim(value): value = [[value]] value = np.asarray(value, object) shape = _shape(**rng) value = _reshape_array_as_excel(value, shape) self.values[rng['name']] = (rng, value) return self
Example #30
Source File: iGAN_predict.py From iGAN with MIT License | 5 votes |
def predict_z(gen_model, _predict, ims, batch_size=32): n = ims.shape[0] n_gen = 0 zs = [] n_batch = int(np.ceil(n / float(batch_size))) for i in range(n_batch): imb = gen_model.transform(ims[batch_size * i:min(n, batch_size * (i + 1)), :, :, :]) zmb = _predict(imb) zs.append(zmb) n_gen += len(imb) zs = np.squeeze(np.concatenate(zs, axis=0)) if np.ndim(zs) == 1: zs = zs[np.newaxis, :] return zs