Python numpy.random 模块,random_sample() 实例源码

我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用numpy.random.random_sample()

项目:inductive-pooling    作者:HUJI-Deep    | 项目源码 | 文件源码
def corrupt_image(img, MAR_prob=0, min_rects=0, max_rects=0, min_width=0, max_width=0):
    new_img = img.copy()
    mask = np.zeros(img.shape[0:2], dtype=np.bool)
    if MAR_prob > 0:
        mask[(random_sample(mask.shape) < MAR_prob)] = True
    if max_rects > 0 and max_width > 0:
        h, w = mask.shape
        num_rects = random_integers(min_rects, max_rects)
        for i in range(num_rects):
            px1 = random_integers(0, w - min(max(min_width, 1), w))
            py1 = random_integers(0, h - min(max(min_width, 1), h))
            px2 = px1 + (min_width - 1) + random_integers(0, max(min(w - px1 - min_width, max_width - min_width), 0));
            py2 = py1 + (min_width - 1) + random_integers(0, max(min(h - py1 - min_width, max_width - min_width), 0));
            if px1 <= px2 and py1 <= py2:
                mask[py1:py2, px1:px2] = True
            else:
                # One of the sides has length 0, so we should remove any pixels4
                pass
    if len(new_img.shape) == 2:
        new_img[mask] = 0
    else:
        new_img[mask,:] = 0
    return (new_img, 1.0 * mask)

# Process command line inputs
项目:comprehend    作者:Fenugreek    | 项目源码 | 文件源码
def sample_h_given_v(self, v):
        """
        Given visible unit values, sample hidden unit values.

        Note: implemented in numpy for efficiency.
              Do not use in computation graph.
        """

        mean_h = sigmoid(np.dot(v, self.params['W'].eval()) + self.params['bhid'].eval())
        rnds = random_sample(mean_h.shape)
        return (mean_h > rnds).astype(np.float32)
项目:comprehend    作者:Fenugreek    | 项目源码 | 文件源码
def sample_v_given_h(self, h):
        """
        Given hidden unit values, sample visible unit values.

        Note: implemented in numpy for efficiency.
              Do not use in computation graph.
        """

        mean_v = sigmoid(np.dot(h, self.params['W'].eval().T) +
                         self.params['bvis'].eval())
        rnds = random_sample(mean_v.shape)
        return (mean_v > rnds).astype(np.float32)
项目:Generative-ConvACs    作者:HUJI-Deep    | 项目源码 | 文件源码
def corrupt_image(img, MAR_prob=0, min_rects=0, max_rects=0, min_width=0, max_width=0, apply_to_all_channels=False):
    def generate_channel_mask():
        mask = np.zeros(img.shape[0:2], dtype=np.bool)
        if MAR_prob > 0:
            mask[(random_sample(mask.shape) < MAR_prob)] = True
        if max_rects > 0 and max_width > 0:
            h, w = mask.shape
            num_rects = random_integers(min_rects, max_rects)
            for i in range(num_rects):
                px1 = random_integers(0, w - min(max(min_width, 1), w))
                py1 = random_integers(0, h - min(max(min_width, 1), h))
                px2 = px1 + min_width + random_integers(0, max(min(w - px1 - min_width, max_width - min_width), 0));
                py2 = py1 + min_width + random_integers(0, max(min(h - py1 - min_width, max_width - min_width), 0));
                if px1 <= px2 and py1 <= py2:
                    mask[py1:py2, px1:px2] = True
                else:
                    # One of the sides has length 0, so we should remove any pixels4
                    pass
        return mask
    new_img = img.copy()
    channels = 1 if len(new_img.shape) == 2 else new_img.shape[-1]
    global_mask = np.zeros(img.shape, dtype=np.bool)
    if channels == 1 or apply_to_all_channels:
        mask = generate_channel_mask()
        if channels == 1:
            global_mask[:, :] = mask
        else:
            for i in xrange(channels):
                global_mask[:, :, i] = mask
    else:
        global_mask = np.zeros(img.shape, dtype=np.bool)
        for i in xrange(channels):
            global_mask[:,:,i] = generate_channel_mask()
    new_img[global_mask] = 0
    return (new_img, 1.0 * global_mask)

# Process command line inputs
项目:support    作者:KwatME    | 项目源码 | 文件源码
def simulate_df(n_rows,
                n_cols,
                n_categories=None,
                index_prefix='Index ',
                column_prefix='Column ',
                random_seed=RANDOM_SEED):
    """
    Simulate DataFrame.
    Arguments:
        n_rows (int): number of rows
        n_cols (int): number of columns
        n_categories (None | int): None (for continuous) | int (for categorical)
        index_prefix (str): prefix for index
        column_prefix (str): prefix for column
        random_seed (int | array):
    Returns:
        DataFrame: (n_rows, n_cols)
    """

    seed(random_seed)

    if n_categories:
        df = DataFrame(randint(0, n_categories, (n_rows, n_cols)))

    else:
        df = DataFrame(random_sample((n_rows, n_cols)))

    df.index = ['{}{}'.format(index_prefix, i) for i in range(n_rows)]
    df.columns = ['{}{}'.format(column_prefix, i) for i in range(n_cols)]

    return df
项目:support    作者:KwatME    | 项目源码 | 文件源码
def simulate_series(size,
                    n_categories=None,
                    name='Simulated Series',
                    index_prefix='Index ',
                    random_seed=RANDOM_SEED):
    """
    Simulate a Series.
    Arguments:
        size (int): size
        n_categories (None | int): None for continuous and int for categorical
        index_prefix (str): index prefix
        random_seed (int | array):
    Returns;
        Series: (size)
    """

    seed(random_seed)

    if n_categories:
        series = Series(randint(low=0, high=n_categories - 1, size=size))

    else:
        series = Series(random_sample(size))

    series.name = name

    series.index = ['{}{}'.format(index_prefix, i) for i in range(size)]

    return series
项目:lddmm-ot    作者:jeanfeydy    | 项目源码 | 文件源码
def wolfe_line_search(self, fun, search_dir, curr_value, exp_decrease) :
        """
        see Numerical Optimization,
        Nocedal and Wright, Algorithm 3.5, p. 60
        """
        f =  lambda t : fun(self.after_step(t * search_dir))[0]
        fp = lambda t : self.scal_L2(fun(self.after_step(t * search_dir))[1], search_dir).Q0
        exit_code = 0 # Default : everything is all right


        # Code to uncomment to check that fp is the true derivative of f========
        h = 1e-8
        for i in range(5) :
            t = random_sample()
            update_th = fp(t)
            update_emp = (f(t+h) - f(t-h)) / (2*h)
            print('')
            print('search dir : ', search_dir.to_array())
            print('Checking the function passed to the Wolfe line search, t = ', t)
            print('Empirical   derivative : ', update_emp)
            print('Theoretical derivative : ', update_th)

        #=======================================================================



        print("Exp decrease : ", exp_decrease)
        (a, _, _, _, _, _) = line_search(f, fp, 0, 1, exp_decrease, curr_value, c2 = 0.95)
        if a == None :
            print('Error during the wolfe line search')
            a = 0
            exit_code = 1 # Exit_code = 1 : break !
        step = a * search_dir
        new_state = self.after_step(step)
        self.set_state(new_state)
        #self.current_cost_grad = (C,grad)
        #self.is_current_cost_computed = True
        self.is_current_point_computed = False
        return (step, exit_code)
项目:adventures-in-ml-code    作者:adventuresinML    | 项目源码 | 文件源码
def setup_and_init_weights(nn_structure):
    W = {}
    b = {}
    for l in range(1, len(nn_structure)):
        W[l] = r.random_sample((nn_structure[l], nn_structure[l-1]))
        b[l] = r.random_sample((nn_structure[l],))
    return W, b