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


Python random.random方法代码示例

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


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

示例1: __init__

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def __init__(self, name, infected, infection_length, initiative,
                 coupling_tendency, condom_use, test_frequency, commitment,
                 coupled=False, coupled_length=0, known=False, partner=None):
        init_state = random.randint(0, 3)
        super().__init__(name, "wandering around", NSTATES, init_state)
        self.coupled = coupled
        self.couple_length = coupled_length
        self.partner = partner
        self.initiative = initiative
        self.infected = infected
        self.known = known
        self.infection_length = infection_length
        self.coupling_tendency = coupling_tendency
        self.condom_use = condom_use
        self.test_frequency = test_frequency
        self.commitment = commitment
        self.state = init_state
        self.update_ntype() 
开发者ID:gcallah,项目名称:indras_net,代码行数:20,代码来源:hiv.py

示例2: discourage

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def discourage(unwanted):
    """
    Discourages extra drinkers from going to the bar by decreasing motivation.
    Chooses drinkers randomly from the drinkers that went to the bar.
    """
    discouraged = 0
    drinkers = get_group(DRINKERS)
    while unwanted:
        if DEBUG:
            user_tell("The members are: " + drinkers.members)
        rand_name = random.choice(list(drinkers.members))
        rand_agent = drinkers[rand_name]

        if DEBUG:
            user_tell("drinker ", rand_agent, " = "
                      + repr(drinkers[rand_agent]))

        rand_agent[MOTIV] = max(rand_agent[MOTIV] - DISC_AMT,
                                MIN_MOTIV)
        discouraged += 1
        unwanted -= 1
    return discouraged 
开发者ID:gcallah,项目名称:indras_net,代码行数:24,代码来源:el_farol.py

示例3: initial_solution

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def initial_solution(self):
        """
        Greedy algorithm to get an initial solution (closest-neighbour).
        """
        cur_node = random.choice(self.nodes)  # start from a random node
        solution = [cur_node]

        free_nodes = set(self.nodes)
        free_nodes.remove(cur_node)
        while free_nodes:
            next_node = min(free_nodes, key=lambda x: self.dist(cur_node, x))  # nearest neighbour
            free_nodes.remove(next_node)
            solution.append(next_node)
            cur_node = next_node

        cur_fit = self.fitness(solution)
        if cur_fit < self.best_fitness:  # If best found so far, update best fitness
            self.best_fitness = cur_fit
            self.best_solution = solution
        self.fitness_list.append(cur_fit)
        return solution, cur_fit 
开发者ID:chncyhn,项目名称:simulated-annealing-tsp,代码行数:23,代码来源:anneal.py

示例4: anneal

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def anneal(self):
        """
        Execute simulated annealing algorithm.
        """
        # Initialize with the greedy solution.
        self.cur_solution, self.cur_fitness = self.initial_solution()

        print("Starting annealing.")
        while self.T >= self.stopping_temperature and self.iteration < self.stopping_iter:
            candidate = list(self.cur_solution)
            l = random.randint(2, self.N - 1)
            i = random.randint(0, self.N - l)
            candidate[i : (i + l)] = reversed(candidate[i : (i + l)])
            self.accept(candidate)
            self.T *= self.alpha
            self.iteration += 1

            self.fitness_list.append(self.cur_fitness)

        print("Best fitness obtained: ", self.best_fitness)
        improvement = 100 * (self.fitness_list[0] - self.best_fitness) / (self.fitness_list[0])
        print(f"Improvement over greedy heuristic: {improvement : .2f}%") 
开发者ID:chncyhn,项目名称:simulated-annealing-tsp,代码行数:24,代码来源:anneal.py

示例5: make_train_test_sets

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def make_train_test_sets(pos_graphs, neg_graphs,
                         test_proportion=.3, random_state=2):
    """make_train_test_sets."""
    random.seed(random_state)
    random.shuffle(pos_graphs)
    random.shuffle(neg_graphs)
    pos_dim = len(pos_graphs)
    neg_dim = len(neg_graphs)
    tr_pos_graphs = pos_graphs[:-int(pos_dim * test_proportion)]
    te_pos_graphs = pos_graphs[-int(pos_dim * test_proportion):]
    tr_neg_graphs = neg_graphs[:-int(neg_dim * test_proportion)]
    te_neg_graphs = neg_graphs[-int(neg_dim * test_proportion):]
    tr_graphs = tr_pos_graphs + tr_neg_graphs
    te_graphs = te_pos_graphs + te_neg_graphs
    tr_targets = [1] * len(tr_pos_graphs) + [0] * len(tr_neg_graphs)
    te_targets = [1] * len(te_pos_graphs) + [0] * len(te_neg_graphs)
    tr_graphs, tr_targets = paired_shuffle(tr_graphs, tr_targets)
    te_graphs, te_targets = paired_shuffle(te_graphs, te_targets)
    return (tr_graphs, np.array(tr_targets)), (te_graphs, np.array(te_targets)) 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:21,代码来源:estimator_utils.py

示例6: getTsvData

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def getTsvData(self, filepath):
        print("Loading training data from "+filepath)
        x1=[]
        x2=[]
        y=[]
        # positive samples from file
        for line in open(filepath):
            l=line.strip().split("\t")
            if len(l)<2:
                continue
            if random() > 0.5:
                x1.append(l[0].lower())
                x2.append(l[1].lower())
            else:
                x1.append(l[1].lower())
                x2.append(l[0].lower())
            y.append(int(l[2]))
        return np.asarray(x1),np.asarray(x2),np.asarray(y) 
开发者ID:dhwajraj,项目名称:deep-siamese-text-similarity,代码行数:20,代码来源:input_helpers.py

示例7: batch_iter

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def batch_iter(self, data, batch_size, num_epochs, shuffle=True):
        """
        Generates a batch iterator for a dataset.
        """
        data = np.asarray(data)
        print(data)
        print(data.shape)
        data_size = len(data)
        num_batches_per_epoch = int(len(data)/batch_size) + 1
        for epoch in range(num_epochs):
            # Shuffle the data at each epoch
            if shuffle:
                shuffle_indices = np.random.permutation(np.arange(data_size))
                shuffled_data = data[shuffle_indices]
            else:
                shuffled_data = data
            for batch_num in range(num_batches_per_epoch):
                start_index = batch_num * batch_size
                end_index = min((batch_num + 1) * batch_size, data_size)
                yield shuffled_data[start_index:end_index] 
开发者ID:dhwajraj,项目名称:deep-siamese-text-similarity,代码行数:22,代码来源:input_helpers.py

示例8: train_step

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def train_step(x1_batch, x2_batch, y_batch):
        """
        A single training step
        """
        if random()>0.5:
            feed_dict = {
                siameseModel.input_x1: x1_batch,
                siameseModel.input_x2: x2_batch,
                siameseModel.input_y: y_batch,
                siameseModel.dropout_keep_prob: FLAGS.dropout_keep_prob,
            }
        else:
            feed_dict = {
                siameseModel.input_x1: x2_batch,
                siameseModel.input_x2: x1_batch,
                siameseModel.input_y: y_batch,
                siameseModel.dropout_keep_prob: FLAGS.dropout_keep_prob,
            }
        _, step, loss, accuracy, dist, sim, summaries = sess.run([tr_op_set, global_step, siameseModel.loss, siameseModel.accuracy, siameseModel.distance, siameseModel.temp_sim, train_summary_op],  feed_dict)
        time_str = datetime.datetime.now().isoformat()
        print("TRAIN {}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
        train_summary_writer.add_summary(summaries, step)
        print(y_batch, dist, sim) 
开发者ID:dhwajraj,项目名称:deep-siamese-text-similarity,代码行数:25,代码来源:train.py

示例9: __call__

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def __call__(self, video):
    """
    Args:
        video (np.ndarray): Video to be cropped.
    Returns:
        np.ndarray: Cropped video.
    """
    if self.padding > 0:
      pad = Pad(self.padding, 0)
      video = pad(video)

    w, h = video.shape[-2], video.shape[-3]
    th, tw = self.size
    if w == tw and h == th:
      return video

    x1 = random.randint(0, w-tw)
    y1 = random.randint(0, h-th)
    return video[..., y1:y1+th, x1:x1+tw, :] 
开发者ID:jthsieh,项目名称:DDPAE-video-prediction,代码行数:21,代码来源:video_transforms.py

示例10: __getitem__

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def __getitem__(self, idx):
    length = self.n_frames_input + self.n_frames_output
    if self.is_train or self.num_objects[0] != 2:
      # Sample number of objects
      num_digits = random.choice(self.num_objects)
      # Generate data on the fly
      images = self.generate_moving_mnist(num_digits)
    else:
      images = self.dataset[:, idx, ...]

    if self.transform is not None:
      images = self.transform(images)
    input = images[:self.n_frames_input]
    if self.n_frames_output > 0:
      output = images[self.n_frames_input:length]
    else:
      output = []

    return input, output 
开发者ID:jthsieh,项目名称:DDPAE-video-prediction,代码行数:21,代码来源:moving_mnist.py

示例11: generate_ip_verify_hash

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def generate_ip_verify_hash(input_dict):
    """
    生成一个标示用户身份的hash
    在 human_ip_verification 功能中使用
    hash一共14位
    hash(前7位+salt) = 后7位 以此来进行验证
    :rtype str
    """
    strbuff = human_ip_verification_answers_hash_str
    for key in input_dict:
        strbuff += key + input_dict[key] + str(random.randint(0, 9000000))
    input_key_hash = hex(zlib.adler32(strbuff.encode(encoding='utf-8')))[2:]
    while len(input_key_hash) < 7:
        input_key_hash += '0'
    output_hash = hex(zlib.adler32((input_key_hash + human_ip_verification_answers_hash_str).encode(encoding='utf-8')))[2:]
    while len(output_hash) < 7:
        output_hash += '0'
    return input_key_hash + output_hash 
开发者ID:aploium,项目名称:zmirror,代码行数:20,代码来源:zmirror.py

示例12: random_projection

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def random_projection(X):

        data_demension = X.shape[1]

        new_data_demension = random.randint(2, data_demension)

        new_X = np.empty((data_demension, new_data_demension))

        minus_one = 0.1
        positive_one = 0.9

        for i in range(len(new_X)):
            for j in range(len(new_X[i])):
                rand = random.random()
                if rand < minus_one:
                    new_X[i][j] = -1.0
                elif rand >= positive_one:
                    new_X[i][j] = 1.0
                else:
                    new_X[i][j] = 0.0

        new_X = np.inner(X, new_X.T)

        return new_X 
开发者ID:fukuball,项目名称:fuku-ml,代码行数:26,代码来源:Utility.py

示例13: should_step_get_rejected

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def should_step_get_rejected(self, standardError):
        """
        Given a standard error, return whether to keep or reject new
        standard error according to the constraint reject probability.

        :Parameters:
            #. standardError (number): The standard error to compare with
            the Constraint standard error

        :Return:
            #. result (boolean): True to reject step, False to accept
        """
        if self.standardError is None:
            raise Exception(LOGGER.error("must compute data first"))
        if standardError<=self.standardError:
            return False
        return randfloat() < self.__rejectProbability 
开发者ID:bachiraoun,项目名称:fullrmc,代码行数:19,代码来源:Constraint.py

示例14: estimate_density

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def estimate_density(DATA_PATH, feature_size):
    """sample 10 times of a size of 1000 for estimating the density of the sparse dataset"""
    if not os.path.exists(DATA_PATH):
        raise Exception("Data is not there!")
    density = []
    P = 0.01
    for _ in range(10):
        num_non_zero = 0
        num_sample = 0
        with open(DATA_PATH) as f:
            for line in f:
                if (random.random() < P):
                    num_non_zero += len(line.split(" ")) - 1
                    num_sample += 1
        density.append(num_non_zero * 1.0 / (feature_size * num_sample))
    return sum(density) / len(density) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:18,代码来源:util.py

示例15: initialise

# 需要导入模块: import random [as 别名]
# 或者: from random import random [as 别名]
def initialise():
    forest = [[tree if random.random() <= initial_trees else space for x in range(forest_width)] for y in range(forest_height)]
    return forest 
开发者ID:pimoroni,项目名称:unicorn-hat-hd,代码行数:5,代码来源:forest-fire.py


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