當前位置: 首頁>>代碼示例>>Python>>正文


Python random.uniform方法代碼示例

本文整理匯總了Python中random.uniform方法的典型用法代碼示例。如果您正苦於以下問題:Python random.uniform方法的具體用法?Python random.uniform怎麽用?Python random.uniform使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在random的用法示例。


在下文中一共展示了random.uniform方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __call__

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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)) 
開發者ID:jthsieh,項目名稱:DDPAE-video-prediction,代碼行數:26,代碼來源:video_transforms.py

示例2: random_size_crop

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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) 
開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:25,代碼來源:opencv.py

示例3: augment_hsv

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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 
開發者ID:zbyuan,項目名稱:pruning_yolov3,代碼行數:23,代碼來源:datasets.py

示例4: sample

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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() 
開發者ID:StanfordVL,項目名稱:robosuite,代碼行數:18,代碼來源:demo_sampler_wrapper.py

示例5: fake_responses

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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'] 
開發者ID:deis,項目名稱:controller,代碼行數:21,代碼來源:__init__.py

示例6: add_cleanup_pod

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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) 
開發者ID:deis,項目名稱:controller,代碼行數:20,代碼來源:mock.py

示例7: get_params

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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 
開發者ID:PistonY,項目名稱:torch-toolbox,代碼行數:22,代碼來源:transforms.py

示例8: random_resize

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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 
開發者ID:fab-jul,項目名稱:L3C-PyTorch,代碼行數:20,代碼來源:import_train_images.py

示例9: __call__

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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)) 
開發者ID:uci-cbcl,項目名稱:DeepLung,代碼行數:27,代碼來源:transforms.py

示例10: spec_augment

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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 
開發者ID:lRomul,項目名稱:argus-freesound,代碼行數:25,代碼來源:transforms.py

示例11: random

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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
    ) 
開發者ID:tensortrade-org,項目名稱:tensortrade,代碼行數:22,代碼來源:parameters.py

示例12: __call__

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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 
開發者ID:uvipen,項目名稱:Yolo-v2-pytorch,代碼行數:27,代碼來源:data_augmentation.py

示例13: __init__

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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 
開發者ID:gcallah,項目名稱:indras_net,代碼行數:9,代碼來源:segregation.py

示例14: __init__

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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() 
開發者ID:gcallah,項目名稱:indras_net,代碼行數:15,代碼來源:standing_ovation.py

示例15: create_rholder

# 需要導入模塊: import random [as 別名]
# 或者: from random import uniform [as 別名]
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}) 
開發者ID:gcallah,項目名稱:indras_net,代碼行數:35,代碼來源:cap_struct.py


注:本文中的random.uniform方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。