我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用numpy.random.binomial()。
def sample(self,action): """ samples given the specified action index and returns the values of the parents of Y, Y. """ if action == 2*self.N+1: # do(z = 1) z = 1 elif action == 2*self.N: # do(z = 0) z = 0 else: # we are not setting z z = binomial(1,self.pZ) x = binomial(1,self.pXgivenZ[1,:,z]) # PXgivenZ[j,i,k] = P(X_i=j|Z=k) if action < 2*self.N: # setting x_i = j i,j = action % self.N, action/self.N x[i] = j y = binomial(1,self.pYgivenX(x)) return x,y
def sample(self,action): """ samples given the specified action index and returns the values of the parents of Y, Y. """ z = binomial(1,self.pZ) x = binomial(1,self.pXgivenZ[1,:,z]) # PXgivenZ[j,i,k] = P(X_i=j|Z=k) if action < 2*self.N: # setting x_i = j i,j = action % self.N, action/self.N x[i] = j y = binomial(1,self.pYgivenX(x)) return x,y # def weights(self): # return np.asarray([self.N1,self.N2,self.N1,self.N2,1]) # # def contract(self,long_form): # result = np.zeros(5) # result[0] = long_form[0] # result[1] = long_form[self.N-1] # result[2] = long_form[self.N] # result[3] = long_form[2*self.N-1] # result[4] = long_form[-1] # return result
def _confirm(self): """Returns an action to confirm an unconfirmed slot. The confirmation could either be explicit or implicit. In the latter case, the action requests an EMPTY slot in addition to implicitly confirming an unconfirmed one. An "unconfirmed" slot is one which is marked "OBTAINED", but not yet "CONFIRMED". Returns: AgentAction: An action to confirm a slot. """ # Controls the fraction of total confirmations that are explicit. b = binomial(1, AGENT_EXPLICIT_VS_IMPLICIT_CONFIRMATION_PROBABILITY) if b == 1: return self._explicit_confirm() else: return self._implicit_confirm()
def optimize_hyper_hdp(self): # Optimize \alpha_0 m_dot = self.msampler.m_dotk.sum() alpha_0 = self.zsampler.alpha_0 n_jdot = np.array(self.zsampler.data_dims) #norm = np.linalg.norm(n_jdot/alpha_0) #u_j = binomial(1, n_jdot/(norm* alpha_0)) u_j = binomial(1, n_jdot/(n_jdot + alpha_0)) v_j = beta(alpha_0 + 1, n_jdot) new_alpha0 = gamma(self.a_alpha + m_dot - u_j.sum(), 1/( self.b_alpha - np.log(v_j).sum()), size=5).mean() self.zsampler.alpha_0 = new_alpha0 # Optimize \gamma K = self.zsampler._K gmma = self.betasampler.gmma #norm = np.linalg.norm(m_dot/gmma) #u = binomial(1, m_dot / (norm*gmma)) u = binomial(1, m_dot / (m_dot + gmma)) v = beta(gmma + 1, m_dot) new_gmma = gamma(self.a_gmma + K -1 + u, 1/(self.b_gmma - np.log(v)), size=5).mean() self.betasampler.gmma = new_gmma print('alpha a, b: %s, %s ' % (self.a_alpha + m_dot - u_j.sum(), 1/( self.b_alpha - np.log(v_j).sum()))) print( 'hyper sample: alpha_0: %s gamma: %s' % (new_alpha0, new_gmma)) return
def test_binomial(self): n = [1] p = [0.5] bad_n = [-1] bad_p_one = [-1] bad_p_two = [1.5] binom = np.random.binomial desired = np.array([1, 1, 1]) self.setSeed() actual = binom(n * 3, p) assert_array_equal(actual, desired) assert_raises(ValueError, binom, bad_n * 3, p) assert_raises(ValueError, binom, n * 3, bad_p_one) assert_raises(ValueError, binom, n * 3, bad_p_two) self.setSeed() actual = binom(n, p * 3) assert_array_equal(actual, desired) assert_raises(ValueError, binom, bad_n, p * 3) assert_raises(ValueError, binom, n, bad_p_one * 3) assert_raises(ValueError, binom, n, bad_p_two * 3)
def test_n_zero(self): # Tests the corner case of n == 0 for the binomial distribution. # binomial(0, p) should be zero for any p in [0, 1]. # This test addresses issue #3480. zeros = np.zeros(2, dtype='int') for p in [0, .5, 1]: assert_(random.binomial(0, p) == 0) np.testing.assert_array_equal(random.binomial(zeros, p), zeros)
def test_p_is_nan(self): # Issue #4571. assert_raises(ValueError, random.binomial, 1, np.nan)
def test_negative_binomial(self): # Ensure that the negative binomial results take floating point # arguments without truncation. self.prng.negative_binomial(0.5, 0.5)
def test_binomial(self): np.random.seed(self.seed) actual = np.random.binomial(100.123, .456, size=(3, 2)) desired = np.array([[37, 43], [42, 48], [46, 45]]) np.testing.assert_array_equal(actual, desired)
def flip(p): return random.binomial(1, p)
def sample_multiple(self,actions,n): """ draws n samples from the reward distributions of the specified actions. """ return binomial(n,self.expected_rewards[actions])
def sample(self,action): x = binomial(1,self.pX[1,:]) if action != self.K - 1: # everything except the do() action i,j = action % self.N, action/self.N x[i] = j y = binomial(1,self.pYgivenX(x)) return x,y
def test_learn_cf_semi(): """Test ovk curl-free estimator fit on semi-supervised data.""" X, y = ovk.toy_data_curl_free_field(n_samples=500) Xtr, Xte, ytr, yte = train_test_split(X, y, train_size=100) nan_mask = binomial(1, 0.1, ytr.shape[0]).astype(bool) ytr[nan_mask, :] = NaN regr_1 = ovk.OVKRidge(ovkernel=ovk.RBFCurlFreeKernel(gamma=10.), lbda=0) regr_1.fit(Xtr, ytr) assert regr_1.score(Xte, yte) >= 0.8
def test_learn_df_semi(): """Test ovk curl-free estimator fit on semi-supervised data..""" X, y = ovk.toy_data_div_free_field(n_samples=500) Xtr, Xte, ytr, yte = train_test_split(X, y, train_size=100) nan_mask = binomial(1, 0.1, ytr.shape[0]).astype(bool) ytr[nan_mask, :] = NaN regr_1 = ovk.OVKRidge(ovkernel=ovk.RBFDivFreeKernel(gamma=10.), lbda=0) regr_1.fit(Xtr, ytr) assert regr_1.score(Xte, yte) >= 0.8
def optimize_hyper_hdp(self): # Optimize \alpha_0 m_dot = self.msampler.m_dotk.sum() alpha_0 = self.zsampler.alpha_0 n_jdot = np.array(self.zsampler.data_dims, dtype=float) # @debug add row count + line count for masked ! #p = np.power(n_jdot / alpha_0, np.arange(n_jdot.shape[0])) #norm = np.linalg.norm(p) #u_j = binomial(1, p/norm) u_j = binomial(1, alpha_0/(n_jdot + alpha_0)) #u_j = binomial(1, n_jdot/(n_jdot + alpha_0)) try: v_j = beta(alpha_0 + 1, n_jdot) except: #n_jdot[n_jdot == 0] = np.finfo(float).eps lgg.warning('Unable to optimize MMSB parameters, possible empty sequence...') return shape_a = self.a_alpha + m_dot - u_j.sum() if shape_a <= 0: lgg.warning('Unable to optimize MMSB parameters, possible empty sequence...') return new_alpha0 = gamma(shape_a, 1/( self.b_alpha - np.log(v_j).sum()), size=3).mean() self.zsampler.alpha_0 = new_alpha0 # Optimize \gamma K = self.zsampler._K #m_dot = self.msampler.m_dotk gmma = self.betasampler.gmma #p = np.power(m_dot / gmma, np.arange(m_dot.shape[0])) #norm = np.linalg.norm(p) #u = binomial(1, p/norm) u = binomial(1, gmma / (m_dot + gmma)) #u = binomial(1, m_dot / (m_dot + gmma)) v = beta(gmma + 1, m_dot) new_gmma = gamma(self.a_gmma + K -1 + u, 1/(self.b_gmma - np.log(v)), size=3).mean() self.betasampler.gmma = new_gmma #print 'm_dot %d, alpha a, b: %s, %s ' % (m_dot, self.a_alpha + m_dot - u_j.sum(), 1/( self.b_alpha - np.log(v_j).sum())) #print 'gamma a, b: %s, %s ' % (self.a_gmma + K -1 + u, 1/(self.b_gmma - np.log(v))) lgg.debug('hyper sample: alpha_0: %s gamma: %s' % (new_alpha0, new_gmma)) return
def test_n_zero(self): # Tests the corner case of n == 0 for the binomial distribution. # binomial(0, p) should be zero for any p in [0, 1]. # This test addresses issue #3480. zeros = np.zeros(2, dtype='int') for p in [0, .5, 1]: assert_(random.binomial(0, p) == 0) assert_array_equal(random.binomial(zeros, p), zeros)
def test_binomial(self): np.random.seed(self.seed) actual = np.random.binomial(100.123, .456, size=(3, 2)) desired = np.array([[37, 43], [42, 48], [46, 45]]) assert_array_equal(actual, desired)
def test_results_dense(): print('restore test') # # set seed # seed(1234) # # create test object # adata = AnnData(np.multiply(binomial(1, 0.15, (100, 20)), negative_binomial(2, 0.25, (100, 20)))) # # adapt marker_genes for cluster (so as to have some form of reasonable input # adata.X[0:10, 0:5] = np.multiply(binomial(1, 0.9, (10, 5)), negative_binomial(1, 0.5, (10, 5))) # # Create cluster according to groups # smp = 'true_groups' # true_groups = np.zeros((2, 100), dtype=bool) # true_groups[0, 0:10] = 1 # true_groups[1, 10:100] = 1 # adata.uns[smp + '_masks'] = true_groups # adata.uns[smp + '_order'] = np.asarray(['0', '1']) # # Now run the rank_genes_groups, test functioning. # # Note: Default value is on copying = true. # with open('objs_t_test.pkl', 'rb') as f: # Python 3: open(..., 'rb') # true_scores_t_test, true_names_t_test = pickle.load(f) # with open('objs_wilcoxon.pkl', 'rb') as f: # Python 3: open(..., 'rb') # true_scores_wilcoxon, true_names_wilcoxon = pickle.load(f) # rank_genes_groups(adata, 'true_groups', n_genes=20, test_type='t_test') # assert np.array_equal(true_scores_t_test, adata.uns['rank_genes_groups_gene_scores']) # assert np.array_equal(true_names_t_test, adata.uns['rank_genes_groups_gene_names']) # rank_genes_groups(adata, 'true_groups', n_genes=20, test_type='wilcoxon') # assert np.array_equal(true_scores_wilcoxon, adata.uns['rank_genes_groups_gene_scores']) # assert np.array_equal(true_names_wilcoxon, adata.uns['rank_genes_groups_gene_names'])
def test_results_sparse(): print('restore test') # # set seed # seed(1234) # # The following construction is inefficient, but makes sure that the same data is used in the sparse case # adata = AnnData(np.multiply(binomial(1, 0.15, (100, 20)), negative_binomial(2, 0.25, (100, 20)))) # # adapt marker_genes for cluster (so as to have some form of reasonable input # adata.X[0:10, 0:5] = np.multiply(binomial(1, 0.9, (10, 5)), negative_binomial(1, 0.5, (10, 5))) # adata_sparse = AnnData(sp.csr_matrix(adata.X)) # # Create cluster according to groups # smp = 'true_groups' # true_groups = np.zeros((2, 100), dtype=bool) # true_groups[0, 0:10] = 1 # true_groups[1, 10:100] = 1 # adata_sparse.uns[smp + '_masks'] = true_groups # adata_sparse.uns[smp + '_order'] = np.asarray(['0', '1']) # # Here, we have saved the true results # # Now run the rank_genes_groups, test functioning. # # Note: Default value is on copying = true. # with open('objs_t_test.pkl', 'rb') as f: # Python 3: open(..., 'rb') # true_scores_t_test, true_names_t_test = pickle.load(f) # with open('objs_wilcoxon.pkl', 'rb') as f: # Python 3: open(..., 'rb') # true_scores_wilcoxon, true_names_wilcoxon = pickle.load(f) # rank_genes_groups(adata_sparse, 'true_groups', n_genes=20, test_type='t_test') # # Here, we allow a minor error tolerance due to different multiplication for sparse/non-spars objects # ERROR_TOLERANCE = 5e-7 # max_error = 0 # for i, k in enumerate(adata_sparse.uns['rank_genes_groups_gene_scores']): # max_error = max(max_error, abs( # adata_sparse.uns['rank_genes_groups_gene_scores'][i][0] - true_scores_t_test[i][0])) # max_error = max(max_error, abs( # adata_sparse.uns['rank_genes_groups_gene_scores'][i][1] - true_scores_t_test[i][1])) # # assert np.array_equal(true_scores_t_test,adata_sparse.uns['rank_genes_groups_gene_scores']) # assert max_error < ERROR_TOLERANCE # rank_genes_groups(adata_sparse, 'true_groups', n_genes=20, test_type='wilcoxon') # assert np.array_equal(true_scores_wilcoxon, adata_sparse.uns['rank_genes_groups_gene_scores']) # assert np.array_equal(true_names_wilcoxon, adata_sparse.uns['rank_genes_groups_gene_names'])
def test_compute_distribution(): print('restore test') # # set seed # seed(1234) # # create test object # adata = AnnData(np.multiply(binomial(1, 0.15, (100, 20)), negative_binomial(2, 0.25, (100, 20)))) # # adapt marker_genes for cluster (so as to have some form of reasonable input # adata.X[0:10, 0:5] = np.multiply(binomial(1, 0.9, (10, 5)), negative_binomial(1, 0.5, (10, 5))) # # Create cluster according to groups # smp = 'true_groups' # true_groups = np.zeros((2, 100), dtype=bool) # true_groups[0, 0:10] = 1 # true_groups[1, 10:100] = 1 # adata.uns[smp + '_masks'] = true_groups # adata.uns[smp + '_order'] = np.asarray(['0', '1']) # # Now run the rank_genes_groups, test functioning. # # Note: Default value is on copying = true. # with open('objs_t_test.pkl', 'rb') as f: # Python 3: open(..., 'rb') # true_scores_t_test, true_names_t_test = pickle.load(f) # with open('objs_wilcoxon.pkl', 'rb') as f: # Python 3: open(..., 'rb') # true_scores_wilcoxon, true_names_wilcoxon = pickle.load(f) # rank_genes_groups(adata, 'true_groups', n_genes=20, compute_distribution=True, test_type='t_test') # assert np.array_equal(true_scores_t_test, adata.uns['rank_genes_groups_gene_scores']) # assert np.array_equal(true_names_t_test, adata.uns['rank_genes_groups_gene_names']) # rank_genes_groups(adata, 'true_groups', n_genes=20, compute_distribution=True, test_type='wilcoxon') # assert np.array_equal(true_scores_wilcoxon, adata.uns['rank_genes_groups_gene_scores']) # assert np.array_equal(true_names_wilcoxon, adata.uns['rank_genes_groups_gene_names'])
def __init__(self, val=None, shape=None, sibling=None, parents=None, child=None, lbda=None, bernoulli_prior=.5, density_conditions=None, p_init=.5, role=None, sampling_indicator = True, parent_layers = None): """ role (str): 'features' or 'observations' or 'data'. Try to infer if not provided """ self.trace_index = 0 self.sampling_fct = None # never use empty lists as default arguments. bad things will happen if parents is None: parents = [] if parent_layers is None: parent_layers = [] self.parent_layers = parent_layers # assign family self.parents = parents self.child = child self.sibling = sibling self.lbda = lbda # assign prior self.set_prior(bernoulli_prior, density_conditions) # ascertain that we have enough information to initiliase the matrix assert (val is not None) or (shape is not None and p_init is not None) # initiliase matrix. TODO sanity checks for matrices (-1,1?) # if value is given, assign if val is not None: self.val = np.array(val, dtype=np.int8) # otherwise, if p_init is a matrix, assign it as value elif type(p_init) is np.ndarray: self.val = np.array(p_init, dtype=np.int8) # otherwise, initialise iid random with p_init else: # print('initialise matrix randomly') self.val = 2*np.array(binomial(n=1, p=p_init, size=shape), dtype=np.int8)-1 self.family_setup() if role is None: self.infer_role() else: self.role = role # sampling indicator is boolean matrix of the same size, type=np.int8 self.set_sampling_indicator(sampling_indicator)
def __init__(self, n=None, method='stub', **distribution): """ Possible arguments for the distribution are: - network_type: specify the type of network that should be constructed (THIS IS MANDATORY). It can either be the name of a distribution or of a certain network type. ['l_partition', 'poisson', 'normal', 'binomial', 'exponential', 'geometric', 'gamma', 'power', 'weibull'] For specific parameters of the distributions, see: http://docs.scipy.org/doc/numpy/reference/routines.random.html - method: The probabilistic framework after which the network will be constructed. - distribution specific arguments. Check out the description of the specific numpy function. Or just give the argument network_type and look at what the error tells you. see self._create_graph for more information """ _Graph.__init__(self) self.is_static = True self._rewiring_attempts = 100000 self._stub_attempts = 100000 self.permitted_types = allowed_dists + ["l_partition", 'full'] self.is_directed = False # to do: pass usefull info in here. self._info = {} #for now only undirected networks if n is not None: self.n = n if method in ['proba', 'stub']: self.method = method else: raise ValueError(method + ' is not a permitted method! Chose either "proba" or "stub"') try: self.nw_name = distribution.pop('network_type') empty_graph = False except KeyError: self.nn = [] self._convert_to_array() empty_graph = True #create an empty graph if network_type is not given if not empty_graph: if self.nw_name not in self.permitted_types: raise ValueError( "The specified network type \"%s\" is not permitted. \ Please chose from " % self.nw_name + '[' + ', '.join(self.permitted_types) + ']') self.distribution = distribution self._create_graph(**self.distribution)
def main(): parser = argparse.ArgumentParser() parser.add_argument('task', type=str, choices=['InvertedPendulum', 'InvertedDoublePendulum', 'Reacher', 'HalfCheetah', 'Swimmer', 'Hopper', 'Walker2d', 'Ant', 'Humanoid', 'HumanoidStandup'], help='(Every task is currently v1.)') parser.add_argument('--alg', type=str, choices=all_algs) parser.add_argument('--nSamples', type=int, default=50) parser.add_argument('--save', type=str) parser.add_argument('--overwrite', action='store_true') args = parser.parse_args() allDir = args.save or os.path.join('output.random-search', args.task) if os.path.exists(allDir): if args.overwrite: shutil.rmtree(allDir) os.makedirs(allDir, exist_ok=True) algs = [args.alg] if args.alg is not None else all_algs np.random.seed(0) for i in range(args.nSamples): l1size = npr.randint(100, 600) l2size = npr.randint(100, l1size) hp_alg = { 'l1size': l1size, 'l2size': l2size, 'reward_k': 10.**npr.uniform(-4, 1), 'l2norm': 10.**npr.uniform(-10, -2), 'pl2norm': 10.**npr.uniform(-10, -2), 'rate': 10.**npr.uniform(-4, -1), 'prate': 10.**npr.uniform(-4, -1), 'outheta': np.maximum(1e-8, npr.normal(loc=0.15, scale=0.1)), 'ousigma': np.maximum(1e-8, npr.normal(loc=0.1, scale=0.05)), 'lrelu': 10.**npr.uniform(-4, -1), 'naf_bn': bool(npr.binomial(1, 0.5)), 'icnn_bn': bool(npr.binomial(1, 0.25)), } if hp_alg['l2norm'] < 1e-8: hp_alg['l2norm'] = 0. if hp_alg['pl2norm'] < 1e-8: hp_alg['pl2norm'] = 0. if hp_alg['lrelu'] < 1e-3: hp_alg['lrelu'] = 0. for alg in algs: algDir = os.path.join(allDir, alg) runExp(args, alg, algDir, i, hp_alg)