Here are the examples of the python api numpy.random.random taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
200 Examples
5
Example 1
View licensedef setUp(self): self.shape = (4, 10) self.x = (numpy.random.random(self.shape) - 0.5) * 20 self.x = self.x.astype(numpy.float32) self.t = numpy.random.random(self.shape).astype(numpy.float32) self.gy = numpy.random.random(self.shape[0]).astype(numpy.float32)
5
Example 2
View licensedef test_project_mo_r2r(self): nao = mol.nao_2c() c = numpy.random.random((nao*2,nao*2)) c = c + numpy.sin(c)*1j c1 = scf.addons.project_mo_r2r(mol, c, mol) self.assertTrue(numpy.allclose(c, c1)) numpy.random.seed(15) n2c = mol.nao_2c() n4c = n2c * 2 mo1 = numpy.random.random((n4c,n4c)) + numpy.random.random((n4c,n4c))*1j mol2 = gto.Mole() mol2.atom = mol.atom mol2.basis = {'H': 'cc-pvdz', 'O': 'cc-pvdz'} mol2.build(False, False) mo2 = scf.addons.project_mo_r2r(mol, mo1, mol2) self.assertAlmostEqual(abs(mo2).sum(), 2159.3715489514038, 11)
5
Example 3
View licensedef create_ICA(self, timeseries): """ :returns: persisted entity IndependentComponents """ operation, _, storage_path = self.__create_operation() partial_ts = TimeSeries(use_storage=False) partial_ts.data = numpy.random.random((10, 10, 10, 10)) partial_ica = IndependentComponents(source=partial_ts, component_time_series=numpy.random.random((10, 10, 10, 10)), prewhitening_matrix=numpy.random.random((10, 10, 10, 10)), unmixing_matrix=numpy.random.random((10, 10, 10, 10)), n_components=10, use_storage=False) ica = IndependentComponents(source=timeseries, n_components=10, storage_path=storage_path) ica.write_data_slice(partial_ica) adapter_instance = StoreAdapter([ica]) OperationService().initiate_prelaunch(operation, adapter_instance, {}) return ica
5
Example 4
View licensedef test_coherencespectrum(self): data = numpy.random.random((10, 10)) ts = time_series.TimeSeries(data=data) dt = spectral.CoherenceSpectrum(source=ts, nfft = 4, array_data = numpy.random.random((10, 10)), frequency = numpy.random.random((10,))) summary_info = dt.summary_info self.assertEqual(summary_info['Number of frequencies'], 10) self.assertEqual(summary_info['Spectral type'], 'CoherenceSpectrum') self.assertEqual(summary_info['FFT length (time-points)'], 4) self.assertEqual(summary_info['Source'], '') self.assertEqual(dt.nfft, 4) self.assertEqual(dt.shape, (10, 10)) self.assertTrue(dt.source is not None)
5
Example 5
View licensedef test_complexcoherence(self): data = numpy.random.random((10, 10)) ts = time_series.TimeSeries(data=data) dt = spectral.ComplexCoherenceSpectrum(source=ts, array_data = numpy.random.random((10, 10)), cross_spectrum = numpy.random.random((10, 10)), epoch_length = 10, segment_length = 5) summary_info = dt.summary_info self.assertEqual(summary_info['Frequency step'], 0.2) self.assertEqual(summary_info['Maximum frequency'], 0.5) self.assertEqual(summary_info['Source'], '') self.assertEqual(summary_info['Spectral type'], 'ComplexCoherenceSpectrum') self.assertTrue(dt.aggregation_functions is None) self.assertEqual(dt.epoch_length, 10) self.assertEqual(dt.segment_length, 5) self.assertEqual(dt.shape, (10, 10)) self.assertTrue(dt.source is not None) self.assertEqual(dt.windowing_function, '')
5
Example 6
View licensedef test_survival_nonzeromean(self): loss_ratio = numpy.random.random() mean = loss_ratio - numpy.random.random() self.assertEqual( 0, self.distribution.survival(loss_ratio, mean, None)) mean = loss_ratio + numpy.random.random() self.assertEqual( 1, self.distribution.survival(loss_ratio, mean, None))
5
Example 7
View licensedef test_survival_nonzeromean(self): loss_ratio = numpy.random.random() mean = loss_ratio - numpy.random.random() self.assertEqual( 0, self.distribution.survival(loss_ratio, mean, None)) mean = loss_ratio + numpy.random.random() self.assertEqual( 1, self.distribution.survival(loss_ratio, mean, None))
3
Example 8
View licensedef test_target_algorithm_multioutput_multiclass_support(self): cls = sklearn.linear_model.SGDClassifier() X = np.random.random((10, 10)) y = np.random.randint(0, 1, size=(10, 10)) self.assertRaisesRegexp(ValueError, 'bad input shape \(10, 10\)', cls.fit, X, y)
3
Example 9
View licensedef _forwardImplementation(self, inbuf, outbuf): """ Activate the copied module instead of the original and feed it with the current state. """ if random.random() < 0.001: outbuf[:] = array([random.randint(self.module.numActions)]) else: outbuf[:] = self.explorerModule.activate(self.state)
3
Example 10
View licensedef test_unsorted_index_raises(self): # should be fixed in netcdf4 v1.2.1 random_data = np.random.random(size=(4, 6)) dim0 = [0, 1, 2, 3] dim1 = [0, 2, 1, 3, 5, 4] # We will sort this in a later step da = xr.DataArray(data=random_data, dims=('dim0', 'dim1'), coords={'dim0': dim0, 'dim1': dim1}, name='randovar') ds = da.to_dataset() with self.roundtrip(ds) as ondisk: inds = np.argsort(dim1) ds2 = ondisk.isel(dim1=inds) try: print(ds2.randovar.values) # should raise IndexError in netCDF4 except IndexError as err: self.assertIn('first by calling .load', str(err))
3
Example 11
View licensedef setUp(self): # Sample size n = 100 # True mean count, given occupancy theta = 2.1 # True occupancy pi = 0.4 # Simulate some data data self.y = (np.random.random(n) < pi) * np.random.poisson(lam=theta, size=n)
3
Example 12
View licensedef rand(n): data = np.random.random(n) data[int(n*0.1):int(n*0.13)] += .5 data[int(n*0.18)] += 2 data[int(n*0.1):int(n*0.13)] *= 5 data[int(n*0.18)] *= 20 return data, np.arange(n, n+len(data)) / float(n)
3
Example 13
View licensedef setUp(self): #randomly generate data matrix self.X = np.random.random((10,50)) #some basis vectors self.trainsets = [self.X, self.X.T] #self.basis_vectors = [0,3,7,8] self.bvecinds = [0,3,7,8] self.setParams()
3
Example 14
View licensedef test_runs(): ary = np.random.random((6, 4)) checkerboard_plot(ary, col_labels=['abc', 'def', 'ghi', 'jkl'], row_labels=['sample %d' % i for i in range(1, 6)], cell_colors=['skyblue', 'whitesmoke'], font_colors=['black', 'black'], figsize=(5, 5))
3
Example 15
View licensedef test_set_seed(self): """Test that numpy and stdlib random seed is set by axelrod seed""" numpy_random_numbers = [] stdlib_random_numbers = [] for _ in range(2): seed(0) numpy_random_numbers.append(numpy.random.random()) stdlib_random_numbers.append(random.random()) self.assertEqual(numpy_random_numbers[0], numpy_random_numbers[1]) self.assertEqual(stdlib_random_numbers[0], stdlib_random_numbers[1])
3
Example 16
View licensedef color_cylinders(cyl_sim_objs): for sim_obj in cyl_sim_objs: color = np.random.random(3) for bt_obj in sim_obj.get_bullet_objects(): for link in bt_obj.GetKinBody().GetLinks(): for geom in link.GetGeometries(): geom.SetDiffuseColor(color)
3
Example 17
View licensedef handleStatus(self, msg): if msg.plan_type == msg.STANDING: goal = transformUtils.frameFromPositionAndRPY( np.array([robotStateJointController.q[0] + 2 * self.max_distance_per_plan * (np.random.random() - 0.5), robotStateJointController.q[1] + 2 * self.max_distance_per_plan * (np.random.random() - 0.5), robotStateJointController.q[2] - 0.84]), [0, 0, robotStateJointController.q[5] + 2 * np.degrees(np.pi) * (np.random.random() - 0.5)]) request = footstepsDriver.constructFootstepPlanRequest(robotStateJointController.q, goal) request.params.max_num_steps = 18 footstepsDriver.sendFootstepPlanRequest(request)
3
Example 18
View licensedef test_extreme_temperature_is_numerically_stable(self): player_low = ProbabilisticPolicyPlayer(None, temperature=1e-12) player_high = ProbabilisticPolicyPlayer(None, temperature=1e+12) distribution = np.random.random(361) distribution = distribution / distribution.sum() self.assertFalse(any(np.isnan(player_low.apply_temperature(distribution)))) self.assertFalse(any(np.isnan(player_high.apply_temperature(distribution))))
3
Example 19
View licensedef test_gray2rgb_alpha(): x = np.random.random((5, 5, 4)) assert_equal(gray2rgb(x, alpha=None).shape, (5, 5, 4)) assert_equal(gray2rgb(x, alpha=False).shape, (5, 5, 3)) assert_equal(gray2rgb(x, alpha=True).shape, (5, 5, 4)) x = np.random.random((5, 5, 3)) assert_equal(gray2rgb(x, alpha=None).shape, (5, 5, 3)) assert_equal(gray2rgb(x, alpha=False).shape, (5, 5, 3)) assert_equal(gray2rgb(x, alpha=True).shape, (5, 5, 4)) assert_equal(gray2rgb(np.array([[1, 2], [3, 4.]]), alpha=True)[0, 0, 3], 1) assert_equal(gray2rgb(np.array([[1, 2], [3, 4]], dtype=np.uint8), alpha=True)[0, 0, 3], 255)
3
Example 20
View licensedef test_rus_sample_wrong_X(): """Test either if an error is raised when X is different at fitting and sampling""" # Create the object rus = RandomUnderSampler(random_state=RND_SEED) rus.fit(X, Y) assert_raises(RuntimeError, rus.sample, np.random.random((100, 40)), np.array([0] * 50 + [1] * 50))
3
Example 21
View licensedef test_lu_refcount(self): # Test that we are keeping track of the reference count with splu. n = 30 a = random.random((n, n)) a[a < 0.95] = 0 # Make a diagonal dominant, to make sure it is not singular a += 4*eye(n) a_ = csc_matrix(a) lu = splu(a_) # And now test that we don't have a refcount bug import sys rc = sys.getrefcount(lu) for attr in ('perm_r', 'perm_c'): perm = getattr(lu, attr) assert_equal(sys.getrefcount(lu), rc + 1) del perm assert_equal(sys.getrefcount(lu), rc)
3
Example 22
View licensedef test_masked(self): # masked arrays are also accepted a = np.random.random([2, 3]) m = ma.array(a, mask=[[0, 1, 0], [0, 1, 1]]) b = broadcast_to_shape(m, (5, 3, 4, 2), (3, 1)) for i in range(5): for j in range(4): self.assertMaskedArrayEqual(b[i, :, j, :].T, m)
3
Example 23
View licensedef random_point_disk(num_points = 1): alpha = np.random.random(num_points) * math.pi * 2.0 radius = np.sqrt(np.random.random(num_points)) x = np.cos(alpha) * radius y = np.sin(alpha) * radius return np.dstack((x,y))[0]
3
Example 24
View licensedef ensure_non_zero(signal): # We add a little bit of static to avoid # 'divide by zero encountered in log' # during MFCC computation signal += np.random.random(len(signal)) * 10**-10 return signal
3
Example 25
View licensedef gen_target(self, arm): """Generate a random target""" self.target = np.random.random(size=arm.DOF,) * \ self.target_gain + self.target_bias return self.target
3
Example 26
View licensedef createModel(seed=1956): params = model_params.MODEL_PARAMS params['modelParams']['spParams']['seed'] = seed # Randomly change encoder resolution to be in [0.78, 0.98], i.e. 0.88 +/- 0.1 params['modelParams']['sensorParams']['encoders']['consumption'][ 'resolution'] = 0.78 + numpy.random.random()*.2 return ModelFactory.create(model_params.MODEL_PARAMS)
3
Example 27
View licensedef test_crps_degenerate_ensemble(self): x = np.random.random() vec = x * np.ones((10,)) for delta in [-np.pi, 0.0, +np.pi]: computed = crps_ensemble(x + delta, vec) expected = np.abs(delta * 1.0 ** 2) self.assertAlmostEqual(computed, expected)
3
Example 28
View licensedef test_toeplitz_real_sym(self): # set specific seed value such that random numbers are reproducible seed(0) src = random(50) - 0.5 rsp = random(50) - 0.5 toep = scipy.linalg.toeplitz(src) x = np.dot(scipy.linalg.inv(toep), rsp) # compare to scipy.linalg x2 = rf.deconvolve._toeplitz_real_sym(src, rsp) np.testing.assert_array_almost_equal(x, x2, decimal=3)
3
Example 29
View licensedef init_h(self): self.H = np.random.random((self._num_bases, self._num_samples)) self.H[:,:] = 1.0 # normalized bases Wnorm = np.sqrt(np.sum(self.W**2.0, axis=0)) self.W /= Wnorm for i in range(self.H.shape[0]): self.H[i,:] *= Wnorm[i] self.update_s()
3
Example 30
View licensedef __init__(self, node_names, weights): self.names = [ ] self.weights = weights self.name_to_ident = { } self.links = [ ] for name in node_names: self.name_to_ident[name] = len(self.names) self.names.append(name) self.links.append([]) self.positions = random.random((len(self.links),2)) self.update_amount = 1.5
3
Example 31
View licensedef test_oct(self): for _ in xrange(100): sig = N.random.random(100000) fmin = N.random.random()*200+1 fmax = N.random.random()*(22048-fmin)+fmin obins = N.random.randint(24)+1 print fmin,fmax,obins scale = OctScale(fmin,fmax,obins) nsgt = NSGT(scale,fs=44100,Ls=len(sig)) c = nsgt.forward(sig) s_r = nsgt.backward(c) rec_err = norm(sig-s_r)/norm(sig) self.assertAlmostEqual(rec_err,0)
3
Example 32
View licensedef randomize(self): if not getattr(self, "mds", None): return self.mds.points = numpy.random.random(size=[self.mds.n,2]) if self.computeStress: self.mds.getStress(self.stressFunc[self.StressFunc][1]) self.stress=self.getAvgStress(self.stressFunc[self.StressFunc][1]) self.graph.updateData()
3
Example 33
View licensedef test_extend_attributes(self): # corpus without features c = Corpus.from_file('bookexcerpts') X = np.random.random((len(c), 3)) c.extend_attributes(X, ['1', '2', '3']) self.assertEqual(c.X.shape, (len(c), 3)) # add to non empty corpus c.extend_attributes(X, ['1', '2', '3']) self.assertEqual(c.X.shape, (len(c), 6)) # extend sparse c.extend_attributes(csr_matrix(X), ['1', '2', '3']) self.assertEqual(c.X.shape, (len(c), 9)) self.assertTrue(issparse(c.X))
3
Example 34
View licensedef test_minibatches(): """Test if minibatches are correctly generated if given a size.""" D = np.random.random((13, 5)) batches = minibatches(D, batch_size=5) assert batches[0].shape[0] == 5 assert batches[1].shape[0] == 5 assert batches[2].shape[0] == 3
3
Example 35
View licensedef __init__(self, n_documents=100, n_document_topics=10, n_units=256, n_vocab=1000, dropout_ratio=0.5, train=True, counts=None, n_samples=15, word_dropout_ratio=0.0, power=0.75, temperature=1.0): em = EmbedMixture(n_documents, n_document_topics, n_units, dropout_ratio=dropout_ratio, temperature=temperature) kwargs = {} kwargs['mixture'] = em kwargs['sampler'] = L.NegativeSampling(n_units, counts, n_samples, power=power) super(LDA2Vec, self).__init__(**kwargs) rand = np.random.random(self.sampler.W.data.shape) self.sampler.W.data[:, :] = rand[:, :] self.n_units = n_units self.train = train self.dropout_ratio = dropout_ratio self.word_dropout_ratio = word_dropout_ratio self.n_samples = n_samples
3
Example 36
View licensedef read(self): out_buffer = StringIO() fname = os.path.basename(self.url) prefix = fname[0] if fname.endswith('.dat'): header = 'filename,class,meta1\n{}001,{},1.0\n'.format(prefix, prefix) out_buffer.write(header.encode('utf-8')) else: X = np.random.random((10, self.num_columns)) text = '\n'.join(','.join(row) for row in X.astype('str')) if fname.endswith('.zip'): with ZipFile(out_buffer, 'w') as z: z.writestr('{}001.txt'.format(prefix), text) elif fname.endswith('.tar.gz'): with tarfile.open(fileobj=out_buffer, mode='w:gz') as t: tarinfo = tarfile.TarInfo('{}001.txt'.format(prefix)) tarinfo.size = len(text) t.addfile(tarinfo, StringIO(text.encode('utf-8'))) return out_buffer.getvalue()
3
Example 37
View licensedef test_point_fog(): '''To see if we're able to render a triangle''' NPOINTS = 10000 vertices = (np.random.random((NPOINTS, 3))-0.5)*3 colors = [colors.blue] * NPOINTS v = QtViewer() tr = v.add_renderer(PointRenderer, vertices, colors) v.run()
3
Example 38
View licensedef in_comm_range(self, network, node1, node2): p1 = network.pos[node1] p2 = network.pos[node2] d = sqrt(sum(pow(p1 - p2, 2))) if random() > d ** 2 / node1.commRange ** 2: if (self.environment.are_visible(p1, p2)): assert node1.commRange == node2.commRange return True return False
3
Example 39
View licensedef test_pandas(): x = np.random.random(1000) i = np.random.random(1000) s = pd.Series(x, index=i) assert nbytes(s) == nbytes(x) + nbytes(i) df = pd.DataFrame(s) assert nbytes(df) == nbytes(s) s = pd.Series(pd.Categorical(['a', 'b'] * 1000)) assert nbytes(s.cat.codes) < nbytes(s) < nbytes(s.cat.codes) * 2
3
Example 40
View license@pytest.mark.parametrize('shape', [(2,), (2, 3), (2, 3, 5)]) @pytest.mark.parametrize('slice', [(Ellipsis,), (None, Ellipsis), (Ellipsis, None), (None, Ellipsis, None)]) def test_slicing_with_Nones(shape, slice): x = np.random.random(shape) d = da.from_array(x, chunks=shape) assert_eq(x[slice], d[slice])
3
Example 41
View licensedef test_classification_predictor(self): minExamples = 2 featureGen = lambda: np.random.random(KeyedModelTests.NDIM) # Need to ensure each user has at least one of each label to train on. cyc = cycle([-1, 1]) labelGen = lambda: next(cyc) lr = LogisticRegression(random_state=0) self.checkKeyedModelEquivalent(minExamples, featureGen, labelGen, sklearnEstimator=lr, yCol="y")
3
Example 42
View licensedef test_add_fields(pcd_fname): import pypcd pc = pypcd.PointCloud.from_path(pcd_fname) old_md = pc.get_metadata() # new_dt = [(f, pc.pc_data.dtype[f]) for f in pc.pc_data.dtype.fields] # new_data = [pc.pc_data[n] for n in pc.pc_data.dtype.names] md = {'fields': ['bla', 'bar'], 'count': [1, 1], 'size': [4, 4], 'type': ['F', 'F']} d = np.rec.fromarrays((np.random.random(len(pc.pc_data)), np.random.random(len(pc.pc_data)))) newpc = pypcd.add_fields(pc, md, d) new_md = newpc.get_metadata() # print len(old_md['fields']), len(md['fields']), len(new_md['fields']) # print old_md['fields'], md['fields'], new_md['fields'] assert(len(old_md['fields'])+len(md['fields']) == len(new_md['fields']))
3
Example 43
View licensedef construct_random_initial(self): """ Construct a random optimization vector. Returns ------- x : ndarray An optimization vector. """ # make cdists like p(x_i | w) cdists = [ np.random.random(size=shape) for shape in self._shapes ] for cdist, axes in zip(cdists, self._idxs): self.row_normalize(cdist, axes) # smash them together x = np.concatenate([ cdist.flatten() for cdist in cdists ], axis=0) return x
3
Example 44
View licensedef test_reproducable(self, TrainSplit, nn): X, y = np.random.random((100, 10)), np.repeat([0, 1, 2, 3], 25) X_train1, X_valid1, y_train1, y_valid1 = TrainSplit(0.2)( X, y, nn) X_train2, X_valid2, y_train2, y_valid2 = TrainSplit(0.2)( X, y, nn) assert np.all(X_train1 == X_train2) assert np.all(y_valid1 == y_valid2)
3
Example 45
View licensedef test_save_3d(self): shape = (4, 5, 3) expected = np.random.random(shape) dist = {0: 'b', 1: 'c', 2: 'n'} distribution = Distribution(self.context, shape, dist=dist) da = self.context.fromarray(expected, distribution=distribution) self.context.save_hdf5(self.output_path, da, mode='w') file_check = self.context.apply(check_hdf5_file, (self.output_path, expected), targets=[self.context.targets[0]])[0] self.assertTrue(file_check)
3
Example 46
View licensedef sample_discrete(distn,size=[],dtype=np.int32): 'samples from a one-dimensional finite pmf' distn = np.atleast_1d(distn) assert (distn >=0).all() and distn.ndim == 1 if (0 == distn).all(): return np.random.randint(distn.shape[0],size=size) cumvals = np.cumsum(distn) return np.sum(np.array(random(size))[...,na] * cumvals[-1] > cumvals, axis=-1,dtype=dtype)
3
Example 47
View licensedef test_add_track(self): track = Multipoint([(np.random.random(), np.random.random()) for i in range(10)], properties={"name":"segment0"}) g = vector.gpx.GPX() g.add_track(track) expected = self.Track([self.Trkseg( [self.Point(tuple(xy), {}, {}) for xy in track.vertices], {"name":"segment0"}, {})], {}, {}) self.assertEqual(g.tracks[0], expected) return
3
Example 48
View licensedef test_projecting_back_and_forth(self): lon0, lat0 = -10.4, 20.3 proj = utils.get_orthographic_projection(lon0, lat0, lon0, lat0) lons = lon0 + (numpy.random.random((20, 10)) * 50 - 25) lats = lat0 + (numpy.random.random((20, 10)) * 50 - 25) xx, yy = proj(lons, lats, reverse=False) self.assertEqual(xx.shape, (20, 10)) self.assertEqual(yy.shape, (20, 10)) blons, blats = proj(xx, yy, reverse=True) self.assertTrue(numpy.allclose(blons, lons)) self.assertTrue(numpy.allclose(blats, lats))
3
Example 49
View licensedef create(self): out = self.TEST_CLASS() for epoch in [0, 100, 400]: data = (numpy.random.random(100) * 1e5).astype(float) out.append(out.EntryClass(data, epoch=epoch, sample_rate=1)) return out
3
Example 50
View licensedef test_broadcastable(): data = {'a': np.random.random((2, 1)), 'b': np.random.random((3, 1)), 'c': 3} func = broadcastable('a', 'b') assert raises(ValidationError, func, data) func = broadcastable('a', 'c') func(data)