Python random.Random() Examples

The following are 30 code examples for showing how to use random.Random(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module random , or try the search function .

Example 1
Project: vergeml   Author: mme   File: imagenet.py    License: MIT License 7 votes vote down vote up
def _makenet(x, num_layers, dropout, random_seed):
    from keras.layers import Dense, Dropout

    dropout_seeder = random.Random(random_seed)

    for i in range(num_layers - 1):
        # add intermediate layers
        if dropout:
            x = Dropout(dropout, seed=dropout_seeder.randint(0, 10000))(x)
        x = Dense(1024, activation="relu", name='dense_layer_{}'.format(i))(x)

    if dropout:
        # add the final dropout layer
        x = Dropout(dropout, seed=dropout_seeder.randint(0, 10000))(x)

    return x 
Example 2
Project: DOTA_models   Author: ringringyi   File: neural_programmer.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self):
    global FLAGS
    self.FLAGS = FLAGS
    self.unk_token = "UNK"
    self.entry_match_token = "entry_match"
    self.column_match_token = "column_match"
    self.dummy_token = "dummy_token"
    self.tf_data_type = {}
    self.tf_data_type["double"] = tf.float64
    self.tf_data_type["float"] = tf.float32
    self.np_data_type = {}
    self.np_data_type["double"] = np.float64
    self.np_data_type["float"] = np.float32
    self.operations_set = ["count"] + [
        "prev", "next", "first_rs", "last_rs", "group_by_max", "greater",
        "lesser", "geq", "leq", "max", "min", "word-match"
    ] + ["reset_select"] + ["print"]
    self.word_ids = {}
    self.reverse_word_ids = {}
    self.word_count = {}
    self.random = Random(FLAGS.python_seed) 
Example 3
Project: Dumb-Cogs   Author: irdumbs   File: adventure.py    License: MIT License 6 votes vote down vote up
def __init__(self, seed=None):
        Data.__init__(self)
        self.output = ''
        self.yesno_callback = False
        self.yesno_casual = False       # whether to insist they answer

        self.clock1 = 30                # counts down from finding last treasure
        self.clock2 = 50                # counts down until cave closes
        self.is_closing = False         # is the cave closing?
        self.panic = False              # they tried to leave during closing?
        self.is_closed = False          # is the cave closed?
        self.is_done = False            # caller can check for "game over"
        self.could_fall_in_pit = False  # could the player fall into a pit?

        self.random_generator = random.Random()
        if seed is not None:
            self.random_generator.seed(seed) 
Example 4
Project: razzy-spinner   Author: rafasashi   File: hmm.py    License: GNU General Public License v3.0 6 votes vote down vote up
def demo_bw():
    # demo Baum Welch by generating some sequences and then performing
    # unsupervised training on them

    print()
    print("Baum-Welch demo for market example")
    print()

    model, states, symbols = _market_hmm_example()

    # generate some random sequences
    training = []
    import random
    rng = random.Random()
    rng.seed(0)
    for i in range(10):
        item = model.random_sample(rng, 5)
        training.append([(i[0], None) for i in item])

    # train on those examples, starting with the model that generated them
    trainer = HiddenMarkovModelTrainer(states, symbols)
    hmm = trainer.train_unsupervised(training, model=model,
                                     max_iterations=1000) 
Example 5
Project: donation-tracker   Author: GamesDoneQuick   File: test_prizemail.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.rand = random.Random(None)
        self.numDonors = 20
        self.numPrizes = 40
        self.event = randgen.build_random_event(
            self.rand, num_runs=20, num_prizes=self.numPrizes, num_donors=self.numDonors
        )
        for prize in self.rand.sample(
            list(self.event.prize_set.all()), self.numPrizes // 10
        ):
            prize.key_code = True
            prize.save()
            randgen.generate_prize_key(self.rand, prize=prize).save()
        self.templateEmail = post_office.models.EmailTemplate.objects.create(
            name='testing_prize_shipping_notification',
            description='',
            subject='A Test',
            content=self.testTemplateContent,
        )
        self.sender = 'nobody@nowhere.com' 
Example 6
Project: donation-tracker   Author: GamesDoneQuick   File: test_prize.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.rand = random.Random(None)
        self.event = randgen.generate_event(self.rand)
        self.event.save()
        self.run = randgen.generate_run(self.rand, event=self.event)
        self.run.order = 1
        self.run.save()
        self.prize = randgen.generate_prize(
            self.rand,
            event=self.event,
            start_run=self.run,
            end_run=self.run,
            random_draw=True,
        )
        self.prize.key_code = True
        self.prize.save()
        models.PrizeKey.objects.bulk_create(
            randgen.generate_prize_key(self.rand, prize=self.prize) for _ in range(100)
        )
        self.prize_keys = self.prize.prizekey_set.all() 
Example 7
Project: donation-tracker   Author: GamesDoneQuick   File: test_prize.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.rand = random.Random(None)
        self.event = randgen.generate_event(self.rand, start_time=today_noon)
        self.event.save()
        randgen.generate_runs(self.rand, self.event, 1, scheduled=True)
        self.write_in_prize = randgen.generate_prizes(self.rand, self.event, 1)[0]
        self.write_in_donor = randgen.generate_donors(self.rand, 1)[0]
        models.PrizeWinner.objects.create(
            prize=self.write_in_prize, winner=self.write_in_donor, acceptcount=1
        )
        self.donation_prize = randgen.generate_prizes(self.rand, self.event, 1)[0]
        self.donation_donor = randgen.generate_donors(self.rand, 1)[0]
        models.Donation.objects.create(
            event=self.event,
            donor=self.donation_donor,
            transactionstate='COMPLETED',
            amount=5,
        )
        models.PrizeWinner.objects.create(
            prize=self.donation_prize, winner=self.donation_donor, acceptcount=1
        ) 
Example 8
Project: donation-tracker   Author: GamesDoneQuick   File: test_admin.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.rand = random.Random(None)
        self.superuser = User.objects.create_superuser(
            'superuser', 'super@example.com', 'password',
        )
        self.processor = User.objects.create(username='processor', is_staff=True)
        self.processor.user_permissions.add(
            Permission.objects.get(name='Can change donor'),
            Permission.objects.get(name='Can change donation'),
        )
        self.head_processor = User.objects.create(
            username='head_processor', is_staff=True
        )
        self.head_processor.user_permissions.add(
            Permission.objects.get(name='Can change donor'),
            Permission.objects.get(name='Can change donation'),
            Permission.objects.get(name='Can send donations to the reader'),
        )
        self.event = randgen.build_random_event(self.rand)
        self.session = self.client.session
        self.session['admin-event'] = self.event.id
        self.session.save() 
Example 9
Project: buildbot-infra   Author: buildbot   File: bb_filters.py    License: MIT License 6 votes vote down vote up
def seeded_range(seed, start, stop=None, step=1, extra=None):
    """
    A filter to produce deterministic random numbers.

    Produce a random item from range(start, stop[, step]), use the value and
    optional ``extra`` value to set the seed for the random number generator.

    Basic usage::

        ansible_fqdn|seeded_range(60)

        "hello"|seeded_range(1, 10, extra="world")
    """
    hashed_seed = new_hash('sha1')
    hashed_seed.update(seed)

    if extra is not None:
        hashed_seed.update(extra)

    hashed_seed = hashed_seed.digest()

    # We rely on randrange's interpretation of parameters
    return Random(hashed_seed).randrange(start, stop, step) 
Example 10
def PredictAnswer(ContextSummary, question, tokenizer, estimator):
    data = {'data': [{'title': 'Random',
           'paragraphs': [{'context': ContextSummary,
             'qas': [{'answers': [],
               'question': question,
               'id': '56be4db0acb8001400a502ec'}]}]}],
         'version': '1.1'}
    FLAGS.interact = True
    eval_examples = read_squad_examples(data = data, is_training=False)
    eval_features, all_results = testing_model(eval_examples, tokenizer, estimator)
    output_prediction_file = os.path.join(FLAGS.output_dir, "predictions.json")
    output_nbest_file = os.path.join(FLAGS.output_dir, "nbest_predictions.json")
    output_null_log_odds_file = os.path.join(FLAGS.output_dir, "null_odds.json")
    Prediction = write_predictions(eval_examples, eval_features, all_results,
                      FLAGS.n_best_size, FLAGS.max_answer_length,
                      FLAGS.do_lower_case, output_prediction_file,
                      output_nbest_file, output_null_log_odds_file)
    
    return list(Prediction.values())[0] 
Example 11
Project: BERT-Classification-Tutorial   Author: Socialbird-AILab   File: modeling_test.py    License: Apache License 2.0 5 votes vote down vote up
def ids_tensor(cls, shape, vocab_size, rng=None, name=None):
        """Creates a random int32 tensor of the shape within the vocab size."""
        if rng is None:
            rng = random.Random()

        total_dims = 1
        for dim in shape:
            total_dims *= dim

        values = []
        for _ in range(total_dims):
            values.append(rng.randint(0, vocab_size - 1))

        return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name) 
Example 12
Project: vergeml   Author: mme   File: test_io.py    License: MIT License 5 votes vote down vote up
def read_samples(self, split, index, n=1):
        items = self.files[split][index:index+n]
        items = [(self.read_file(filename), meta) for filename, meta in items]
        
        res = []
        for item, meta in items:
            rng = random.Random(str(self.random_seed) + meta['filename'])
            res.append(Sample(item, None, meta.copy(), rng)) 

        return res 
Example 13
Project: vergeml   Author: mme   File: test_views.py    License: MIT License 5 votes vote down vote up
def read_samples(self, split, index, n=1):
        items = self.data[split][index: index+n]
        return [Sample(item, item+5, {'meta': item}, random.Random(self.random_seed + item))
                for item in items] 
Example 14
Project: vergeml   Author: mme   File: test_data.py    License: MIT License 5 votes vote down vote up
def read_samples(self, split, index, n=1):
        items = self.files[split][index:index+n]


        items = [(Path(filename).read_text(), meta) for filename, meta in items]

        res = []
        for item, meta in items:
            rng = random.Random(str(self.random_seed) + meta['filename'])
            res.append(Sample(item, None, meta.copy(), rng))

        return res 
Example 15
Project: vergeml   Author: mme   File: test_data_conf.py    License: MIT License 5 votes vote down vote up
def read_samples(self, split, index, n=1):
        items = self.files[split][index:index+n]
        items = [(self.read_file(filename), meta) for filename, meta in items]

        res = []
        for item, meta in items:
            rng = random.Random(str(self.random_seed) + meta['filename'])
            res.append(Sample(item, None, meta.copy(), rng))

        return res 
Example 16
Project: vergeml   Author: mme   File: test_loader.py    License: MIT License 5 votes vote down vote up
def read_samples(self, split, index, n=1):
        items = self.files[split][index:index+n]
        items = [(Path(filename).read_text(), meta) for filename, meta in items]

        res = []
        for item, meta in items:
            rng = random.Random(str(self.random_seed) + meta['filename'])
            res.append(Sample(item, None, meta.copy(), rng))

        return res 
Example 17
Project: vergeml   Author: mme   File: io.py    License: MIT License 5 votes vote down vote up
def __init__(self, x: Any, y: Any, meta: dict, rng: Optional[random.Random]):
        """
        :param x: the sample data
        :param y: the ground truth
        :param meta: sample metadata, i.e. the split, the source filename
        :param rng: a per sample random generator
        """
        self.x = x
        self.y = y
        self.meta = meta
        self.rng = rng 
Example 18
Project: vergeml   Author: mme   File: io.py    License: MIT License 5 votes vote down vote up
def split(self, num_samples: int):
        """Split the dataset in train, val and test sets by percentage or absolute count.

        It works by receiving the total number of samples and a configuration
        object, and calculates an array of indices per split.:

        :param num_samples: the total number of samples

        :return: a tuple of indices for (train, val, test)
        """

        val_num = int(num_samples * self.val_perc // 100) if self.val_perc else self.val_num or 0
        test_num = int(num_samples * self.test_perc // 100) if self.test_perc else self.test_num or 0

        if val_num + test_num > num_samples:
            hint_key = None
            hint_type = None

            if self.val_num:
                hint_key = 'val'
                hint_type = 'val-split'
            elif self.test_num:
                hint_key = 'val'
                hint_type = 'test-split'

            raise VergeMLError("There are not enough samples to provide the configured number for the val and test split",
                               "If you use absolute numbers for 'val-split' or 'test-split', try to lower them",
                               help_topic='split', hint_key=hint_key, hint_type=hint_type)

        rng = random.Random(self.random_seed)
        indices = rng.sample(range(num_samples), num_samples)
        val, test, train = indices[:val_num], indices[val_num:val_num + test_num], indices[val_num + test_num:]
        return train, val, test 
Example 19
Project: vergeml   Author: mme   File: views.py    License: MIT License 5 votes vote down vote up
def __init__(self, # pylint: disable=R0913
                 loader,
                 split,
                 fetch_size=8,
                 infinite=False,
                 with_meta=False,
                 randomize=False,
                 random_seed=42,
                 transform_x=lambda x: x,
                 transform_y=lambda y: y):

        self.loader = loader
        self.split = split

        self.loader.begin_read_samples()
        self.num_samples = self.loader.num_samples(self.split)
        self.loader.end_read_samples()

        self.infinite = infinite
        self.with_meta = with_meta
        self.transform_x = transform_x
        self.transform_y = transform_y
        self.fetch_size = fetch_size
        self.rng = random.Random(random_seed) if randomize else None
        self.ixs = None

        self.current_index = 0
        self._shuffle() 
Example 20
Project: vergeml   Author: mme   File: operation.py    License: MIT License 5 votes vote down vote up
def transform(self, data: Any, rng: random.Random) -> Any:
        """Transform either x or y.

        :param data: the data to transform
        :param rng: the random generator

        :return: the transformed data

        transform() will pass in data, which can be either x or the y.
        When x and y of the same sample are processed with transform, the random number
        generator will be reset on the second call so that both pieces of data are
        processed with the same random numbers.
        """
        raise NotImplementedError 
Example 21
Project: vergeml   Author: mme   File: data.py    License: MIT License 5 votes vote down vote up
def _load_list(loader,  # pylint: disable=R0914,R0913
               random_seed,
               split,
               transform_x,
               transform_y,
               with_meta,
               randomize,
               layout):
    # pylint: disable=C0103
    res = []
    loader.begin_read_samples()

    num_samples = loader.num_samples(split)

    for sample in loader.read_samples(split, 0, num_samples):
        x, y, m = sample.x, sample.y, sample.meta
        x, y = transform_x(x), transform_y(y)
        if with_meta:
            res.append((x, y, m))
        else:
            res.append((x, y))

    loader.end_read_samples()

    if randomize:
        random.Random(random_seed).shuffle(res)

    if layout in ('lists', 'arrays'):
        res = tuple(map(list, zip(*res)))
        if not res:
            res = ([], [], []) if with_meta else ([], [])

    if layout == 'arrays':
        xs, ys, *meta = res
        res = tuple([np.array(xs), np.array(ys)] + meta)
    return res 
Example 22
Project: vergeml   Author: mme   File: image.py    License: MIT License 5 votes vote down vote up
def read_samples(self, split, index, n=1):
        items = self.files[split][index:index+n]
        items = [(open_image(filename), meta) for filename, meta in items]
        
        res = []
        for img, meta in items:
            rng = random.Random(str(self.random_seed) + meta['filename'])
            res.append(Sample(img, None, meta.copy(), rng)) 

        return res 
Example 23
Project: vergeml   Author: mme   File: labeled_image.py    License: MIT License 5 votes vote down vote up
def read_samples(self, split, index, n=1):
        items = self.files[split][index:index+n]
        items = [(open_image(filename), filename, meta) for filename, meta in items]

        res = []
        for img, filename, meta in items:
            rng = random.Random(str(self.random_seed) + meta['filename'])
            y = Labels(self.classes["files"][filename])
            res.append(Sample(img, y, meta.copy(), rng))

        return res 
Example 24
def __init__(self, save_dir, model_name, step=10, window=20, max_freq=8000, desc_file=None):
        """
        Params:
            step (int): Step size in milliseconds between windows
            window (int): FFT window size in milliseconds
            max_freq (int): Only FFT bins corresponding to frequencies between
                [0, max_freq] are returned
            desc_file (str, optional): Path to a JSON-line file that contains
                labels and paths to the audio files. If this is None, then
                load metadata right away
        """
        #calc_feat_dim returns int(0.001*window*max_freq)+1
        super(DataGenerator, self).__init__()
        # feat_dim=0.001*20*8000+1=161
        self.feat_dim = calc_feat_dim(window, max_freq)
        # 1d 161 length of array filled with zeros
        self.feats_mean = np.zeros((self.feat_dim,))
        # 1d 161 length of array filled with 1s
        self.feats_std = np.ones((self.feat_dim,))
        self.max_input_length = 0
        self.max_length_list_in_batch = []
        # 1d 161 length of array filled with random value
        #[0.0, 1.0)
        self.rng = random.Random()
        if desc_file is not None:
            self.load_metadata_from_desc_file(desc_file)
        self.step = step
        self.window = window
        self.max_freq = max_freq
        self.save_dir = save_dir
        self.model_name = model_name 
Example 25
Project: Dumb-Cogs   Author: irdumbs   File: adventure.py    License: MIT License 5 votes vote down vote up
def resume(self, obj):
        """Returns an Adventure game saved to the given file."""
        if isinstance(obj, str):
            savefile = open(obj, 'rb')
        else:
            savefile = obj
        game = pickle.loads(zlib.decompress(savefile.read()))
        if savefile is not obj:
            savefile.close()
        # Reinstate the random number generator.
        game.random_generator = random.Random()
        game.random_generator.setstate(game.random_state)
        del game.random_state
        return game 
Example 26
Project: jawfish   Author: war-and-code   File: tempfile.py    License: MIT License 5 votes vote down vote up
def rng(self):
        cur_pid = _os.getpid()
        if cur_pid != getattr(self, '_rng_pid', None):
            self._rng = _Random()
            self._rng_pid = cur_pid
        return self._rng 
Example 27
Project: razzy-spinner   Author: rafasashi   File: hmm.py    License: GNU General Public License v3.0 5 votes vote down vote up
def random_sample(self, rng, length):
        """
        Randomly sample the HMM to generate a sentence of a given length. This
        samples the prior distribution then the observation distribution and
        transition distribution for each subsequent observation and state.
        This will mostly generate unintelligible garbage, but can provide some
        amusement.

        @return:        the randomly created state/observation sequence,
                        generated according to the HMM's probability
                        distributions. The SUBTOKENS have TEXT and TAG
                        properties containing the observation and state
                        respectively.
        @rtype:         list
        @param rng:     random number generator
        @type rng:      Random (or any object with a random() method)
        @param length:  desired output length
        @type length:   int
        """

        # sample the starting state and symbol prob dists
        tokens = []
        state = self._sample_probdist(self._priors, rng.random(), self._states)
        symbol = self._sample_probdist(self._outputs[state],
                                  rng.random(), self._symbols)
        tokens.append((symbol, state))

        for i in range(1, length):
            # sample the state transition and symbol prob dists
            state = self._sample_probdist(self._transitions[state],
                                     rng.random(), self._states)
            symbol = self._sample_probdist(self._outputs[state],
                                      rng.random(), self._symbols)
            tokens.append((symbol, state))

        return tokens 
Example 28
Project: razzy-spinner   Author: rafasashi   File: hmm.py    License: GNU General Public License v3.0 5 votes vote down vote up
def demo_bw():
    # demo Baum Welch by generating some sequences and then performing
    # unsupervised training on them

    # example taken from page 381, Huang et al
    symbols = ['up', 'down', 'unchanged']
    states = ['bull', 'bear', 'static']

    def pd(values, samples):
        d = {}
        for value, item in zip(values, samples):
            d[item] = value
        return DictionaryProbDist(d)

    def cpd(array, conditions, samples):
        d = {}
        for values, condition in zip(array, conditions):
            d[condition] = pd(values, samples)
        return DictionaryConditionalProbDist(d)

    A = array([[0.6, 0.2, 0.2], [0.5, 0.3, 0.2], [0.4, 0.1, 0.5]], float64)
    A = cpd(A, states, states)
    B = array([[0.7, 0.1, 0.2], [0.1, 0.6, 0.3], [0.3, 0.3, 0.4]], float64)
    B = cpd(B, states, symbols)
    pi = array([0.5, 0.2, 0.3], float64)
    pi = pd(pi, states)

    model = HiddenMarkovModel(symbols=symbols, states=states,
                              transitions=A, outputs=B, priors=pi)

    # generate some random sequences
    training = []
    import random
    rng = random.Random()
    for i in range(10):
        item = model.random_sample(rng, 5)
        training.append([(i[0], None) for i in item])

    # train on those examples, starting with the model that generated them
    trainer = HiddenMarkovModelTrainer(states, symbols)
    hmm = trainer.train_unsupervised(training, model=model, max_iterations=1000) 
Example 29
Project: razzy-spinner   Author: rafasashi   File: hmm.py    License: GNU General Public License v3.0 5 votes vote down vote up
def random_sample(self, rng, length):
        """
        Randomly sample the HMM to generate a sentence of a given length. This
        samples the prior distribution then the observation distribution and
        transition distribution for each subsequent observation and state.
        This will mostly generate unintelligible garbage, but can provide some
        amusement.

        :return:        the randomly created state/observation sequence,
                        generated according to the HMM's probability
                        distributions. The SUBTOKENS have TEXT and TAG
                        properties containing the observation and state
                        respectively.
        :rtype:         list
        :param rng:     random number generator
        :type rng:      Random (or any object with a random() method)
        :param length:  desired output length
        :type length:   int
        """

        # sample the starting state and symbol prob dists
        tokens = []
        state = self._sample_probdist(self._priors, rng.random(), self._states)
        symbol = self._sample_probdist(self._outputs[state],
                                  rng.random(), self._symbols)
        tokens.append((symbol, state))

        for i in range(1, length):
            # sample the state transition and symbol prob dists
            state = self._sample_probdist(self._transitions[state],
                                     rng.random(), self._states)
            symbol = self._sample_probdist(self._outputs[state],
                                      rng.random(), self._symbols)
            tokens.append((symbol, state))

        return tokens 
Example 30
Project: razzy-spinner   Author: rafasashi   File: kmeans.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, num_means, distance, repeats=1,
                       conv_test=1e-6, initial_means=None,
                       normalise=False, svd_dimensions=None,
                       rng=None, avoid_empty_clusters=False):

        """
        :param  num_means:  the number of means to use (may use fewer)
        :type   num_means:  int
        :param  distance:   measure of distance between two vectors
        :type   distance:   function taking two vectors and returing a float
        :param  repeats:    number of randomised clustering trials to use
        :type   repeats:    int
        :param  conv_test:  maximum variation in mean differences before
                            deemed convergent
        :type   conv_test:  number
        :param  initial_means: set of k initial means
        :type   initial_means: sequence of vectors
        :param  normalise:  should vectors be normalised to length 1
        :type   normalise:  boolean
        :param svd_dimensions: number of dimensions to use in reducing vector
                               dimensionsionality with SVD
        :type svd_dimensions: int
        :param  rng:        random number generator (or None)
        :type   rng:        Random
        :param avoid_empty_clusters: include current centroid in computation
                                     of next one; avoids undefined behavior
                                     when clusters become empty
        :type avoid_empty_clusters: boolean
        """
        VectorSpaceClusterer.__init__(self, normalise, svd_dimensions)
        self._num_means = num_means
        self._distance = distance
        self._max_difference = conv_test
        assert not initial_means or len(initial_means) == num_means
        self._means = initial_means
        assert repeats >= 1
        assert not (initial_means and repeats > 1)
        self._repeats = repeats
        self._rng = (rng if rng else random.Random())
        self._avoid_empty_clusters = avoid_empty_clusters