Python numpy.random.seed() Examples

The following are 30 code examples of numpy.random.seed(). 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: strainsimulationwrapper.py    From CAMISIM with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: test_graphs.py    From drmad with MIT License 6 votes vote down vote up
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 
Example #3
Source File: test_image.py    From neural-network-animation with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: test.py    From block with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: test_factor.py    From zipline-chinese with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: test.py    From qpth with Apache License 2.0 6 votes vote down vote up
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 
Example #7
Source File: test_helper.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: test_factor.py    From catalyst with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: rng.py    From Jacinle with MIT License 5 votes vote down vote up
def gen_rng(seed=None):
    return JacRandomState(seed) 
Example #10
Source File: iso_gan.py    From ad_examples with MIT License 5 votes vote down vote up
def set_random_seeds(py_seed=42, np_seed=42, tf_seed=42):
    random.seed(py_seed)
    rnd.seed(np_seed)
    tf.set_random_seed(tf_seed) 
Example #11
Source File: glad_support.py    From ad_examples with MIT License 5 votes vote down vote up
def set_random_seeds(py_seed=42, np_seed=42, tf_seed=42):
    random.seed(py_seed)
    rnd.seed(np_seed)
    tf.set_random_seed(tf_seed) 
Example #12
Source File: test_LogSoftMax.py    From Kayak with MIT License 5 votes vote down vote up
def test_logsoftmax_values_1():
    npr.seed(1)

    for ii in xrange(NUM_TRIALS):

        np_X = npr.randn(5,6)
        X    = kayak.Parameter(np_X)
        Y    = kayak.LogSoftMax(X)

        np_Y = np.exp(np_X)
        np_Y = np_Y / np.sum(np_Y, axis=1)[:,np.newaxis]
        np_Y = np.log(np_Y)

        assert Y.shape == np_X.shape
        assert np.all(close_float(Y.value, np_Y)) 
Example #13
Source File: test_LogSoftMax.py    From Kayak with MIT License 5 votes vote down vote up
def test_logsoftmax_values_2():
    npr.seed(2)

    for ii in xrange(NUM_TRIALS):

        np_X = npr.randn(5,6)
        X    = kayak.Parameter(np_X)
        Y    = kayak.LogSoftMax(X, axis=0)

        np_Y = np.exp(np_X)
        np_Y = np_Y / np.sum(np_Y, axis=0)[np.newaxis,:]
        np_Y = np.log(np_Y)

        assert Y.shape == np_X.shape
        assert np.all(close_float(Y.value, np_Y)) 
Example #14
Source File: rng.py    From Jacinle with MIT License 5 votes vote down vote up
def reset_global_seed(seed=None, verbose=False):
    if seed is None:
        seed = gen_seed()
    for k, seed_getter in global_rng_registry.items():
        if verbose:
            from jacinle.logging import get_logger
            logger = get_logger(__file__)
            logger.critical('Reset random seed for: {} (pid={}, seed={}).'.format(k, os.getpid(), seed))
        seed_getter()(seed) 
Example #15
Source File: rng.py    From Jacinle with MIT License 5 votes vote down vote up
def _initialize_global_seed():
    seed = os.getenv('JAC_RANDOM_SEED', None)
    if seed is not None:
        reset_global_seed(seed) 
Example #16
Source File: test_LogSoftMax.py    From Kayak with MIT License 5 votes vote down vote up
def test_logsoftmax_grad_1():
    npr.seed(3)

    for ii in xrange(NUM_TRIALS):

        np_X = npr.randn(5,6)
        X    = kayak.Parameter(np_X)
        Y    = kayak.LogSoftMax(X)
        Z    = kayak.MatSum(Y)

        assert kayak.util.checkgrad(X, Z) < MAX_GRAD_DIFF 
Example #17
Source File: test_LogSoftMax.py    From Kayak with MIT License 5 votes vote down vote up
def test_logsoftmax_grad_2():
    npr.seed(4)

    for ii in xrange(NUM_TRIALS):

        np_X = npr.randn(5,6)
        X    = kayak.Parameter(np_X)
        Y    = kayak.LogSoftMax(X, axis=0)
        Z    = kayak.MatSum(Y)

        assert kayak.util.checkgrad(X, Z) < MAX_GRAD_DIFF 
Example #18
Source File: test_factor.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def test_masked_rankdata_2d(self,
                                seed_value,
                                method,
                                use_mask,
                                set_missing,
                                ascending):
        eyemask = ~eye(5, dtype=bool)
        nomask = ones((5, 5), dtype=bool)

        seed(seed_value)
        asfloat = (randn(5, 5) * seed_value)
        asdatetime = (asfloat).copy().view('datetime64[ns]')

        mask = eyemask if use_mask else nomask
        if set_missing:
            asfloat[:, 2] = nan
            asdatetime[:, 2] = NaTns

        float_result = masked_rankdata_2d(
            data=asfloat,
            mask=mask,
            missing_value=nan,
            method=method,
            ascending=True,
        )
        datetime_result = masked_rankdata_2d(
            data=asdatetime,
            mask=mask,
            missing_value=NaTns,
            method=method,
            ascending=True,
        )

        check_arrays(float_result, datetime_result) 
Example #19
Source File: create.py    From optnet with Apache License 2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--minBps', type=int, default=1)
    parser.add_argument('--maxBps', type=int, default=10)
    parser.add_argument('--seqLen', type=int, default=100)
    parser.add_argument('--minHeight', type=int, default=10)
    parser.add_argument('--maxHeight', type=int, default=100)
    parser.add_argument('--noise', type=float, default=10)
    parser.add_argument('--nSamples', type=int, default=10000)
    parser.add_argument('--save', type=str, default='data/synthetic')
    args = parser.parse_args()

    npr.seed(0)

    save = args.save
    if os.path.isdir(save):
        shutil.rmtree(save)
    os.makedirs(save)

    X, Y = [], []
    for i in range(args.nSamples):
        Xi, Yi = sample(args)
        X.append(Xi); Y.append(Yi)
        if i == 0:
            fig, ax = plt.subplots(1, 1)
            plt.plot(Xi, label='Corrupted')
            plt.plot(Yi, label='Original')
            plt.legend()
            f = os.path.join(args.save, "example.png")
            fig.savefig(f)
            print("Created {}".format(f))

    X = np.array(X)
    Y = np.array(Y)

    for loc,arr in (('features.pt', X), ('labels.pt', Y)):
        fname = os.path.join(args.save, loc)
        with open(fname, 'wb') as f:
            torch.save(torch.Tensor(arr), f)
        print("Created {}".format(fname)) 
Example #20
Source File: gan.py    From ad_examples with MIT License 5 votes vote down vote up
def set_random_seeds(py_seed=42, np_seed=42, tf_seed=42):
    random.seed(py_seed)
    rnd.seed(np_seed)
    tf.set_random_seed(tf_seed) 
Example #21
Source File: test_dict_vectorizer.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_int_features_in_pipeline(self):

        import numpy.random as rn
        import pandas as pd

        rn.seed(0)

        x_train_dict = [
            dict((rn.randint(100), 1) for i in range(20)) for j in range(100)
        ]
        y_train = [0, 1] * 50

        from sklearn.pipeline import Pipeline
        from sklearn.feature_extraction import DictVectorizer
        from sklearn.linear_model import LogisticRegression

        pl = Pipeline([("dv", DictVectorizer()), ("lm", LogisticRegression())])
        pl.fit(x_train_dict, y_train)

        import coremltools

        model = coremltools.converters.sklearn.convert(
            pl, input_features="features", output_feature_names="target"
        )

        if _is_macos() and _macos_version() >= (10, 13):
            x = pd.DataFrame(
                {"features": x_train_dict, "prediction": pl.predict(x_train_dict)}
            )

            cur_eval_metics = evaluate_classifier(model, x)
            self.assertEquals(cur_eval_metics["num_errors"], 0) 
Example #22
Source File: test_imputer.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_conversion_boston(self):

        from sklearn.datasets import load_boston

        scikit_data = load_boston()

        sh = scikit_data.data.shape

        rn.seed(0)
        missing_value_indices = [
            (rn.randint(sh[0]), rn.randint(sh[1])) for k in range(sh[0])
        ]

        for strategy in ["mean", "median", "most_frequent"]:
            for missing_value in [0, "NaN", -999]:

                X = np.array(scikit_data.data).copy()

                for i, j in missing_value_indices:
                    X[i, j] = missing_value

                model = Imputer(missing_values=missing_value, strategy=strategy)
                model = model.fit(X)

                tr_X = model.transform(X.copy())

                spec = converter.convert(model, scikit_data.feature_names, "out")

                input_data = [dict(zip(scikit_data.feature_names, row)) for row in X]

                output_data = [{"out": row} for row in tr_X]

                result = evaluate_transformer(spec, input_data, output_data)

                assert result["num_errors"] == 0 
Example #23
Source File: _test_utils.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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") 
Example #24
Source File: regression_base.py    From imylu with Apache License 2.0 5 votes vote down vote up
def fit(self, data: ndarray, label: ndarray, learning_rate: float, epochs: int,
            method="batch", sample_rate=1.0, random_state=None):
        """Train regression model.

        Arguments:
            data {ndarray} -- Training data.
            label {ndarray} -- Target values.
            learning_rate {float} -- Learning rate.
            epochs {int} -- Number of epochs to update the gradient.

        Keyword Arguments:
            method {str} -- "batch" or "stochastic" (default: {"batch"})
            sample_rate {float} -- Between 0 and 1 (default: {1.0})
            random_state {int} -- The seed used by the random number generator. (default: {None})
        """

        assert method in ("batch", "stochastic"), str(method)

        # Batch gradient descent.
        if method == "batch":
            self._batch_gradient_descent(data, label, learning_rate, epochs)

        # Stochastic gradient descent.
        if method == "stochastic":
            self._stochastic_gradient_descent(
                data, label, learning_rate, epochs, sample_rate, random_state) 
Example #25
Source File: batch_utils.py    From Neural-Chatbot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, questions, answers, vocabulary, batch_size, sequence_length, one_hot_target, stream=False):
        random.seed(0)
        self.sequence_length = sequence_length
        self.vocabulary = vocabulary
        self.batch_size = batch_size
        self.one_hot_target = one_hot_target
        self.stream = stream

        self.questions = questions
        self.answers = answers
        self.inverse_vocabulary = dict((word, i) for i, word in enumerate(self.vocabulary)) 
Example #26
Source File: test_token_swapper.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def setUp(self) -> None:
        """Set up test cases."""
        random.seed(0) 
Example #27
Source File: eval_iteration.py    From pddm with Apache License 2.0 5 votes vote down vote up
def main():

    #############################
    ## vars to specify for eval
    #############################

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--job_path', type=str,
        default='../output/cheetah')  #address this WRT working directory
    parser.add_argument('--iter_num', type=int, default=0)
    parser.add_argument('--num_eval_rollouts', type=int, default=3)
    parser.add_argument('--eval_run_length', type=int, default=-1)
    parser.add_argument('--gpu_frac', type=float, default=0.9)
    parser.add_argument('--use_ground_truth_dynamics', action="store_true")
    parser.add_argument('--execute_sideRollouts', action="store_true")
    parser.add_argument('--use_gpu', action="store_true")
    parser.add_argument('--seed', type=int, default=0)
    args = parser.parse_args()

    #directory to load from
    save_dir = os.path.abspath(args.job_path)
    assert os.path.isdir(save_dir)

    ##########################
    ## run evaluation
    ##########################

    try:
        run_eval(args, save_dir)
    except (KeyboardInterrupt, SystemExit):
        print('Terminating...')
        sys.exit(0)
    except Exception as e:
        print('ERROR: Exception occured while running a job....')
        traceback.print_exc() 
Example #28
Source File: neuralnet.py    From PySigmoid with MIT License 5 votes vote down vote up
def __init__(self):
        # Seed the random number generator, so it generates the same numbers
        # every time the program runs.
        random.seed(1)

        # We model a single neuron, with 3 input connections and 1 output connection.
        # We assign random weights to a 3 x 1 matrix, with values in the range -1 to 1
        # and mean 0.
        self.synaptic_weights = 2 * random.random((3, 1)) - 1
        self.synaptic_weights = posify(self.synaptic_weights)

    # The Sigmoid function, which describes an S shaped curve.
    # We pass the weighted sum of the inputs through this function to
    # normalise them between 0 and 1. 
Example #29
Source File: argumenthandler.py    From CAMISIM with Apache License 2.0 5 votes vote down vote up
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 
Example #30
Source File: test_matfuncs.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_matrix_power_operator(self):
        random.seed(1234)
        n = 5
        k = 2
        p = 3
        nsamples = 10
        for i in range(nsamples):
            A = np.random.randn(n, n)
            B = np.random.randn(n, k)
            op = MatrixPowerOperator(A, p)
            assert_allclose(op.matmat(B), matrix_power(A, p).dot(B))
            assert_allclose(op.T.matmat(B), matrix_power(A, p).T.dot(B))