Python numpy.asfarray() Examples
The following are 30 code examples for showing how to use numpy.asfarray(). 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: prefactor Author: lofar-astron File: make_clean_mask.py License: GNU General Public License v3.0 | 6 votes |
def __init__(self, x, y): if len(x) != len(y): raise IndexError('x and y must be equally sized.') self.x = np.asfarray(x) self.y = np.asfarray(y) # Closes the polygon if were open x1, y1 = x[0], y[0] xn, yn = x[-1], y[-1] if x1 != xn or y1 != yn: self.x = np.concatenate((self.x, [x1])) self.y = np.concatenate((self.y, [y1])) # Anti-clockwise coordinates if _det(self.x, self.y) < 0: self.x = self.x[::-1] self.y = self.y[::-1]
Example 2
Project: lambda-packs Author: ryfeus File: basic.py License: MIT License | 6 votes |
def _asfarray(x): """Like numpy asfarray, except that it does not modify x dtype if x is already an array with a float dtype, and do not cast complex types to real.""" if hasattr(x, "dtype") and x.dtype.char in numpy.typecodes["AllFloat"]: # 'dtype' attribute does not ensure that the # object is an ndarray (e.g. Series class # from the pandas library) if x.dtype == numpy.half: # no half-precision routines, so convert to single precision return numpy.asarray(x, dtype=numpy.float32) return numpy.asarray(x, dtype=x.dtype) else: # We cannot use asfarray directly because it converts sequences of # complex to sequence of real ret = numpy.asarray(x) if ret.dtype == numpy.half: return numpy.asarray(ret, dtype=numpy.float32) elif ret.dtype.char not in numpy.typecodes["AllFloat"]: return numpy.asfarray(x) return ret
Example 3
Project: FRETBursts Author: tritemio File: bg_cache.py License: GNU General Public License v2.0 | 6 votes |
def _load_bg_data(d, bg_calc_kwargs, h5file): """Load background data from a HDF5 file.""" group_name = bg_to_signature(d, **bg_calc_kwargs) if group_name not in h5file.root.background: msg = 'Group "%s" not found in the HDF5 file.' % group_name raise ValueError(msg) bg_auto_th_us0 = None bg_group = h5file.get_node('/background/', group_name) pprint('\n - Loading bakground data: ') bg = {} for node in bg_group._f_iter_nodes(): if node._v_name.startswith('BG_'): ph_sel = Ph_sel.from_str(node._v_name[len('BG_'):]) bg[ph_sel] = [np.asfarray(b) for b in node.read()] Lim = bg_group.Lim.read() Ph_p = bg_group.Ph_p.read() if 'bg_auto_th_us0' in bg_group: bg_auto_th_us0 = bg_group.bg_auto_th_us0.read() return bg, Lim, Ph_p, bg_auto_th_us0
Example 4
Project: emva1288 Author: EMVA1288 File: routines.py License: GNU General Public License v3.0 | 6 votes |
def LinearB(Xi, Yi): X = np.asfarray(Xi) Y = np.asfarray(Yi) # we want a function y = m * x + b def fp(v, x): return x * v[0] + v[1] # the error of the function e = x - y def e(v, x, y): return (fp(v, x) - y) # the initial value of m, we choose 1, because we thought YODA would # have chosen 1 v0 = np.array([1.0, 1.0]) vr, _success = leastsq(e, v0, args=(X, Y)) # compute the R**2 (sqrt of the mean of the squares of the errors) err = np.sqrt(sum(np.square(e(vr, X, Y))) / (len(X) * len(X))) # print vr, success, err return vr, err
Example 5
Project: CNN_Own_Dataset Author: YeongHyeon File: constructor.py License: MIT License | 6 votes |
def next_batch(self, batch_size=10): datas = np.empty((0, self._height, self._width, self._dimension), int) labels = np.empty((0, self._class_len), int) for idx in range(batch_size): random.randint(0, len(self._datas)-1) tmp_img = scipy.misc.imread(self._datas[idx]) tmp_img = scipy.misc.imresize(tmp_img, (self._height, self._width)) tmp_img = tmp_img.reshape(1, self._height, self._width, self._dimension) datas = np.append(datas, tmp_img, axis=0) labels = np.append(labels, np.eye(self._class_len)[int(np.asfarray(self._labels[idx]))].reshape(1, self._class_len), axis=0) return datas, labels
Example 6
Project: GraphicDesignPatternByPython Author: Relph1119 File: basic.py License: MIT License | 6 votes |
def _asfarray(x): """Like numpy asfarray, except that it does not modify x dtype if x is already an array with a float dtype, and do not cast complex types to real.""" if hasattr(x, "dtype") and x.dtype.char in numpy.typecodes["AllFloat"]: # 'dtype' attribute does not ensure that the # object is an ndarray (e.g. Series class # from the pandas library) if x.dtype == numpy.half: # no half-precision routines, so convert to single precision return numpy.asarray(x, dtype=numpy.float32) return numpy.asarray(x, dtype=x.dtype) else: # We cannot use asfarray directly because it converts sequences of # complex to sequence of real ret = numpy.asarray(x) if ret.dtype == numpy.half: return numpy.asarray(ret, dtype=numpy.float32) elif ret.dtype.char not in numpy.typecodes["AllFloat"]: return numpy.asfarray(x) return ret
Example 7
Project: pb_bss Author: fgnt File: complex_watson.py License: MIT License | 6 votes |
def log_norm_low_concentration(scale, dimension): """ Calculates logarithm of pdf function. Good at very low concentrations but starts to drop of at 20. """ scale = np.asfarray(scale) shape = scale.shape scale = scale.ravel() # Mardia1999Watson Equation 4, Taylor series b_range = range(dimension, dimension + 20 - 1 + 1) b_range = np.asarray(b_range)[None, :] return ( np.log(2) + dimension * np.log(np.pi) - np.log(math.factorial(dimension - 1)) + np.log(1 + np.sum(np.cumprod(scale[:, None] / b_range, -1), -1)) ).reshape(shape)
Example 8
Project: m3gm Author: yuvalpinter File: io_utils.py License: GNU General Public License v3.0 | 6 votes |
def load_embeddings(filename, a2i, emb_size=DEFAULT_EMBEDDING_DIM): """ loads embeddings for synsets ("atoms") from existing file, or initializes them to uniform random """ atom_to_embed = {} if filename is not None: if filename.endswith('npy'): return np.load(filename) with codecs.open(filename, "r", "utf-8") as f: for line in f: split = line.split() if len(split) > 2: atom = split[0] vec = split[1:] atom_to_embed[atom] = np.asfarray(vec) embedding_dim = len(atom_to_embed[list(atom_to_embed.keys())[0]]) else: embedding_dim = emb_size out = np.random.uniform(-0.8, 0.8, (len(a2i), embedding_dim)) if filename is not None: for atom, embed in list(atom_to_embed.items()): if atom in a2i: out[a2i[atom]] = np.array(embed) return out
Example 9
Project: knowledge_graph_attention_network Author: xiangwang1223 File: metrics.py License: MIT License | 6 votes |
def dcg_at_k(r, k, method=1): """Score is discounted cumulative gain (dcg) Relevance is positive real values. Can use binary as the previous methods. Returns: Discounted cumulative gain """ r = np.asfarray(r)[:k] if r.size: if method == 0: return r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1))) elif method == 1: return np.sum(r / np.log2(np.arange(2, r.size + 2))) else: raise ValueError('method must be 0 or 1.') return 0.
Example 10
Project: neural_graph_collaborative_filtering Author: xiangwang1223 File: metrics.py License: MIT License | 6 votes |
def dcg_at_k(r, k, method=1): """Score is discounted cumulative gain (dcg) Relevance is positive real values. Can use binary as the previous methods. Returns: Discounted cumulative gain """ r = np.asfarray(r)[:k] if r.size: if method == 0: return r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1))) elif method == 1: return np.sum(r / np.log2(np.arange(2, r.size + 2))) else: raise ValueError('method must be 0 or 1.') return 0.
Example 11
Project: lightkurve Author: KeplerGO File: targetpixelfile.py License: MIT License | 6 votes |
def _estimate_centroids_via_quadratic(self, aperture_mask): """Estimate centroids by fitting a 2D quadratic to the brightest pixels; this is a helper method for `estimate_centroids()`.""" aperture_mask = self._parse_aperture_mask(aperture_mask) col_centr, row_centr = [], [] for idx in range(len(self.time)): col, row = centroid_quadratic(self.flux[idx], mask=aperture_mask) col_centr.append(col) row_centr.append(row) # Finally, we add .5 to the result bellow because the convention is that # pixels are centered at .5, 1.5, 2.5, ... col_centr = np.asfarray(col_centr) + self.column + .5 row_centr = np.asfarray(row_centr) + self.row + .5 col_centr = Quantity(col_centr, unit='pixel') row_centr = Quantity(row_centr, unit='pixel') return col_centr, row_centr
Example 12
Project: Splunking-Crime Author: nccgroup File: basic.py License: GNU Affero General Public License v3.0 | 6 votes |
def _asfarray(x): """Like numpy asfarray, except that it does not modify x dtype if x is already an array with a float dtype, and do not cast complex types to real.""" if hasattr(x, "dtype") and x.dtype.char in numpy.typecodes["AllFloat"]: # 'dtype' attribute does not ensure that the # object is an ndarray (e.g. Series class # from the pandas library) if x.dtype == numpy.half: # no half-precision routines, so convert to single precision return numpy.asarray(x, dtype=numpy.float32) return numpy.asarray(x, dtype=x.dtype) else: # We cannot use asfarray directly because it converts sequences of # complex to sequence of real ret = numpy.asarray(x) if ret.dtype == numpy.half: return numpy.asarray(ret, dtype=numpy.float32) elif ret.dtype.char not in numpy.typecodes["AllFloat"]: return numpy.asfarray(x) return ret
Example 13
Project: scikit-ued Author: LaurentRDC File: array_utils.py License: MIT License | 6 votes |
def complex_array(real, imag): """ Combine two real ndarrays into a complex array. Parameters ---------- real, imag : array_like Real and imaginary parts of a complex array. Returns ------- complex : `~numpy.ndarray` Complex array. """ real, imag = np.asfarray(real), np.asfarray(imag) comp = real.astype(np.complex) comp += 1j * imag return comp
Example 14
Project: ACAN Author: miraiaroha File: nyu_dataloader.py License: MIT License | 5 votes |
def train_transform(self, rgb, depth): t = [Resize(240.0 / iheight)] # this is for computational efficiency, since rotation can be slow if self.rotate: angle = np.random.uniform(-5.0, 5.0) # random rotation degrees t.append(Rotate(angle)) if self.scale: s = np.random.uniform(1.0, 1.5) # random scaling depth = depth / s t.append(Resize(s)) if self.crop: slide = np.random.uniform(0.0, 1.0) t.append(RandomCrop(self.input_size, slide)) else: # center crop t.append(CenterCrop(self.input_size)) if self.flip: do_flip = np.random.uniform(0.0, 1.0) < 0.5 # random horizontal flip t.append(HorizontalFlip(do_flip)) # perform 1st step of data augmentation transform = Compose(t) rgb_np = transform(rgb) if self.jitter: color_jitter = ColorJitter(0.4, 0.4, 0.4) rgb_np = color_jitter(rgb_np) # random color jittering rgb_np = np.asfarray(rgb_np, dtype='float') / 255 depth_np = transform(depth) return rgb_np, depth_np
Example 15
Project: ACAN Author: miraiaroha File: nyu_dataloader.py License: MIT License | 5 votes |
def val_transform(self, rgb, depth): transform = Compose([Resize(240.0 / iheight), CenterCrop(self.input_size), ]) rgb_np = transform(rgb) rgb_np = np.asfarray(rgb_np, dtype='float') / 255 depth_np = transform(depth) return rgb_np, depth_np
Example 16
Project: ACAN Author: miraiaroha File: kitti_dataloader.py License: MIT License | 5 votes |
def train_transform(self, rgb, depth): t = [Crop(130, 10, 240, 1200), Resize(180 / 240)] # this is for computational efficiency, since rotation can be slow if self.rotate: angle = np.random.uniform(-5.0, 5.0) # random rotation degrees t.append(Rotate(angle)) if self.scale: s = np.random.uniform(1.0, 1.5) # random scaling depth = depth / s t.append(Resize(s)) if self.crop: # random crop slide = np.random.uniform(0.0, 1.0) t.append(RandomCrop(self.input_size, slide)) else: # center crop t.append(CenterCrop(self.input_size)) if self.flip: do_flip = np.random.uniform(0.0, 1.0) < 0.5 # random horizontal flip t.append(HorizontalFlip(do_flip)) # perform 1st step of data augmentation transform = Compose(t) rgb_np = transform(rgb) if self.jitter: color_jitter = ColorJitter(0.4, 0.4, 0.4) rgb_np = color_jitter(rgb_np) # random color jittering rgb_np = np.asfarray(rgb_np, dtype='float') / 255 # Scipy affine_transform produced RuntimeError when the depth map was # given as a 'numpy.ndarray' depth_np = np.asfarray(depth, dtype='float32') depth_np = transform(depth_np) return rgb_np, depth_np
Example 17
Project: ACAN Author: miraiaroha File: kitti_dataloader.py License: MIT License | 5 votes |
def val_transform(self, rgb, depth): transform = Compose([Crop(130, 10, 240, 1200), Resize(180 / 240), CenterCrop(self.input_size), ]) rgb_np = transform(rgb) rgb_np = np.asfarray(rgb_np, dtype='float') / 255 depth_np = np.asfarray(depth, dtype='float32') depth_np = transform(depth_np) return rgb_np, depth_np
Example 18
Project: pymoo Author: msu-coinlab File: go_benchmark.py License: Apache License 2.0 | 5 votes |
def success(self, x, tol=1.e-5): """ Tests if a candidate solution at the global minimum. The default test is Parameters ---------- x : sequence The candidate vector for testing if the global minimum has been reached. Must have ``len(x) == self.N`` tol : float The evaluated function and known global minimum must differ by less than this amount to be at a global minimum. Returns ------- bool : is the candidate vector at the global minimum? """ val = self.fun(asarray(x)) if abs(val - self.fglob) < tol: return True # the solution should still be in bounds, otherwise immediate fail. if np.any(x > np.asfarray(self.bounds)[:, 1]): return False if np.any(x < np.asfarray(self.bounds)[:, 0]): return False # you found a lower global minimum. This shouldn't happen. if val < self.fglob: raise ValueError("Found a lower global minimum", x, val, self.fglob) return False
Example 19
Project: tartarus Author: sergiooramas File: eval.py License: MIT License | 5 votes |
def dcg_at_k(r, k): """ Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) k: Number of results to consider Returns: Discounted cumulative gain """ r = np.asfarray(r)[:k] if r.size: return np.sum(r / np.log2(np.arange(2, r.size + 2))) return 0.
Example 20
Project: recruit Author: Frank-qlu File: test_regression.py License: Apache License 2.0 | 5 votes |
def test_asfarray_none(self): # Test for changeset r5065 assert_array_equal(np.array([np.nan]), np.asfarray([None]))
Example 21
Project: lambda-packs Author: ryfeus File: test_regression.py License: MIT License | 5 votes |
def test_asfarray_none(self, level=rlevel): # Test for changeset r5065 assert_array_equal(np.array([np.nan]), np.asfarray([None]))
Example 22
Project: auto-alt-text-lambda-api Author: abhisuri97 File: test_regression.py License: MIT License | 5 votes |
def test_asfarray_none(self, level=rlevel): # Test for changeset r5065 assert_array_equal(np.array([np.nan]), np.asfarray([None]))
Example 23
Project: auto-alt-text-lambda-api Author: abhisuri97 File: gradient_checker.py License: MIT License | 5 votes |
def _compute_gradient(x, x_shape, dx, y, y_shape, dy, x_init_value=None, delta=1e-3, extra_feed_dict=None): """Computes the theoretical and numerical jacobian.""" t = dtypes.as_dtype(x.dtype) allowed_types = [dtypes.float16, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128] assert t.base_dtype in allowed_types, "Don't support type %s for x" % t.name t2 = dtypes.as_dtype(y.dtype) assert t2.base_dtype in allowed_types, "Don't support type %s for y" % t2.name if x_init_value is not None: i_shape = list(x_init_value.shape) assert(list(x_shape) == i_shape), "x_shape = %s, init_data shape = %s" % ( x_shape, i_shape) x_data = x_init_value else: if t == dtypes.float16: dtype = np.float16 elif t == dtypes.float32: dtype = np.float32 else: dtype = np.float64 x_data = np.asfarray(np.random.random_sample(x_shape), dtype=dtype) jacob_t = _compute_theoretical_jacobian( x, x_shape, x_data, dy, y_shape, dx, extra_feed_dict=extra_feed_dict) jacob_n = _compute_numeric_jacobian( x, x_shape, x_data, y, y_shape, delta, extra_feed_dict=extra_feed_dict) return jacob_t, jacob_n
Example 24
Project: jMetalPy Author: jMetal File: knapsack.py License: MIT License | 5 votes |
def __read_from_file(self, filename: str): """ This function reads a Knapsack Problem instance from a file. It expects the following format: num_of_items (dimension) capacity of the knapsack num_of_items-tuples of weight-profit :param filename: File which describes the instance. :type filename: str. """ if filename is None: raise FileNotFoundError('Filename can not be None') with open(filename) as file: lines = file.readlines() data = [line.split() for line in lines if len(line.split()) >= 1] self.number_of_bits = int(data[0][0]) self.capacity = float(data[1][0]) weights_and_profits = np.asfarray(data[2:], dtype=np.float32) self.weights = weights_and_profits[:, 0] self.profits = weights_and_profits[:, 1]
Example 25
Project: vnpy_crypto Author: birforce File: test_regression.py License: MIT License | 5 votes |
def test_asfarray_none(self): # Test for changeset r5065 assert_array_equal(np.array([np.nan]), np.asfarray([None]))
Example 26
Project: DeepRobust Author: DSE-MSU File: optimizer.py License: MIT License | 5 votes |
def init_population_array(self, init): """ Initialises the population with a user specified population. Parameters ---------- init : np.ndarray Array specifying subset of the initial population. The array should have shape (M, len(x)), where len(x) is the number of parameters. The population is clipped to the lower and upper `bounds`. """ # make sure you're using a float array popn = np.asfarray(init) if (np.size(popn, 0) < 5 or popn.shape[1] != self.parameter_count or len(popn.shape) != 2): raise ValueError("The population supplied needs to have shape" " (M, len(x)), where M > 4.") # scale values and clip to bounds, assigning to population self.population = np.clip(self._unscale_parameters(popn), 0, 1) self.num_population_members = np.size(self.population, 0) self.population_shape = (self.num_population_members, self.parameter_count) # reset population energies self.population_energies = (np.ones(self.num_population_members) * np.inf) # reset number of function evaluations counter self._nfev = 0
Example 27
Project: Computable Author: ktraunmueller File: test_regression.py License: MIT License | 5 votes |
def test_asfarray_none(self, level=rlevel): """Test for changeset r5065""" assert_array_equal(np.array([np.nan]), np.asfarray([None]))
Example 28
Project: Computable Author: ktraunmueller File: basic.py License: MIT License | 5 votes |
def _asfarray(x): """Like numpy asfarray, except that it does not modify x dtype if x is already an array with a float dtype, and do not cast complex types to real.""" if hasattr(x, "dtype") and x.dtype.char in numpy.typecodes["AllFloat"]: return x else: # We cannot use asfarray directly because it converts sequences of # complex to sequence of real ret = numpy.asarray(x) if not ret.dtype.char in numpy.typecodes["AllFloat"]: return numpy.asfarray(x) return ret
Example 29
Project: audfprint Author: dpwe File: audio_read.py License: MIT License | 5 votes |
def wavread(filename): """Read in audio data from a wav file. Return d, sr.""" # Read in wav file. samplerate, wave_data = wav.read(filename) # Normalize short ints to floats in range [-1..1). data = np.asfarray(wave_data) / 32768.0 return data, samplerate
Example 30
Project: Mastering-Elasticsearch-7.0 Author: PacktPublishing File: test_regression.py License: MIT License | 5 votes |
def test_asfarray_none(self): # Test for changeset r5065 assert_array_equal(np.array([np.nan]), np.asfarray([None]))