numpy.random.randint

Here are the examples of the python api numpy.random.randint taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

9085 Examples 7

5 Source : test_binaural.py
with MIT License
from DrMarc

def test_drr():
    for _ in range(10):
        steepness = numpy.random.randint(1, 3)
        duration = numpy.random.uniform(2.0, 8.0)
        decay_resolution = 10
        decay_curve = [numpy.exp(-i * steepness) for i in range(decay_resolution)]
        sound = slab.Binaural.whitenoise(kind='dichotic', duration=duration, samplerate=44100)
        impulse = sound.envelope(apply_envelope=decay_curve)
        winlength = numpy.random.uniform(0.0001, 0.01)
        if numpy.random.randint(0, 2):
            winlength = max(2, impulse.in_samples(winlength, impulse.samplerate))
        if numpy.random.randint(0, 2):
            drr = impulse.drr(winlength=winlength)
        else:
            drr = impulse.drr()
        assert 0 > drr > -100
        assert isinstance(drr, float)

5 Source : test_psychoacoustics.py
with MIT License
from DrMarc

def test_sequence_from_trials():
    for i in range(100):  # generate from integers
        start = numpy.random.randint(1, 100)
        stop = start+numpy.random.randint(1, 10)
        trials = [numpy.random.randint(start, stop) for i in range(100)]
        sequence = slab.Trialsequence(trials=trials)
        assert all(numpy.unique(sequence.trials) == numpy.array(range(1, sequence.n_conditions+1)))
    trials = ["a", "x", "x", "z", "a", "a", "a", "z"]
    sequence = slab.Trialsequence(trials=trials)
    assert all(numpy.unique(sequence.trials) == numpy.array(range(1, sequence.n_conditions + 1)))
    sounds = [slab.Sound.pinknoise(), slab.Sound.whitenoise()]
    trials = [random.choice(sounds) for i in range(50)]
    sequence = slab.Trialsequence(trials=trials)
    assert all(numpy.unique(sequence.trials) == numpy.array(range(1, sequence.n_conditions + 1)))


def test_sequence():

5 Source : test_signal.py
with MIT License
from DrMarc

def test_signal_generation():
    # (numpy.ndarray | object | list)
    for _ in range(100):
        n_samples = numpy.random.randint(100, 10000)
        n_channels = numpy.random.randint(1, 10)
        samplerate = numpy.random.randint(10, 1000)
        sig = slab.Signal(numpy.random.randn(n_samples, n_channels), samplerate)
        assert sig.n_channels == n_channels
        assert sig.n_samples == n_samples
        assert sig.samplerate == samplerate
        assert len(sig.times) == len(sig.data)
        numpy.testing.assert_almost_equal(sig.times.max()*samplerate, n_samples, decimal=-1)


def test_arithmetics():

5 Source : test_signal.py
with MIT License
from DrMarc

def test_arithmetics():
    for _ in range(100):
        n_samples = numpy.random.randint(100, 10000)
        n_channels = numpy.random.randint(1, 10)
        samplerate = numpy.random.randint(10, 1000)
        sig = slab.Signal(numpy.random.randn(n_samples, n_channels), samplerate=samplerate)
        numpy.testing.assert_equal((sig+sig).data, (sig*2).data)
        numpy.testing.assert_equal((sig-sig).data, numpy.zeros([n_samples, n_channels]))
        numpy.testing.assert_equal((sig*sig).data, sig**2)


def test_samplerate():

5 Source : test_signal.py
with MIT License
from DrMarc

def test_channels():
    for _ in range(100):
        n_samples = numpy.random.randint(100, 10000)
        n_channels = numpy.random.randint(1, 10)
        samplerate = numpy.random.randint(10, 1000)
        sig = slab.Signal(numpy.random.randn(n_samples, n_channels), samplerate=samplerate)
        for i, ch in enumerate(sig.channels()):
            numpy.testing.assert_equal(sig.channel(i).data, ch.data)


def test_resize():

5 Source : test_signal.py
with MIT License
from DrMarc

def test_trim():
    for _ in range(100):
        n_samples = numpy.random.randint(100, 10000)
        n_channels = numpy.random.randint(1, 10)
        samplerate = numpy.random.randint(10, 1000)
        sig = slab.Signal(numpy.random.randn(n_samples, n_channels), samplerate=samplerate)
        start, stop = numpy.sort(numpy.random.randint(0, n_samples+1, 2))
        if start == stop:
            start -= 1
        if numpy.random.rand()   <   0.5:
            trimmed = sig.trim(start=start, stop=stop)
        else:
            trimmed = sig.trim(start=start/samplerate, stop=stop/samplerate)
        assert numpy.abs(trimmed.n_samples - (stop-start))  < = 1
    with pytest.raises(ValueError):  # testing start not preceding stop case
        trimmed = sig.trim(start=stop, stop=start)


def test_resample():

3 Source : room_agent.py
with MIT License
from 011235813

    def reset(self, randomize=False):
        if randomize:
            self.position = np.random.randint(3)
        else:
            self.position = 1
        self.total_given = np.zeros(self.n_agents - 1)

3 Source : room_symmetric_centralized.py
with MIT License
from 011235813

    def reset(self):
        self.solved = False
        self.state = (np.random.randint(3, size=self._n_agents) if
                      self.randomize else np.ones(self._n_agents, dtype=int))
        self.steps = 0
        obs = self.get_obs()

        return [obs]

3 Source : facenet.py
with MIT License
from 1024210879

def crop(image, random_crop, image_size):
    if image.shape[1]>image_size:
        sz1 = int(image.shape[1]//2)
        sz2 = int(image_size//2)
        if random_crop:
            diff = sz1-sz2
            (h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1))
        else:
            (h, v) = (0,0)
        image = image[(sz1-sz2+v):(sz1+sz2+v),(sz1-sz2+h):(sz1+sz2+h),:]
    return image
  
def flip(image, random_flip):

3 Source : 生成数据并增强.py
with Apache License 2.0
from 1044197988

def add_noise(img):
    for i in range(200): #添加点噪声
        temp_x = np.random.randint(0,img.shape[0])
        temp_y = np.random.randint(0,img.shape[1])
        img[temp_x][temp_y] = 255
    return img
    
#添加数据
def data_augment(xb,yb):

3 Source : data_augment.py
with Apache License 2.0
from 1adrianb

    def _apply_blended(self, img, mixing_weights, m):
        # This is my first crack and implementing a slightly faster mixed augmentation. Instead
        # of accumulating the mix for each chain in a Numpy array and then blending with original,
        # it recomputes the blending coefficients and applies one PIL image blend per chain.
        # TODO the results appear in the right ballpark but they differ by more than rounding.
        img_orig = img.copy()
        ws = self._calc_blended_weights(mixing_weights, m)
        for w in ws:
            depth = self.depth if self.depth > 0 else np.random.randint(1, 4)
            ops = np.random.choice(self.ops, depth, replace=True)
            img_aug = img_orig  # no ops are in-place, deep copy not necessary
            for op in ops:
                img_aug = op(img_aug)
            img = Image.blend(img, img_aug, w)
        return img

    def _apply_basic(self, img, mixing_weights, m):

3 Source : transforms.py
with MIT License
from 2han9x1a0release

def random_crop(im, size, pad_size=0):
    """Performs random crop (CHW format)."""
    if pad_size > 0:
        im = zero_pad(im=im, pad_size=pad_size)
    h, w = im.shape[1:]
    y = np.random.randint(0, h - size)
    x = np.random.randint(0, w - size)
    im_crop = im[:, y : (y + size), x : (x + size)]
    assert im_crop.shape[1:] == (size, size)
    return im_crop


def scale(size, im):

3 Source : addnoise.py
with MIT License
from 3dperceptionlab

    def __call__(self, sample):
        ff_noise_ = np.random.randint(-self.ff_noise, high=self.ff_noise, size=sample.x[:, 0].shape)
        mf_noise_ = np.random.randint(-self.mf_noise, high=self.mf_noise, size=sample.x[:, 1].shape)
        th_noise_ = np.random.randint(-self.th_noise, high=self.th_noise, size=sample.x[:, 2].shape)
        noise_ = np.array([ff_noise_, mf_noise_, th_noise_]).T

        augmented_batch_ = deepcopy(sample)
        augmented_batch_.x = augmented_batch_.x + torch.from_numpy(noise_).type(torch.FloatTensor)

        return augmented_batch_

    def __repr__(self):

3 Source : test_PlotDataItem.py
with MIT License
from 3fon3fonov

def test_bool():
    truths = np.random.randint(0, 2, size=(100,)).astype(bool)
    pdi = pg.PlotDataItem(truths)
    bounds = pdi.dataBounds(1)
    assert isinstance(bounds[0], np.uint8)
    assert isinstance(bounds[1], np.uint8)
    xdata, ydata = pdi.getData()
    assert ydata.dtype == np.uint8


def test_fft():

3 Source : train.py
with Apache License 2.0
from 5agado

def get_training_data(images, batch_size, config, warp_mult_factor=1):
    warped_images = []
    target_images = []

    indexes = np.random.randint(len(images), size=batch_size)
    for index in indexes:
        image = images[index]
        image = FaceGenerator.random_transform(image, **config['random_transform'])
        warped_img, target_img = FaceGenerator.random_warp(image, mult_f=warp_mult_factor)

        warped_images.append(warped_img)
        target_images.append(target_img)

    return np.array(warped_images), np.array(target_images)


def main(_):

3 Source : imagenet.py
with GNU General Public License v3.0
from 82magnolia

def random_shift_events(event_tensor, max_shift=20, resolution=(224, 224)):
    H, W = resolution
    x_shift, y_shift = np.random.randint(-max_shift, max_shift + 1, size=(2,))
    event_tensor[:, 0] += x_shift
    event_tensor[:, 1] += y_shift

    valid_events = (event_tensor[:, 0] >= 0) & (event_tensor[:, 0]   <   W) & (event_tensor[:, 1] >= 0) & (event_tensor[:, 1]  <  H)
    event_tensor = event_tensor[valid_events]

    return event_tensor


def random_flip_events_along_x(event_tensor, resolution=(224, 224), p=0.5):

3 Source : square_crop.py
with MIT License
from 921kiyo

def random_rot(image):
    angles = [0, 90, 180, 270]
    i = np.random.randint(0,3)
    angle = angles[i]
    return rotate(image, angle)
    

for (dirpath,_,filenames) in os.walk(src_folder):

3 Source : transformations.py
with Apache License 2.0
from 94mia

    def __call__(self, sample):
        image, label = sample['image'], sample['label']

        h, w = image.shape[:2]
        new_h, new_w = self.output_size

        top = np.random.randint(0, h - new_h)
        left = np.random.randint(0, w - new_w)

        image = image[top: top + new_h, left: left + new_w, :]

        label = label[top: top + new_h, left: left + new_w]

        sample['image'], sample['label'] = image, label

        return sample


class RandomResizedCrop(object):

3 Source : strided_window_data.py
with MIT License
from 95616ARG

def test_out_shape():
    """Tests that the out_* methods work correctly.
    """
    in_shape = (32, 64, np.random.randint(1, 128))
    out_channels = np.random.randint(1, 128)
    window_shape = (4, 2)
    strides = (3, 1)
    pad = (1, 3)
    window_data = StridedWindowData(in_shape, window_shape, strides,
                                    pad, out_channels)
    # After padding, height is 34. 
    # [0 - 4), [3 - 7), [6 - 10), ..., [30 - 34)
    assert window_data.out_height() == 11
    # After padding, width is 70. 
    # [0 - 2), [1 - 3), [2 - 4), ..., [68 - 70)
    assert window_data.out_width() == 69
    assert window_data.out_shape() == (11, 69, out_channels)

def test_serialize():

3 Source : Evaluation.py
with MIT License
from aaronworry

def initial():
    k = np.random.randint(0, 3)
    if k == 0:
        s = env.initialUp()
    elif k == 1:
        s = env.initialDown()
    else:
        s = env.initialOn()
    return s

def evalWithHardCode():

3 Source : trainAndEvalDDPG.py
with MIT License
from aaronworry

def initial():
    k = np.random.randint(0, 2)
    if k == 0:
        s = env.initialOn()
    else:
        s = env.initialDown()
    return s


def train():

3 Source : trainAndEvalStepUp.py
with MIT License
from aaronworry

def initial():
    k = np.random.randint(0, 2)
    if k == 0:
        s = env.initialOn()
    else:
        s = env.initialUp()
    return s

def train():

3 Source : trainQ.py
with MIT License
from aaronworry

def initial():
    tt = np.random.randint(0, 3)
    if tt == 0:
        s = env.initialUp()
    elif tt == 1:
        s = env.initialDown()
    else:
        s = env.initialOn()
    return s

def train():

3 Source : ant_soft_actor_critic.py
with MIT License
from abbyvansoest

    def sample_batch(self, batch_size=32):
        idxs = np.random.randint(0, self.size, size=batch_size)
        return dict(obs1=self.obs1_buf[idxs],
                    obs2=self.obs2_buf[idxs],
                    acts=self.acts_buf[idxs],
                    rews=self.rews_buf[idxs],
                    done=self.done_buf[idxs])

"""

3 Source : utils.py
with MIT License
from abduallahmohamed

def data_generator(T, mem_length, b_size):
    """
    Generate data for the copying memory task

    :param T: The total blank time length
    :param mem_length: The length of the memory to be recalled
    :param b_size: The batch size
    :return: Input and target data tensor
    """
    seq = torch.from_numpy(np.random.randint(1, 9, size=(b_size, mem_length))).float()
    zeros = torch.zeros((b_size, T))
    marker = 9 * torch.ones((b_size, mem_length + 1))
    placeholders = torch.zeros((b_size, mem_length))

    x = torch.cat((seq, zeros[:, :-1], marker), 1)
    y = torch.cat((placeholders, zeros, seq), 1).long()

    x, y = Variable(x), Variable(y)
    return x, y

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, labels=None):
        if random.randint(2):
            image[:, :, 1] *= random.uniform(self.lower, self.upper)

        return image, labels


class RandomHue(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, labels=None):
        if random.randint(2):
            image[:, :, 0] += random.uniform(-self.delta, self.delta)
            image[:, :, 0][image[:, :, 0] > 360.0] -= 360.0
            image[:, :, 0][image[:, :, 0]   <   0.0] += 360.0
        return image, labels


class SwapChannels(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, labels=None):
        if random.randint(2):
            swap = self.perms[random.randint(len(self.perms))]
            shuffle = SwapChannels(swap)  # shuffle channels
            image = shuffle(image)
        return image, labels


class ConvertColor(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, labels=None):
        if random.randint(2):
            alpha = random.uniform(self.lower, self.upper)
            image *= alpha
        return image, labels


class RandomBrightness(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, labels=None):
        if random.randint(2):
            delta = random.uniform(-self.delta, self.delta)
            image += delta
        return image, labels


class ToCV2Image(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, labels):
        im = image.copy()
        im, labels = self.rand_brightness(im, labels)
        if random.randint(2):
            distort = Compose(self.pd[:-1])
        else:
            distort = Compose(self.pd[1:])
        im, labels = distort(im, labels)
        return self.rand_light_noise(im, labels)


class SubtractMeans(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, labels):
        _, width, _ = image.shape
        if random.randint(2):
            image = image[:, ::-1]
            labels = labels[:, ::-1]
        return image, labels


class SegNetAugmentation(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, boxes=None, labels=None):
        if random.randint(2):
            image[:, :, 1] *= random.uniform(self.lower, self.upper)

        return image, boxes, labels


class RandomHue(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, boxes=None, labels=None):
        if random.randint(2):
            image[:, :, 0] += random.uniform(-self.delta, self.delta)
            image[:, :, 0][image[:, :, 0] > 360.0] -= 360.0
            image[:, :, 0][image[:, :, 0]   <   0.0] += 360.0
        return image, boxes, labels


class RandomLightingNoise(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, boxes=None, labels=None):
        if random.randint(2):
            swap = self.perms[random.randint(len(self.perms))]
            shuffle = SwapChannels(swap)  # shuffle channels
            image = shuffle(image)
        return image, boxes, labels


class ConvertColor(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, boxes=None, labels=None):
        if random.randint(2):
            alpha = random.uniform(self.lower, self.upper)
            image *= alpha
        return image, boxes, labels


class RandomBrightness(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, boxes=None, labels=None):
        if random.randint(2):
            delta = random.uniform(-self.delta, self.delta)
            image += delta
        return image, boxes, labels


class ToCV2Image(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, boxes, classes):
        _, width, _ = image.shape
        if random.randint(2):
            image = image[:, ::-1]
            boxes = boxes.copy()
            boxes[:, 0::2] = width - boxes[:, 2::-2]
        return image, boxes, classes


class SwapChannels(object):

3 Source : augmentations.py
with MIT License
from abeja-inc

    def __call__(self, image, boxes, labels):
        im = image.copy()
        im, boxes, labels = self.rand_brightness(im, boxes, labels)
        if random.randint(2):
            distort = Compose(self.pd[:-1])
        else:
            distort = Compose(self.pd[1:])
        im, boxes, labels = distort(im, boxes, labels)
        return self.rand_light_noise(im, boxes, labels)


class SSDAugmentation(object):

3 Source : contrib.py
with GNU General Public License v3.0
from acamero

    def next_solution(self):
        solution = op.Solution(self.targets,
                               ['architecture'])
        num_layers = np.random.randint(low=self.min_layers,
                                       high=(self.max_layers + 1))
        layers = np.random.randint(low=self.min_neurons,
                                   high=(self.max_neurons + 1),
                                   size=num_layers)
        look_back = np.random.randint(low=self.min_look_back,
                                      high=(self.max_look_back + 1),
                                      size=1)
        solution.set_encoded('architecture',
                             np.concatenate((look_back, layers)).tolist())
        return solution

    def validate_solution(self,

3 Source : ea.py
with GNU General Public License v3.0
from acamero

def binaryTournament(population):
    """ Binary tournament. Selects two solutions from the population
    and compare them. Returns the fittest one.
    """
    positions = np.random.randint(low=0,
                                  high=len(population),
                                  size=2)
    if population[positions[0]].comparedTo(
            population[positions[1]]) > 0:
        return deepcopy(population[positions[0]])
    else:
        return deepcopy(population[positions[1]])


def elitistPlusReplacement(population,

3 Source : algorithms.py
with GNU General Public License v3.0
from acamero

    def _init_individual(self, clazz):
        solution = list()
        # First, we define the architecture (how many layers and neurons per layer)
        ranges = [(self.config.min_neurons, self.config.max_neurons+1)] * np.random.randint(self.config.min_layers, high=self.config.max_layers+1)
        layers = [self.layer_in] + [np.random.randint(*p) for p in ranges] + [self.layer_out]
        solution.append(layers)
        # Then, the look back
        solution.append( np.random.randint(self.config.min_look_back, self.config.max_look_back+1 ) )
        solution.extend( self._generate_weights(layers) )
        return clazz(solution) 

    def _validate_individual(self, individual):

3 Source : algorithms.py
with GNU General Public License v3.0
from acamero

    def _init_individual(self, clazz):
        # range [min,max)
        ranges = [(0,100), (1, self.config.max_look_back+1)]
        ranges = ranges + [(1, self.config.max_neurons+1)] * np.random.randint(1, high=self.config.max_layers+1)
        return clazz(np.random.randint(*p) for p in ranges) 

    def _validate_individual(self, individual):

3 Source : test_image.py
with Apache License 2.0
from Accenture

def run_around_tests(tmp_path):
    """Create a temp image for test"""
    rand_img = np.random.randint(0, 255, (3, 3, 3), dtype='uint8')
    Image.fromarray(rand_img).save(os.path.join(tmp_path, _STUB_IMG_FNAME))
    yield


def test_read_image_bgr(tmp_path):

3 Source : encoding.py
with MIT License
from ace19-dev

def encoding_op(func, inp, grad, name=None, victim_op='IdentityN'):
    # Need to generate a unique name to avoid duplicates.
    rnd_name = 'my_gradient' + str(np.random.randint(0, 1E+8))
    tf.RegisterGradient(rnd_name)(grad)
    g = tf.get_default_graph()
    with g.gradient_override_map({victim_op: rnd_name}):
        return func(inp, name=name)


def encoding(X, C, S):

3 Source : multipie_3d.py
with Apache License 2.0
from achao2013

    def __call__(self, image):
        h, w = image.shape[:2]
        new_h, new_w = self.output_size

        top = np.random.randint(0, h - new_h)
        left = np.random.randint(0, w - new_w)

        cropped_image = image[top:top+new_h, left:left+new_w]

        return cropped_image, [left,top,left+new_w,top+new_h]

3 Source : transforms.py
with Apache License 2.0
from achao2013

    def random_select(img_scales):
        """Randomly select an img_scale from given candidates.

        Args:
            img_scales (list[tuple]): Images scales for selection.

        Returns:
            (tuple, int): Returns a tuple ``(img_scale, scale_dix)``, \
                where ``img_scale`` is the selected image scale and \
                ``scale_idx`` is the selected index in the given candidates.
        """

        assert deep3dmap.core.utils.is_list_of(img_scales, tuple)
        scale_idx = np.random.randint(len(img_scales))
        img_scale = img_scales[scale_idx]
        return img_scale, scale_idx

    @staticmethod

3 Source : transforms.py
with Apache License 2.0
from achao2013

    def get_indexes(self, dataset):
        """Call function to collect indexes.

        Args:
            dataset (:obj:`MultiImageMixDataset`): The dataset.

        Returns:
            list: indexes.
        """

        indexs = [random.randint(0, len(dataset)) for _ in range(3)]
        return indexs

    def _mosaic_transform(self, results):

3 Source : transforms.py
with Apache License 2.0
from achao2013

    def get_indexes(self, dataset):
        """Call function to collect indexes.

        Args:
            dataset (:obj:`MultiImageMixDataset`): The dataset.

        Returns:
            list: indexes.
        """

        for i in range(self.max_iters):
            index = random.randint(0, len(dataset))
            gt_bboxes_i = dataset.get_ann_info(index)['bboxes']
            if len(gt_bboxes_i) != 0:
                break

        return index

    def _mixup_transform(self, results):

3 Source : test_utils.py
with Apache License 2.0
from achao2013

    def test_flip_is_label(self):
        # Generate the points
        heatmaps = torch.from_numpy(np.random.randint(1, high=250, size=(68, 64, 64)).astype('float32'))

        flipped_heatmaps = flip(flip(heatmaps.clone(), is_label=True), is_label=True)

        assert np.allclose(heatmaps.numpy(), flipped_heatmaps.numpy())

    def test_flip_is_image(self):

See More Examples