当前位置: 首页>>代码示例>>Python>>正文


Python random.seed方法代码示例

本文整理汇总了Python中numpy.random.seed方法的典型用法代码示例。如果您正苦于以下问题:Python random.seed方法的具体用法?Python random.seed怎么用?Python random.seed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy.random的用法示例。


在下文中一共展示了random.seed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _get_simulate_cmd

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def _get_simulate_cmd(self, directory_strains, filepath_genome, filepath_gff):
		"""
		Get system command to start simulation. Change directory to the strain directory and start simulating strains.

		@param directory_strains: Directory for the simulated strains
		@type directory_strains: str | unicode
		@param filepath_genome: Genome to get simulated strains of
		@type filepath_genome: str | unicode
		@param filepath_gff: gff file with gene annotations
		@type filepath_gff: str | unicode

		@return: System command line
		@rtype: str
		"""
		cmd_run_simujobrun = "cd {dir}; {executable} {filepath_genome} {filepath_gff} {seed}" + " >> {log}"
		cmd = cmd_run_simujobrun.format(
			dir=directory_strains,
			executable=self._executable_sim,
			filepath_genome=filepath_genome,
			filepath_gff=filepath_gff,
			seed=self._get_seed(),
			log=os.path.join(directory_strains, os.path.basename(filepath_genome) + ".sim.log")
		)
		return cmd 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:26,代码来源:strainsimulationwrapper.py

示例2: test_np

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def test_np():
    npr.seed(0)

    nx, nineq, neq = 4, 6, 7
    Q = npr.randn(nx, nx)
    G = npr.randn(nineq, nx)
    A = npr.randn(neq, nx)
    D = np.diag(npr.rand(nineq))

    K_ = np.bmat((
        (Q, np.zeros((nx, nineq)), G.T, A.T),
        (np.zeros((nineq, nx)), D, np.eye(nineq), np.zeros((nineq, neq))),
        (G, np.eye(nineq), np.zeros((nineq, nineq + neq))),
        (A, np.zeros((neq, nineq + nineq + neq)))
    ))

    K = block((
        (Q,   0, G.T, A.T),
        (0,   D, 'I',   0),
        (G, 'I',   0,   0),
        (A,   0,   0,   0)
    ))

    assert np.allclose(K_, K) 
开发者ID:bamos,项目名称:block,代码行数:26,代码来源:test.py

示例3: get_grads

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def get_grads(nBatch=1, nz=10, neq=1, nineq=3, Qscale=1.,
              Gscale=1., hscale=1., Ascale=1., bscale=1.):
    assert(nBatch == 1)
    npr.seed(1)
    L = np.random.randn(nz, nz)
    Q = Qscale * L.dot(L.T)
    G = Gscale * npr.randn(nineq, nz)
    # h = hscale*npr.randn(nineq)
    z0 = npr.randn(nz)
    s0 = npr.rand(nineq)
    h = G.dot(z0) + s0
    A = Ascale * npr.randn(neq, nz)
    # b = bscale*npr.randn(neq)
    b = A.dot(z0)

    p = npr.randn(nBatch, nz)
    # print(np.linalg.norm(p))
    truez = npr.randn(nBatch, nz)

    Q, p, G, h, A, b, truez = [x.astype(np.float64) for x in
                               [Q, p, G, h, A, b, truez]]
    _, zhat, nu, lam, slacks = qp_cvxpy.forward_single_np(Q, p[0], G, h, A, b)

    grads = get_grads_torch(Q, p, G, h, A, b, truez)
    return [p[0], Q, G, h, A, b, truez], grads 
开发者ID:locuslab,项目名称:qpth,代码行数:27,代码来源:test.py

示例4: test_imsave_color_alpha

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def test_imsave_color_alpha():
    # Test that imsave accept arrays with ndim=3 where the third dimension is
    # color and alpha without raising any exceptions, and that the data is
    # acceptably preserved through a save/read roundtrip.
    from numpy import random
    random.seed(1)
    data = random.rand(256, 128, 4)

    buff = io.BytesIO()
    plt.imsave(buff, data)

    buff.seek(0)
    arr_buf = plt.imread(buff)

    # Recreate the float -> uint8 -> float32 conversion of the data
    data = (255*data).astype('uint8').astype('float32')/255
    # Wherever alpha values were rounded down to 0, the rgb values all get set
    # to 0 during imsave (this is reasonable behaviour).
    # Recreate that here:
    for j in range(3):
        data[data[:, :, 3] == 0, j] = 1

    assert_array_equal(data, arr_buf) 
开发者ID:miloharper,项目名称:neural-network-animation,代码行数:25,代码来源:test_image.py

示例5: test_next_opt_len

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def test_next_opt_len(self):
        random.seed(1234)

        def nums():
            for j in range(1, 1000):
                yield j
            yield 2**5 * 3**5 * 4**5 + 1

        for n in nums():
            m = next_fast_len(n)
            msg = "n=%d, m=%d" % (n, m)

            assert_(m >= n, msg)

            # check regularity
            k = m
            for d in [2, 3, 5]:
                while True:
                    a, b = divmod(k, d)
                    if b == 0:
                        k = a
                    else:
                        break
            assert_equal(k, 1, err_msg=msg) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:26,代码来源:test_helper.py

示例6: test_hess_vector_prod

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def test_hess_vector_prod():
    npr.seed(1)
    randv = npr.randn(10)
    def fun(x):
        return np.sin(np.dot(x, randv))
    df = grad(fun)
    def vector_product(x, v):
        return np.sin(np.dot(v, df(x)))
    ddf = grad(vector_product)
    A = npr.randn(10)
    B = npr.randn(10)
    check_grads(fun, A)
    check_grads(vector_product, A, B)

# TODO:
# Grad three or more, wrt different args
# Diamond patterns
# Taking grad again after returning const
# Empty functions
# 2nd derivatives with fanout, thinking about the outgrad adder 
开发者ID:bigaidream-projects,项目名称:drmad,代码行数:22,代码来源:test_graphs.py

示例7: test_returns

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def test_returns(self, seed_value, window_length):

        returns = Returns(window_length=window_length)

        today = datetime64(1, 'ns')
        assets = arange(3)
        out = empty((3,), dtype=float)

        seed(seed_value)  # Seed so we get deterministic results.
        test_data = abs(randn(window_length, 3))

        # Calculate the expected returns
        expected = (test_data[-1] - test_data[0]) / test_data[0]

        out = empty((3,), dtype=float)
        returns.compute(today, assets, out, test_data)

        check_allclose(expected, out) 
开发者ID:zhanghan1990,项目名称:zipline-chinese,代码行数:20,代码来源:test_factor.py

示例8: _read_options

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def _read_options(self, options):
        """
        Read passed arguments.

        @rtype: None
        """
        if not self._validator.validate_file(options.config_file, key='-c'):
            self._valid_arguments = False
            return
        self._file_path_config = self._validator.get_full_path(options.config_file)
        self._verbose = not options.silent
        self._debug = options.debug_mode
        self._phase = options.phase
        self._dataset_id = options.data_set_id
        self._max_processors = options.max_processors
        self._seed = options.seed
        # self._directory_output = options.output_directory
        # self._sample_size_in_base_pairs = options.sample_size_gbp
        # if self._sample_size_in_base_pairs is not None:
        #     self._sample_size_in_base_pairs = long(options.sample_size_gbp * self._base_pairs_multiplication_factor)
        # self.read_simulator = options.read_simulator
        # self._error_profile = options.error_profile
        # self._fragment_size_standard_deviation_in_bp = options.fragment_size_standard_deviation
        # self._fragments_size_mean_in_bp = options.fragments_size_mean
        # self.plasmid_file = options.plasmid_file
        # self._number_of_samples = options.number_of_samples
        # self._phase_pooled_gsa = options.pooled_gsa 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:29,代码来源:argumenthandler.py

示例9: generate_input

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def generate_input(args):
    global _log
    _log = logger(verbose = args.debug)
    np_rand.seed(args.seed)
    #MAX_RANK = args.maxrank
    config = ConfigParser()
    config.read(args.config)
    try:
        max_strains = int(config.get("Main", max_strains_per_otu))
    except:
        max_strains = 3 # no max_strains have been set for this community - use cami value
        _log.warning("Max strains per OTU not set, using default (3)")
    try:
        mu = int(config.get("Main", "log_mu"))
        sigma = int(config.get("Main", "log_sigma"))
    except:
        mu = 1
        sigma = 2 # this aint particularily beatiful
        _log.warning("Mu and sigma have not been set, using defaults (1,2)") #TODO 
    tax_profile = read_taxonomic_profile(args.profile, config, args.samples)
    genomes_map, total_genomes = read_genomes_list(args.reference_genomes, args.additional_references)
    per_rank_map = get_genomes_per_rank(genomes_map, RANKS, MAX_RANK)
    otu_genome_map, unmatched_otus, per_rank_map = map_otus_to_genomes(tax_profile, per_rank_map, RANKS, MAX_RANK, mu, sigma, max_strains, args.debug, args.no_replace, total_genomes)
    if (args.fill_up and len(unmatched_otus) > 0):
        otu_genome_map = fill_up_genomes(otu_genome_map, unmatched_otus, per_rank_map, tax_profile, args.debug)
    cfg_path = write_config(otu_genome_map, genomes_map, args.o, config)
    _log.info("Community design finished")
    _log = None
    return cfg_path 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:31,代码来源:get_genomes.py

示例10: setup_tensorflow

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def setup_tensorflow():
    # Create session
    config = tf.ConfigProto(log_device_placement=FLAGS.log_device_placement)
    sess = tf.Session(config=config)

    # Initialize rng with a deterministic seed
    with sess.graph.as_default():
        tf.set_random_seed(FLAGS.random_seed)
        
    random.seed(FLAGS.random_seed)
    np.random.seed(FLAGS.random_seed)

    summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph)

    return sess, summary_writer 
开发者ID:david-gpu,项目名称:srez,代码行数:17,代码来源:srez_main.py

示例11: test_linear_operator

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def test_linear_operator():
    npr.seed(0)

    nx, nineq, neq = 4, 6, 7
    Q = npr.randn(nx, nx)
    G = npr.randn(nineq, nx)
    A = npr.randn(neq, nx)
    D = np.diag(npr.rand(nineq))

    K_ = np.bmat((
        (Q, np.zeros((nx, nineq)), G.T, A.T),
        (np.zeros((nineq, nx)), D, np.eye(nineq), np.zeros((nineq, neq))),
        (G, np.eye(nineq), np.zeros((nineq, nineq + neq))),
        (A, np.zeros((neq, nineq + nineq + neq)))
    ))

    Q_lo = sla.aslinearoperator(Q)
    G_lo = sla.aslinearoperator(G)
    A_lo = sla.aslinearoperator(A)
    D_lo = sla.aslinearoperator(D)

    K = block((
        (Q_lo,    0,    G.T,    A.T),
        (0,    D_lo,    'I',      0),
        (G_lo,  'I',      0,      0),
        (A_lo,    0,      0,      0)
    ), arrtype=sla.LinearOperator)

    w1 = np.random.randn(K_.shape[1])
    assert np.allclose(K_.dot(w1), K.dot(w1))
    w2 = np.random.randn(K_.shape[0])
    assert np.allclose(K_.T.dot(w2), K.H.dot(w2))
    W = np.random.randn(*K_.shape)
    assert np.allclose(K_.dot(W), K.dot(W)) 
开发者ID:bamos,项目名称:block,代码行数:36,代码来源:test.py

示例12: _random_array

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def _random_array(shape, random_seed=10):  # type: (Tuple[int, ...], Any) -> np._ArrayLike[float]
    if random_seed:
        npr.seed(random_seed) # type: ignore
    return npr.ranf(shape).astype("float32") 
开发者ID:onnx,项目名称:onnx-coreml,代码行数:6,代码来源:_test_utils.py

示例13: setup_class

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def setup_class(cls):
        R.seed(54321)
        cls.X = R.standard_normal((40,10)) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:5,代码来源:test_contrast.py

示例14: logistic_regression_chain

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def logistic_regression_chain(x, t, N_iter=100, stepsize=1, th0=1, q=0.1, y0=1, seed=None):

    # Set seed
    npr.seed(seed)

    # Obtain joint distributions over z and th and set step functions
    model = ff.LogisticModel(x, t, th0=th0, y0=y0)
    z__stepper = ff.zStepMH(model.log_pseudo_lik , q)
    th_stepper = ff.ThetaStepMH(model.log_p_joint, stepsize)

    # Initialize
    N, D = x.shape
    th = np.random.randn(D)*th0
    z = ff.BrightnessVars(N)

    # run chain
    th_chain = np.zeros((N_iter,  ) +  th.shape)
    z_chain  = np.zeros((N_iter, N), dtype=bool)

    for i in range(N_iter):
        th = th_stepper.step(th, z)
        z  = z__stepper.step(th ,z)
        # Record the intermediate results
        th_chain[i,:] = th.copy()
        z_chain[i,z.bright] = 1

    print "th0 = ", th0, "frac accepted is", th_stepper.frac_accepted,  "bright frac is:", np.mean(z_chain)
    return th_chain, z_chain 
开发者ID:HIPS,项目名称:firefly-monte-carlo,代码行数:30,代码来源:chain_generators.py

示例15: main

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import seed [as 别名]
def main(args):
    print args

    if args.seed >= 0:
        seed = args.seed
    else:
        seed = int(time.time()*1000) % 9999
    print "seed:", seed
    random.seed(seed)

    model = None
    if args.train:
        vocabx, vocaby = Pipe.create_vocabulary(args)
        if args.embedding:
            vocabx, embeddings = Pipe.load_embeddings(args)
        train_x, train_y = Pipe.read_corpus(args.train, args, vocabx, vocaby)
        if args.dev:
            dev_x, dev_y = Pipe.read_corpus(args.dev, args, vocabx, vocaby)
        if args.test:
            test_x, test_y = Pipe.read_corpus(args.test, args, vocabx, vocaby)
        model = ConvModel(
                  args = args,
                  vocabx = vocabx,
                  vocaby = vocaby
            )
        model.ready( embeddings if args.embedding else None )
        model.train(
                (train_x, train_y),
                (dev_x, dev_y) if args.dev else None,
                (test_x, test_y) if args.test else None,
            ) 
开发者ID:taolei87,项目名称:text_convnet,代码行数:33,代码来源:model.py


注:本文中的numpy.random.seed方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。