当前位置: 首页>>代码示例>>Python>>正文


Python random.uniform方法代码示例

本文整理汇总了Python中numpy.random.uniform方法的典型用法代码示例。如果您正苦于以下问题:Python random.uniform方法的具体用法?Python random.uniform怎么用?Python random.uniform使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy.random的用法示例。


在下文中一共展示了random.uniform方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _validate_csr_generation_inputs

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def _validate_csr_generation_inputs(num_rows, num_cols, density,
                                    distribution="uniform"):
    """Validates inputs for csr generation helper functions
    """
    total_nnz = int(num_rows * num_cols * density)
    if density < 0 or density > 1:
        raise ValueError("density has to be between 0 and 1")

    if num_rows <= 0 or num_cols <= 0:
        raise ValueError("num_rows or num_cols should be greater than 0")

    if distribution == "powerlaw":
        if total_nnz < 2 * num_rows:
            raise ValueError("not supported for this density: %s"
                             " for this shape (%s, %s)"
                             " Please keep :"
                             " num_rows * num_cols * density >= 2 * num_rows"
                             % (density, num_rows, num_cols)) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:20,代码来源:test_utils.py

示例2: __call__

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def __call__(self, image, boxes, labels):
        if random.randint(2):
            return image, boxes, labels

        height, width, depth = image.shape
        ratio = random.uniform(1, 4)
        left = random.uniform(0, width*ratio - width)
        top = random.uniform(0, height*ratio - height)

        expand_image = np.zeros(
            (int(height*ratio), int(width*ratio), depth),
            dtype=image.dtype)
        expand_image[:, :, :] = self.mean
        expand_image[int(top):int(top + height),
                     int(left):int(left + width)] = image
        image = expand_image

        boxes = boxes.copy()
        boxes[:, :2] += (int(left), int(top))
        boxes[:, 2:] += (int(left), int(top))

        return image, boxes, labels 
开发者ID:soo89,项目名称:CSD-SSD,代码行数:24,代码来源:augmentations.py

示例3: cv_random_crop

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def cv_random_crop(img, scale_size, output_size, params=None):

    if params is None:
        height, width, _ = img.shape
        w = nprandom.uniform(0.6 * width, width)
        h = nprandom.uniform(0.6 * height, height)
        left = nprandom.uniform(width - w)
        top = nprandom.uniform(height - h)
        # convert to integer rect x1,y1,x2,y2
        rect = np.array([int(left), int(top), int(left + w), int(top + h)])
        flip = random.random()<0.5
    else:
        rect,flip = params

    img = img[rect[1]:rect[3], rect[0]:rect[2], :]

    return img, [rect, flip] 
开发者ID:gurkirt,项目名称:2D-kinectics,代码行数:19,代码来源:kinetics.py

示例4: rand_init_weights

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def rand_init_weights(L_in, L_out):
    """Initializes weight matrix with random values.

    Args:
        X (numpy.array): Features' dataset.
        L_in (int): Number of units in previous layer.
        n_hidden_layers (int): Number of units in next layer.

    Returns:
        numpy.array: Random values' matrix of conforming dimensions.
    """
    W = zeros((L_out, 1 + L_in), float64)  # plus 1 for bias term
    epsilon_init = sqrt(6) / sqrt((L_in + 1) + L_out)

    W = uniform(size=(L_out, 1 + L_in)) * 2 * epsilon_init - epsilon_init
    return W 
开发者ID:Benardi,项目名称:touvlo,代码行数:18,代码来源:sgl_parm.py

示例5: testConv1DLayer

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def testConv1DLayer():

    rng = numpy.random.RandomState()

    input = T.tensor3('input')

    #windowSize = 3
    n_in = 4
    n_hiddens = [10,10,5]
    #convR = Conv1DR(rng, input, n_in, n_hiddens, windowSize/2)
    convLayer = Conv1DLayer(rng, input, n_in, 5, halfWinSize=1)
    
    #f = theano.function([input],convR.output)    
    #f = theano.function([input],[convLayer.output, convLayer.out2, convLayer.convout, convLayer.out3])    
    f = theano.function([input], convLayer.output)    

    numOfProfiles=6
    seqLen = 10
    profile = numpy.random.uniform(0,1, (numOfProfiles, seqLen,n_in))
    
    out = f(profile)
    print out.shape
    print out 
开发者ID:j3xugit,项目名称:RaptorX-Contact,代码行数:25,代码来源:Conv1d.py

示例6: __call__

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def __call__(self, image, polygons=None):
        if np.random.randint(2):
            return image, polygons

        height, width, depth = image.shape
        ratio = np.random.uniform(1, 2)
        left = np.random.uniform(0, width * ratio - width)
        top = np.random.uniform(0, height * ratio - height)

        expand_image = np.zeros(
          (int(height * ratio), int(width * ratio), depth),
          dtype=image.dtype)
        expand_image[:, :, :] = self.fill
        expand_image[int(top):int(top + height),
        int(left):int(left + width)] = image
        image = expand_image

        if polygons is not None:
            for polygon in polygons:
                polygon.points[:, 0] = polygon.points[:, 0] + left
                polygon.points[:, 1] = polygon.points[:, 1] + top
        return image, polygons 
开发者ID:princewang1994,项目名称:TextSnake.pytorch,代码行数:24,代码来源:augmentation.py

示例7: test_risk_adjusted_metrics

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def test_risk_adjusted_metrics():
    # Returns from the portfolio (r) and market (m)
    r = nrand.uniform(-1, 1, 50)
    m = nrand.uniform(-1, 1, 50)
    # Expected return
    e = numpy.mean(r)
    # Risk free rate
    f = 0.06
    # Risk-adjusted return based on Volatility
    print("Treynor Ratio =", treynor_ratio(e, r, m, f))
    print("Sharpe Ratio =", sharpe_ratio(e, r, f))
    print("Information Ratio =", information_ratio(r, m))
    # Risk-adjusted return based on Value at Risk
    print("Excess VaR =", excess_var(e, r, f, 0.05))
    print("Conditional Sharpe Ratio =", conditional_sharpe_ratio(e, r, f, 0.05))
    # Risk-adjusted return based on Lower Partial Moments
    print("Omega Ratio =", omega_ratio(e, r, f))
    print("Sortino Ratio =", sortino_ratio(e, r, f))
    print("Kappa 3 Ratio =", kappa_three_ratio(e, r, f))
    print("Gain Loss Ratio =", gain_loss_ratio(r))
    print("Upside Potential Ratio =", upside_potential_ratio(r))
    # Risk-adjusted return based on Drawdown risk
    print("Calmar Ratio =", calmar_ratio(e, r, f))
    print("Sterling Ratio =", sterling_ration(e, r, f, 5))
    print("Burke Ratio =", burke_ratio(e, r, f, 5)) 
开发者ID:naripok,项目名称:cryptotrader,代码行数:27,代码来源:risk.py

示例8: __call__

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def __call__(self,img, attr_idx):
        if attr_idx not in self.select:
            return img, attr_idx

        h, w, _ = img.shape
        area = h * w
        for attempt in range(10):
            s = random.uniform(self.scale[0], self.scale[1])
            d = 0.25 + (0.45 - 0.25) / (self.scale[1] - self.scale[0]) * (s - self.scale[0])
            target_area = s * area

            new_w = int(round(math.sqrt(target_area)))
            new_h = int(round(math.sqrt(target_area)))

            if new_w < w and new_h < h:
                dw = w-new_w
                dh = h - new_h
                x0 = random.randint(int((0.5-d)*dw), min(int((0.5+d)*dw)+1,dw))
                y0 = (random.randint(max(0,int(0.8*dh)-1), dh))
                out = fixed_crop(img, x0, y0, new_w, new_h, self.size)
                return out, attr_idx

        # Fallback
        return bottom_crop(img, self.size), attr_idx 
开发者ID:KaiJin1995,项目名称:ZSL2018_Zero_Shot_Learning,代码行数:26,代码来源:transforms_self.py

示例9: __call__

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def __call__(self, image, boxes, labels):
        if random.randint(5):
            return image, boxes, labels

        height, width, depth = image.shape
        ratio = random.uniform(1, 4)
        left = random.uniform(0, width*ratio - width)
        top = random.uniform(0, height*ratio - height)

        expand_image = np.zeros(
            (int(height*ratio), int(width*ratio), depth),
            dtype=image.dtype)
        expand_image[:, :, :] = self.mean
        expand_image[int(top):int(top + height),
                     int(left):int(left + width)] = image
        image = expand_image

        boxes = boxes.copy()
        boxes[:, :2] += (int(left), int(top))
        boxes[:, 2:] += (int(left), int(top))

        return image, boxes, labels 
开发者ID:lijiannuist,项目名称:lightDSFD,代码行数:24,代码来源:augmentations.py

示例10: get_random_params

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def get_random_params(self, num=1):
        """Generate random sets of model parameters in the default bounds.

        Samples num values for each model parameter from a uniform distribution
        between the default bounds.
        
        Args:
            num: (optional) Integer, specifying the number of parameter sets,
                that will be generated. Default is 1.
        
        Returns:
            A numpy array of the models custom data type, containing the at
            random generated parameters.

        """
        params = np.zeros(num, dtype=self._dtype)
        # sample one value for each parameter
        for param in self._param_list:
            values = uniform(low=self._default_bounds[param][0],
                             high=self._default_bounds[param][1],
                             size=num)
            params[param] = values

        return params 
开发者ID:kratzert,项目名称:RRMPG,代码行数:26,代码来源:basemodel.py

示例11: _get_uniform_dataset_csr

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def _get_uniform_dataset_csr(num_rows, num_cols, density=0.1, dtype=None,
                             data_init=None, shuffle_csr_indices=False):
    """Returns CSRNDArray with uniform distribution
    This generates a csr matrix with totalnnz unique randomly chosen numbers
    from num_rows*num_cols and arranges them in the 2d array in the
    following way:
    row_index = (random_number_generated / num_rows)
    col_index = random_number_generated - row_index * num_cols
    """
    _validate_csr_generation_inputs(num_rows, num_cols, density,
                                    distribution="uniform")
    try:
        from scipy import sparse as spsp
        csr = spsp.rand(num_rows, num_cols, density, dtype=dtype, format="csr")
        if data_init is not None:
            csr.data.fill(data_init)
        if shuffle_csr_indices is True:
            shuffle_csr_column_indices(csr)
        result = mx.nd.sparse.csr_matrix((csr.data, csr.indices, csr.indptr),
                                         shape=(num_rows, num_cols), dtype=dtype)
    except ImportError:
        assert(data_init is None), \
               "data_init option is not supported when scipy is absent"
        assert(not shuffle_csr_indices), \
               "shuffle_csr_indices option is not supported when scipy is absent"
        # scipy not available. try to generate one from a dense array
        dns = mx.nd.random.uniform(shape=(num_rows, num_cols), dtype=dtype)
        masked_dns = dns * (dns < density)
        result = masked_dns.tostype('csr')
    return result 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:32,代码来源:test_utils.py

示例12: compare_optimizer

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def compare_optimizer(opt1, opt2, shape, dtype, w_stype='default', g_stype='default',
                      rtol=1e-4, atol=1e-5, compare_states=True):
    """Compare opt1 and opt2."""
    if w_stype == 'default':
        w2 = mx.random.uniform(shape=shape, ctx=default_context(), dtype=dtype)
        w1 = w2.copyto(default_context())
    elif w_stype == 'row_sparse' or w_stype == 'csr':
        w2 = rand_ndarray(shape, w_stype, density=1, dtype=dtype)
        w1 = w2.copyto(default_context()).tostype('default')
    else:
        raise Exception("type not supported yet")
    if g_stype == 'default':
        g2 = mx.random.uniform(shape=shape, ctx=default_context(), dtype=dtype)
        g1 = g2.copyto(default_context())
    elif g_stype == 'row_sparse' or g_stype == 'csr':
        g2 = rand_ndarray(shape, g_stype, dtype=dtype)
        g1 = g2.copyto(default_context()).tostype('default')
    else:
        raise Exception("type not supported yet")

    state1 = opt1.create_state_multi_precision(0, w1)
    state2 = opt2.create_state_multi_precision(0, w2)
    if compare_states:
        compare_ndarray_tuple(state1, state2)

    opt1.update_multi_precision(0, w1, g1, state1)
    opt2.update_multi_precision(0, w2, g2, state2)
    if compare_states:
        compare_ndarray_tuple(state1, state2, rtol=rtol, atol=atol)
    assert_almost_equal(w1.asnumpy(), w2.asnumpy(), rtol=rtol, atol=atol) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:32,代码来源:test_utils.py

示例13: fun

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def fun(self, x, *args):
        self.nfev += 1

        rnd = uniform(0.0, 1.0, size=(self.N, ))
        i = arange(1, self.N + 1)

        return sum(rnd * abs(x - 1.0 / i)) 
开发者ID:msu-coinlab,项目名称:pymoo,代码行数:9,代码来源:go_funcs_S.py

示例14: __call__

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def __call__(self, img, boxes, labels):
        if random.randint(2):
            return img, boxes, labels

        h, w, c = img.shape
        ratio = random.uniform(self.min_ratio, self.max_ratio)
        expand_img = np.full((int(h * ratio), int(w * ratio), c),
                             self.mean).astype(img.dtype)
        left = int(random.uniform(0, w * ratio - w))
        top = int(random.uniform(0, h * ratio - h))
        expand_img[top:top + h, left:left + w] = img
        img = expand_img
        boxes += np.tile((left, top), 2)
        return img, boxes, labels 
开发者ID:dingjiansw101,项目名称:AerialDetection,代码行数:16,代码来源:extra_aug.py

示例15: _appendix_c

# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import uniform [as 别名]
def _appendix_c(self):
        q = npr.uniform(0, self._avg_deg - math.sqrt(self._avg_deg))
        p = self._k * self._avg_deg - q
        if random.random() < 0.5:
            return p, q
        else:
            return q, p 
开发者ID:dmlc,项目名称:dgl,代码行数:9,代码来源:sbm.py


注:本文中的numpy.random.uniform方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。