Python numpy.random.random_sample() Examples
The following are 16
code examples of numpy.random.random_sample().
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.random
, or try the search function
.
Example #1
Source File: external_modules.py From script-languages with MIT License | 6 votes |
def test_numpy_inverse(self, dim): self.query(dedent('''\ CREATE EXTERNAL SCALAR SCRIPT numpy(dim INTEGER) RETURNS boolean AS # redirector @@redirector_url@@ from numpy import * from numpy.linalg import inv from numpy.random import seed, random_sample def run(ctx): dim = ctx.dim seed(12345678 * dim) A = random_sample((dim, dim)) Ai = inv(A) R = dot(A, Ai) - identity(dim) return bool(-1e-12 <= R.min() <= R.max() <= 1e-12) ''')) rows = self.query('SELECT numpy(?) FROM dual', dim) self.assertRowsEqual([(True,)], rows)
Example #2
Source File: external_modules.py From script-languages with MIT License | 6 votes |
def test_numpy_inverse(self, dim): self.query(dedent('''\ CREATE python SCALAR SCRIPT numpy(dim INTEGER) RETURNS boolean AS from numpy import * from numpy.linalg import inv from numpy.random import seed, random_sample def run(ctx): dim = ctx.dim seed(12345678 * dim) A = random_sample((dim, dim)) Ai = inv(A) R = dot(A, Ai) - identity(dim) return bool(-1e-12 <= R.min() <= R.max() <= 1e-12) ''')) rows = self.query('SELECT numpy(?) FROM dual', dim) self.assertRowsEqual([(True,)], rows)
Example #3
Source File: external_modules.py From script-languages with MIT License | 6 votes |
def test_numpy_inverse(self, dim): self.query(dedent('''\ CREATE python3 SCALAR SCRIPT numpy(dim INTEGER) RETURNS boolean AS from numpy import * from numpy.linalg import inv from numpy.random import seed, random_sample def run(ctx): dim = ctx.dim seed(12345678 * dim) A = random_sample((dim, dim)) Ai = inv(A) R = dot(A, Ai) - identity(dim) return bool(-1e-12 <= R.min() <= R.max() <= 1e-12) ''')) rows = self.query('SELECT numpy(?) FROM dual', dim) self.assertRowsEqual([(True,)], rows)
Example #4
Source File: test_alns.py From ALNS with MIT License | 6 votes |
def test_fixed_seed_outcomes(): """ Tests if fixing a seed results in deterministic outcomes even when using a 'random' acceptance criterion (here SA). """ outcomes = [0.01171, 0.00011, 0.01025] for seed, desired in enumerate(outcomes): # idx is seed alns = get_alns_instance( [lambda state, rnd: ValueState(rnd.random_sample())], [lambda state, rnd: None], seed) simulated_annealing = SimulatedAnnealing(1, .25, 1 / 100) result = alns.iterate(One(), [1, 1, 1, 1], .5, simulated_annealing, 100) assert_almost_equal(result.best_state.objective(), desired, decimal=5) # TODO test more complicated examples?
Example #5
Source File: binned_array_tests.py From bx-python with MIT License | 6 votes |
def setup(): global source global target source = [] for i in range(13): if random() < 0.5: source = concatenate((source, random(CHUNK_SIZE_RANDOM))) else: source = concatenate((source, zeros(CHUNK_SIZE_ZEROS, 'f'))) source = source.astype('f') # Set on target target = BinnedArray(128, NaN, len(source)) for i in range(len(source)): # if not isNaN( source[i] ): target[i] = source[i] return source, target
Example #6
Source File: binned_array_tests.py From bx-python with MIT License | 6 votes |
def test_file_lzo(): # With a file (lzo) target.to_file(open("/tmp/foo3", "wb"), comp_type="lzo") target3 = FileBinnedArray(open("/tmp/foo3", 'rb')) # Verify for i in range(len(source)): assert source[i] == target3[i], "No match, index: %d, source: %d, target: %d" % (i, source[i], target3[i]) # Verify with slices target3 = FileBinnedArray(open("/tmp/foo3", 'rb')) for i in range(10): a = int(random() * len(source)) b = int(random() * len(source)) if b < a: a, b = b, a assert allclose(source[a:b], target3[a:b]), "No match, index: %d:%d, source: %s, target: %s" % \ (a, b, ",".join(map(str, source[a:a+10])), ",".join(map(str, target3[a:a+10])))
Example #7
Source File: conftest.py From landlab with MIT License | 6 votes |
def pytest_generate_tests(metafunc): if "diagonal_property" in metafunc.fixturenames: metafunc.parametrize("diagonal_property", DIAGONAL_PROPERTIES) elif "edge_name" in metafunc.fixturenames: metafunc.parametrize("edge_name", EDGE_NAMES) elif "graph_element" in metafunc.fixturenames: metafunc.parametrize("graph_element", GRAPH_ELEMENTS) elif "field_dtype" in metafunc.fixturenames: metafunc.parametrize("field_dtype", FIELD_DTYPES) elif "random_xy" in metafunc.fixturenames: from numpy.random import random_sample metafunc.parametrize( "random_xy", ( tuple(-1e3 * random_sample(2)), tuple(1e3 * random_sample(2)), tuple(1e3 * (random_sample(2) - 0.5)), ), )
Example #8
Source File: random.py From recordlinkage with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _compute_vectorized(self, args, y): random_values = random_sample(args.index.shape[0]) if self.a != 0.0 or self.b != 1.0: random_values = (self.b - self.a) * random_values + self.a return random_values
Example #9
Source File: rv.py From Computable with MIT License | 5 votes |
def randwppf(ppf, args=(), size=None): """ returns an array of randomly distributed integers of a distribution whose percent point function (inverse of the CDF or quantile function) is given. args is a tuple of extra arguments to the ppf function (i.e. shape, location, scale), and size is the size of the output. Note the ppf function must accept an array of q values to compute over. """ U = random_sample(size=size) return ppf(*(U,)+args)
Example #10
Source File: generate_missing_data.py From Generative-ConvACs with MIT License | 5 votes |
def corrupt_image(img, MAR_prob=0, min_rects=0, max_rects=0, min_width=0, max_width=0, apply_to_all_channels=False): def generate_channel_mask(): mask = np.zeros(img.shape[0:2], dtype=np.bool) if MAR_prob > 0: mask[(random_sample(mask.shape) < MAR_prob)] = True if max_rects > 0 and max_width > 0: h, w = mask.shape num_rects = random_integers(min_rects, max_rects) for i in range(num_rects): px1 = random_integers(0, w - min(max(min_width, 1), w)) py1 = random_integers(0, h - min(max(min_width, 1), h)) px2 = px1 + min_width + random_integers(0, max(min(w - px1 - min_width, max_width - min_width), 0)); py2 = py1 + min_width + random_integers(0, max(min(h - py1 - min_width, max_width - min_width), 0)); if px1 <= px2 and py1 <= py2: mask[py1:py2, px1:px2] = True else: # One of the sides has length 0, so we should remove any pixels4 pass return mask new_img = img.copy() channels = 1 if len(new_img.shape) == 2 else new_img.shape[-1] global_mask = np.zeros(img.shape, dtype=np.bool) if channels == 1 or apply_to_all_channels: mask = generate_channel_mask() if channels == 1: global_mask[:, :] = mask else: for i in xrange(channels): global_mask[:, :, i] = mask else: global_mask = np.zeros(img.shape, dtype=np.bool) for i in xrange(channels): global_mask[:,:,i] = generate_channel_mask() new_img[global_mask] = 0 return (new_img, 1.0 * global_mask) # Process command line inputs
Example #11
Source File: fake_data.py From lda2vec with MIT License | 5 votes |
def sample(values, probabilities, size): assert np.allclose(np.sum(probabilities, axis=-1), 1.0) bins = np.add.accumulate(probabilities) return values[np.digitize(random_sample(size), bins)]
Example #12
Source File: tests.py From nninit with MIT License | 5 votes |
def _random_float(self, a, b): return (b - a) * random_sample() + a
Example #13
Source File: binned_array_tests.py From bx-python with MIT License | 5 votes |
def test_simple(): # Verify for i in range(len(source)): assert source[i] == target[i], "No match, index: %d, source: %f, target: %f, len( source ): %d" % (i, source[i], target[i], len(source)) # Verify with slices for i in range(10): a = int(random() * len(source)) b = int(random() * len(source)) if b < a: a, b = b, a assert allclose(source[a:b], target[a:b]), "No match, index: %d:%d, source: %s, target: %s" % \ (a, b, ",".join(map(str, source[a:a+10])), ",".join(map(str, target[a:a+10])))
Example #14
Source File: binned_array_tests.py From bx-python with MIT License | 5 votes |
def test_file(): # With a file (zlib) target.to_file(open("/tmp/foo", "wb")) target2 = FileBinnedArray(open("/tmp/foo", 'rb')) for i in range(len(source)): assert source[i] == target2[i], "No match, index: %d, source: %d, target: %d" % (i, source[i], target2[i]) # Verify with slices target2 = FileBinnedArray(open("/tmp/foo", 'rb')) for i in range(10): a = int(random() * len(source)) b = int(random() * len(source)) if b < a: a, b = b, a assert allclose(source[a:b], target[a:b]), "No match, index: %d:%d, source: %s, target: %s" % \ (a, b, ",".join(map(str, source[a:a+10])), ",".join(map(str, target2[a:a+10])))
Example #15
Source File: model.py From lddmm-ot with MIT License | 5 votes |
def wolfe_line_search(self, fun, search_dir, curr_value, exp_decrease) : """ see Numerical Optimization, Nocedal and Wright, Algorithm 3.5, p. 60 """ f = lambda t : fun(self.after_step(t * search_dir))[0] fp = lambda t : self.scal_L2(fun(self.after_step(t * search_dir))[1], search_dir).Q0 exit_code = 0 # Default : everything is all right # Code to uncomment to check that fp is the true derivative of f======== h = 1e-8 for i in range(5) : t = random_sample() update_th = fp(t) update_emp = (f(t+h) - f(t-h)) / (2*h) print('') print('search dir : ', search_dir.to_array()) print('Checking the function passed to the Wolfe line search, t = ', t) print('Empirical derivative : ', update_emp) print('Theoretical derivative : ', update_th) #======================================================================= print("Exp decrease : ", exp_decrease) (a, _, _, _, _, _) = line_search(f, fp, 0, 1, exp_decrease, curr_value, c2 = 0.95) if a == None : print('Error during the wolfe line search') a = 0 exit_code = 1 # Exit_code = 1 : break ! step = a * search_dir new_state = self.after_step(step) self.set_state(new_state) #self.current_cost_grad = (C,grad) #self.is_current_cost_computed = True self.is_current_point_computed = False return (step, exit_code)
Example #16
Source File: rv.py From Computable with MIT License | 4 votes |
def randwcdf(cdf, mean=1.0, args=(), size=None): """ Returns an array of randomly distributed integers given a CDF. Given a cumulative distribution function (CDF) returns an array of randomly distributed integers that would satisfy the CDF. Parameters ---------- cdf : function CDF function that accepts a single value and `args`, and returns an single value. mean : float, optional The mean of the distribution which helps the solver. Defaults to 1.0. args : tuple, optional Extra arguments to the cdf function (i.e. shape, location, scale) size : {int, None}, optional Is the size of the output. If None, only 1 value will be returned. Returns ------- randwcdf : ndarray Array of random numbers. Notes ----- Can use the ``scipy.stats.distributions.*.cdf`` functions for the `cdf` parameter. """ import scipy.optimize as optimize def _ppfopt(x, q, *nargs): newargs = (x,)+nargs return cdf(*newargs) - q def _ppf(q, *nargs): return optimize.fsolve(_ppfopt, mean, args=(q,)+nargs) _vppf = vectorize(_ppf) U = random_sample(size=size) return _vppf(*(U,)+args)