Python random.uniform() Examples

The following are 30 code examples for showing how to use random.uniform(). 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: pruning_yolov3   Author: zbyuan   File: datasets.py    License: GNU General Public License v3.0 7 votes vote down vote up
def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
    x = (np.random.uniform(-1, 1, 3) * np.array([hgain, sgain, vgain]) + 1).astype(np.float32)  # random gains
    img_hsv = (cv2.cvtColor(img, cv2.COLOR_BGR2HSV) * x.reshape((1, 1, 3))).clip(None, 255).astype(np.uint8)
    cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)  # no return needed


# def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):  # original version
#     # SV augmentation by 50%
#     img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)  # hue, sat, val
#
#     S = img_hsv[:, :, 1].astype(np.float32)  # saturation
#     V = img_hsv[:, :, 2].astype(np.float32)  # value
#
#     a = random.uniform(-1, 1) * sgain + 1
#     b = random.uniform(-1, 1) * vgain + 1
#     S *= a
#     V *= b
#
#     img_hsv[:, :, 1] = S if a < 1 else S.clip(None, 255)
#     img_hsv[:, :, 2] = V if b < 1 else V.clip(None, 255)
#     cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)  # no return needed 
Example 2
Project: DDPAE-video-prediction   Author: jthsieh   File: video_transforms.py    License: MIT License 6 votes vote down vote up
def __call__(self, video):
    for attempt in range(10):
      area = video.shape[-3]*video.shape[-2]
      target_area = random.uniform(0.08, 1.0)*area
      aspect_ratio = random.uniform(3./4, 4./3)

      w = int(round(math.sqrt(target_area*aspect_ratio)))
      h = int(round(math.sqrt(target_area/aspect_ratio)))

      if random.random() < 0.5:
        w, h = h, w

      if w <= video.shape[-2] and h <= video.shape[-3]:
        x1 = random.randint(0, video.shape[-2]-w)
        y1 = random.randint(0, video.shape[-3]-h)

        video = video[..., y1:y1+h, x1:x1+w, :]

        return resize(video, (self.size, self.size), self.interpolation)

    # Fallback
    scale = Scale(self.size, interpolation=self.interpolation)
    crop = CenterCrop(self.size)
    return crop(scale(video)) 
Example 3
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: opencv.py    License: Apache License 2.0 6 votes vote down vote up
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)):
    """Randomly crop src with size. Randomize area and aspect ratio"""
    h, w, _ = src.shape
    area = w*h
    for _ in range(10):
        new_area = random.uniform(min_area, 1.0) * area
        new_ratio = random.uniform(*ratio)
        new_w = int(new_area*new_ratio)
        new_h = int(new_area/new_ratio)

        if random.uniform(0., 1.) < 0.5:
            new_w, new_h = new_h, new_w

        if new_w > w or new_h > h:
            continue

        x0 = random.randint(0, w - new_w)
        y0 = random.randint(0, h - new_h)

        out = fixed_crop(src, x0, y0, new_w, new_h, size)
        return out, (x0, y0, new_w, new_h)

    return random_crop(src, size) 
Example 4
Project: robosuite   Author: StanfordVL   File: demo_sampler_wrapper.py    License: MIT License 6 votes vote down vote up
def sample(self):
        """
        This is the core sampling method. Samples a state from a
        demonstration, in accordance with the configuration.
        """

        # chooses a sampling scheme randomly based on the mixing ratios
        seed = random.uniform(0, 1)
        ratio = np.cumsum(self.scheme_ratios)
        ratio = ratio > seed
        for i, v in enumerate(ratio):
            if v:
                break

        sample_method = getattr(self, self.sample_method_dict[self.sampling_schemes[i]])
        return sample_method() 
Example 5
Project: controller   Author: deis   File: __init__.py    License: MIT License 6 votes vote down vote up
def fake_responses(request, context):
    responses = [
        # increasing the chance of 404
        {'text': 'Not Found', 'status_code': 404},
        {'text': 'Not Found', 'status_code': 404},
        {'text': 'Not Found', 'status_code': 404},
        {'text': 'Not Found', 'status_code': 404},
        {'text': 'OK', 'status_code': 200},
        {'text': 'Gateway timeout', 'status_code': 504},
        {'text': 'Bad gateway', 'status_code': 502},
    ]
    random.shuffle(responses)
    response = responses.pop()

    context.status_code = response['status_code']
    context.reason = response['text']
    # Random float x, 1.0 <= x < 4.0 for some sleep jitter
    time.sleep(random.uniform(1, 4))
    return response['text'] 
Example 6
Project: controller   Author: deis   File: mock.py    License: MIT License 6 votes vote down vote up
def add_cleanup_pod(url):
    """populate the cleanup pod list"""
    # variance allows a pod to stay alive past grace period
    variance = random.uniform(0.1, 1.5)
    grace = round(settings.KUBERNETES_POD_TERMINATION_GRACE_PERIOD_SECONDS * variance)

    # save
    pods = cache.get('cleanup_pods', {})
    pods[url] = (datetime.utcnow() + timedelta(seconds=grace))
    cache.set('cleanup_pods', pods)

    # add grace period timestamp
    pod = cache.get(url)
    grace = settings.KUBERNETES_POD_TERMINATION_GRACE_PERIOD_SECONDS
    pd = datetime.utcnow() + timedelta(seconds=grace)
    timestamp = str(pd.strftime(MockSchedulerClient.DATETIME_FORMAT))
    pod['metadata']['deletionTimestamp'] = timestamp
    cache.set(url, pod) 
Example 7
Project: torch-toolbox   Author: PistonY   File: transforms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_params(img, scale, ratio):

        if type(img) == np.ndarray:
            img_h, img_w, img_c = img.shape
        else: 
            img_h, img_w = img.size
            img_c = len(img.getbands())

        s = random.uniform(*scale)
        # if you img_h != img_w you may need this.
        # r_1 = max(r_1, (img_h*s)/img_w)
        # r_2 = min(r_2, img_h / (img_w*s))
        r = random.uniform(*ratio)
        s = s * img_h * img_w
        w = int(math.sqrt(s / r))
        h = int(math.sqrt(s * r))
        left = random.randint(0, img_w - w)
        top = random.randint(0, img_h - h)

        return left, top, h, w, img_c 
Example 8
Project: L3C-PyTorch   Author: fab-jul   File: import_train_images.py    License: GNU General Public License v3.0 6 votes vote down vote up
def random_resize(im, min_res: int, max_scale=_DEFAULT_MAX_SCALE):
    """Scale longer side to `min_res`, but only if that scales by <= max_scale."""
    W, H = im.size
    D = min(W, H)
    scale_min = min_res / D
    # Image is too small to downscale by a factor smaller MAX_SCALE.
    if scale_min > max_scale:
        return None

    # Get a random scale for new size.
    scale = random.uniform(scale_min, max_scale)
    new_size = round(W * scale), round(H * scale)
    try:
        # Using LANCZOS!
        return im.resize(new_size, resample=PIL.Image.LANCZOS)
    except OSError as e:  # Happens for corrupted images
        print('*** Caught im.resize error', e)
        return None 
Example 9
Project: DeepLung   Author: uci-cbcl   File: transforms.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, img):
        for attempt in range(10):
            area = img.size[0] * img.size[1]
            target_area = random.uniform(0.08, 1.0) * area
            aspect_ratio = random.uniform(3. / 4, 4. / 3)

            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))

            if random.random() < 0.5:
                w, h = h, w

            if w <= img.size[0] and h <= img.size[1]:
                x1 = random.randint(0, img.size[0] - w)
                y1 = random.randint(0, img.size[1] - h)

                img = img.crop((x1, y1, x1 + w, y1 + h))
                assert(img.size == (w, h))

                return img.resize((self.size, self.size), self.interpolation)

        # Fallback
        scale = Scale(self.size, interpolation=self.interpolation)
        crop = CenterCrop(self.size)
        return crop(scale(img)) 
Example 10
Project: argus-freesound   Author: lRomul   File: transforms.py    License: MIT License 6 votes vote down vote up
def spec_augment(spec: np.ndarray,
                 num_mask=2,
                 freq_masking=0.15,
                 time_masking=0.20,
                 value=0):
    spec = spec.copy()
    num_mask = random.randint(1, num_mask)
    for i in range(num_mask):
        all_freqs_num, all_frames_num  = spec.shape
        freq_percentage = random.uniform(0.0, freq_masking)

        num_freqs_to_mask = int(freq_percentage * all_freqs_num)
        f0 = np.random.uniform(low=0.0, high=all_freqs_num - num_freqs_to_mask)
        f0 = int(f0)
        spec[f0:f0 + num_freqs_to_mask, :] = value

        time_percentage = random.uniform(0.0, time_masking)

        num_frames_to_mask = int(time_percentage * all_frames_num)
        t0 = np.random.uniform(low=0.0, high=all_frames_num - num_frames_to_mask)
        t0 = int(t0)
        spec[:, t0:t0 + num_frames_to_mask] = value
    return spec 
Example 11
Project: tensortrade   Author: tensortrade-org   File: parameters.py    License: Apache License 2.0 6 votes vote down vote up
def random(base_price, t_gen, delta):
    return ModelParameters(
        all_s0=base_price,
        all_r0=0.5,
        all_time=t_gen,
        all_delta=delta,
        all_sigma=uniform(0.1, 0.8),
        gbm_mu=uniform(-0.3, 0.6),
        jumps_lamda=uniform(0.0071, 0.6),
        jumps_sigma=uniform(-0.03, 0.04),
        jumps_mu=uniform(-0.2, 0.2),
        cir_a=3.0,
        cir_mu=0.5,
        cir_rho=0.5,
        ou_a=3.0,
        ou_mu=0.5,
        heston_a=uniform(1, 5),
        heston_mu=uniform(0.156, 0.693),
        heston_vol0=0.06125
    ) 
Example 12
Project: Yolo-v2-pytorch   Author: uvipen   File: data_augmentation.py    License: MIT License 6 votes vote down vote up
def __call__(self, data):
        image, label = data
        height, width = image.shape[:2]
        xmin = width
        ymin = height
        xmax = 0
        ymax = 0
        for lb in label:
            xmin = min(xmin, lb[0])
            ymin = min(ymin, lb[1])
            xmax = max(xmax, lb[2])
            ymax = max(ymax, lb[2])
        cropped_left = uniform(0, self.max_crop)
        cropped_right = uniform(0, self.max_crop)
        cropped_top = uniform(0, self.max_crop)
        cropped_bottom = uniform(0, self.max_crop)
        new_xmin = int(min(cropped_left * width, xmin))
        new_ymin = int(min(cropped_top * height, ymin))
        new_xmax = int(max(width - 1 - cropped_right * width, xmax))
        new_ymax = int(max(height - 1 - cropped_bottom * height, ymax))

        image = image[new_ymin:new_ymax, new_xmin:new_xmax, :]
        label = [[lb[0] - new_xmin, lb[1] - new_ymin, lb[2] - new_xmin, lb[3] - new_ymin, lb[4]] for lb in label]

        return image, label 
Example 13
Project: indras_net   Author: gcallah   File: segregation.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, goal, min_tol, max_tol, max_move=100,
                 max_detect=1):
        super().__init__(name, goal, max_move=max_move, max_detect=max_detect)
        self.tolerance = random.uniform(max_tol, min_tol)
        self.stance = None
        self.orientation = None
        self.visible_pre = None 
Example 14
Project: indras_net   Author: gcallah   File: standing_ovation.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, goal, noise):
        super().__init__(name, goal, 2, SITTING)
        self.name = name
        self.goal = goal
        self.noise = noise
        self.state = SITTING
        self.standard = random.uniform(0.4, 1.0)
        self.ntype = self.state
        self.next_state = STANDING
        self.changed = False
        self.pressure = 0

        self.reaction() 
Example 15
Project: indras_net   Author: gcallah   File: cap_struct.py    License: GNU General Public License v3.0 5 votes vote down vote up
def create_rholder(name, i, props=None):
    """
    Create an agent.
    """
    k_price = DEF_K_PRICE
    resources = copy.deepcopy(DEF_CAP_WANTED)
    num_resources = len(resources)

    price_list = copy.deepcopy(DEF_EACH_CAP_PRICE)
    if props is not None:
        k_price = props.get('cap_price',
                            DEF_K_PRICE)
        for k in price_list.keys():
            price_list[k] = float("{0:.2f}".format(float(k_price
                                                   * random.uniform(0.5,
                                                                    1.5))))

    starting_cash = DEF_RHOLDER_CASH
    if props is not None:
        starting_cash = get_prop('rholder_starting_cash',
                                 DEF_RHOLDER_CASH)

    if props is not None:
        total_resources = get_prop('rholder_starting_resource_total',
                                   DEF_TOTAL_RESOURCES_RHOLDER_HAVE)
        for k in resources.keys():
            resources[k] = int((total_resources * 2)
                               * (random.random() / num_resources))

    return Agent(name + str(i), action=rholder_action,
                 attrs={"cash": starting_cash,
                        "resources": resources,
                        "price": price_list}) 
Example 16
Project: ALF   Author: blackberry   File: grammr2.py    License: Apache License 2.0 5 votes vote down vote up
def choice(self):
        target = random.uniform(0, self.total)
        for w, v in zip(self.weights, self.values):
            target -= w
            if target < 0:
                return v
        raise Exception("Too much total weight? remainder is %0.2f from %0.2f total" % (target, self.total)) 
Example 17
Project: DDPAE-video-prediction   Author: jthsieh   File: video_transforms.py    License: MIT License 5 votes vote down vote up
def get_params(brightness, contrast, saturation, hue):
    """Get a randomized transform to be applied on image.
    Arguments are same as that of __init__.
    Returns:
        Transform which randomly adjusts brightness, contrast and
        saturation in a random order.
    """
    transforms = []
    if brightness > 0:
      brightness_factor = random.uniform(max(0, 1 - brightness), 1 + brightness)
      transforms.append(lambda img: F.adjust_brightness(img, brightness_factor))

    if contrast > 0:
      contrast_factor = random.uniform(max(0, 1 - contrast), 1 + contrast)
      transforms.append(lambda img: F.adjust_contrast(img, contrast_factor))

    if saturation > 0:
      saturation_factor = random.uniform(max(0, 1 - saturation), 1 + saturation)
      transforms.append(lambda img: F.adjust_saturation(img, saturation_factor))

    if hue > 0:
      hue_factor = random.uniform(-hue, hue)
      transforms.append(lambda img: F.adjust_hue(img, hue_factor))

    random.shuffle(transforms)

    return transforms 
Example 18
Project: Random-Erasing   Author: zhunzhong07   File: transforms.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, img):

        if random.uniform(0, 1) > self.probability:
            return img

        for attempt in range(100):
            area = img.size()[1] * img.size()[2]
       
            target_area = random.uniform(self.sl, self.sh) * area
            aspect_ratio = random.uniform(self.r1, 1/self.r1)

            h = int(round(math.sqrt(target_area * aspect_ratio)))
            w = int(round(math.sqrt(target_area / aspect_ratio)))

            if w < img.size()[2] and h < img.size()[1]:
                x1 = random.randint(0, img.size()[1] - h)
                y1 = random.randint(0, img.size()[2] - w)
                if img.size()[0] == 3:
                    img[0, x1:x1+h, y1:y1+w] = self.mean[0]
                    img[1, x1:x1+h, y1:y1+w] = self.mean[1]
                    img[2, x1:x1+h, y1:y1+w] = self.mean[2]
                else:
                    img[0, x1:x1+h, y1:y1+w] = self.mean[0]
                return img

        return img 
Example 19
Project: Random-Erasing   Author: zhunzhong07   File: test_progress.py    License: Apache License 2.0 5 votes vote down vote up
def sleep():
    t = 0.01
    t += t * random.uniform(-0.1, 0.1)  # Add some variance
    time.sleep(t) 
Example 20
Project: CAMISIM   Author: CAMI-challenge   File: strainsimulationwrapper.py    License: Apache License 2.0 5 votes vote down vote up
def _get_genome_amounts_geometric(probability, max_genome_amount, geometric_probability=0.3):
		"""
		Get amounts of genomes by original genome

		@param probability: Proportion of simulated original genomes
		@type probability: int | long | float
		@param max_genome_amount: Total number of genomes
		@type max_genome_amount: int | long

		@return: List of integers representing amount of strains
		@rtype: list[int]
		"""
		assert isinstance(probability, (int, long, float))
		assert 0 <= probability <= 1
		assert isinstance(max_genome_amount, (int, long))

		final_amounts = []
		while sum(final_amounts) < max_genome_amount:
			if random.uniform(0, 1) < probability:
				final_amounts.append(1)
			else:
				amount = 1 + np_random.geometric(geometric_probability)
				final_amounts.append(amount)

		final_amounts[-1] -= sum(final_amounts) - max_genome_amount
		return final_amounts 
Example 21
Project: CAMISIM   Author: CAMI-challenge   File: strainsimulationwrapper.py    License: Apache License 2.0 5 votes vote down vote up
def _get_genome_amounts_uniform(probability, max_genome_amount):
		"""
		Get amounts of genomes by original genome

		@param probability: Proportion of simulated original genomes
		@type probability: int | long | float
		@param max_genome_amount: Total number of genomes
		@type max_genome_amount: int | long

		@return: List of integers representing amount of strains
		@rtype: list[int]
		"""
		assert isinstance(probability, (int, long, float))
		assert 0 <= probability <= 1
		assert isinstance(max_genome_amount, (int, long))

		final_amounts = []
		while sum(final_amounts) < max_genome_amount:
			if random.uniform(0, 1) < probability:
				final_amounts.append(1)
			else:
				amount = 1 + random.randint(1, 3)
				final_amounts.append(amount)

		final_amounts[-1] -= sum(final_amounts) - max_genome_amount
		return final_amounts 
Example 22
Project: deep-learning-note   Author: wdxtub   File: 49_word2vec.py    License: MIT License 5 votes vote down vote up
def discard(idx):
    return random.uniform(0, 1) < 1 - math.sqrt(
        1e-4 / counter[idx_to_token[idx]] * num_tokens
    ) 
Example 23
Project: DeepLab_v3_plus   Author: songdejia   File: transform.py    License: MIT License 5 votes vote down vote up
def __call__(self, sample):
        img = sample['image']
        mask = sample['label']
        assert img.size == mask.size
        for attempt in range(10):
            area = img.size[0] * img.size[1]
            target_area = random.uniform(0.45, 1.0) * area
            aspect_ratio = random.uniform(0.5, 2)

            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))

            if random.random() < 0.5:
                w, h = h, w

            if w <= img.size[0] and h <= img.size[1]:
                x1 = random.randint(0, img.size[0] - w)
                y1 = random.randint(0, img.size[1] - h)

                img = img.crop((x1, y1, x1 + w, y1 + h))
                mask = mask.crop((x1, y1, x1 + w, y1 + h))
                assert (img.size == (w, h))

                img = img.resize((self.size, self.size), Image.BILINEAR)
                mask = mask.resize((self.size, self.size), Image.NEAREST)

                return {'image': img,
                        'label': mask}

        # Fallback
        scale = Scale(self.size)
        crop = CenterCrop(self.size)
        sample = crop(scale(sample))
        return sample 
Example 24
Project: DeepLab_v3_plus   Author: songdejia   File: transform.py    License: MIT License 5 votes vote down vote up
def __call__(self, sample):
        img = sample['image']
        mask = sample['label']
        assert img.size == mask.size

        #w = int(random.uniform(0.8, 2.5) * img.size[0])
        #h = int(random.uniform(0.8, 2.5) * img.size[1])
        scale = random.uniform(0.8, 2.5)
        w = int(scale * img.size[0])
        h = int(scale * img.size[1])

        img, mask = img.resize((w, h), Image.BILINEAR), mask.resize((w, h), Image.NEAREST)
        sample = {'image': img, 'label': mask}

        return self.crop(self.scale(sample)) 
Example 25
Project: DeepLab_v3_plus   Author: songdejia   File: transform.py    License: MIT License 5 votes vote down vote up
def __call__(self, sample):
        img = sample['image']
        mask = sample['label']
        assert img.size == mask.size

        scale = random.uniform(self.limit[0], self.limit[1])
        w = int(scale * img.size[0])
        h = int(scale * img.size[1])

        img, mask = img.resize((w, h), Image.BILINEAR), mask.resize((w, h), Image.NEAREST)

        return {'image': img, 'label': mask} 
Example 26
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: detection.py    License: Apache License 2.0 5 votes vote down vote up
def _random_pad_proposal(self, label, height, width):
        """Generate random padding region"""
        from math import sqrt
        if not self.enabled or height <= 0 or width <= 0:
            return ()
        min_area = self.area_range[0] * height * width
        max_area = self.area_range[1] * height * width
        for _ in range(self.max_attempts):
            ratio = random.uniform(*self.aspect_ratio_range)
            if ratio <= 0:
                continue
            h = int(round(sqrt(min_area / ratio)))
            max_h = int(round(sqrt(max_area / ratio)))
            if round(h * ratio) < width:
                h = int((width + 0.499999) / ratio)
            if h < height:
                h = height
            if h > max_h:
                h = max_h
            if h < max_h:
                h = random.randint(h, max_h)
            w = int(round(h * ratio))
            if (h - height) < 2 or (w - width) < 2:
                continue  # marginal padding is not helpful

            y = random.randint(0, max(0, h - height))
            x = random.randint(0, max(0, w - width))
            new_label = self._update_labels(label, (x, y, w, h), height, width)
            return (x, y, w, h, new_label)
        return () 
Example 27
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: image.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, src):
        """Augmenter body"""
        alpha = 1.0 + random.uniform(-self.brightness, self.brightness)
        src *= alpha
        return src 
Example 28
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: image.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, src):
        """Augmenter body"""
        alpha = 1.0 + random.uniform(-self.saturation, self.saturation)
        gray = src * self.coef
        gray = nd.sum(gray, axis=2, keepdims=True)
        gray *= (1.0 - alpha)
        src *= alpha
        src += gray
        return src 
Example 29
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: image.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, src):
        """Augmenter body.
        Using approximate linear transfomation described in:
        https://beesbuzz.biz/code/hsv_color_transforms.php
        """
        alpha = random.uniform(-self.hue, self.hue)
        u = np.cos(alpha * np.pi)
        w = np.sin(alpha * np.pi)
        bt = np.array([[1.0, 0.0, 0.0],
                       [0.0, u, -w],
                       [0.0, w, u]])
        t = np.dot(np.dot(self.ityiq, bt), self.tyiq).T
        src = nd.dot(src, nd.array(t))
        return src 
Example 30
def gen_rsp_random_indices(shape, density=.5, force_indices=None):
    assert density >= 0 and density <= 1
    indices = set()
    if force_indices is not None:
        for val in force_indices:
            indices.add(int(val))
    if not np.isclose(density, .0, rtol=1.e-3, atol=1.e-3, equal_nan=True) and len(shape) > 0:
        row_count = shape[0]
        for i in range(row_count):
            r = random.uniform(0, 1)
            if r <= density and len(indices) < shape[0]:
                indices.add(i)
    assert len(indices) <= shape[0]
    return list(indices)