本文整理匯總了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()
示例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
示例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
示例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}%")
示例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))
示例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)
示例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]
示例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)
示例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, :]
示例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
示例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
示例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
示例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
示例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)
示例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