本文整理匯總了Python中random.normalvariate方法的典型用法代碼示例。如果您正苦於以下問題:Python random.normalvariate方法的具體用法?Python random.normalvariate怎麽用?Python random.normalvariate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類random
的用法示例。
在下文中一共展示了random.normalvariate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_gauss_data
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def _get_gauss_data(n=10000, covariance=0.4, expand=True):
"""Generate correlated and uncorrelated Gaussian variables.
Generate two sets of random normal data, where one set has a given
covariance and the second is uncorrelated.
"""
corr_expected = covariance / (1 * np.sqrt(covariance**2 + (1-covariance)**2))
expected_mi = calculate_mi(corr_expected)
src_corr = [rn.normalvariate(0, 1) for r in range(n)] # correlated src
src_uncorr = [rn.normalvariate(0, 1) for r in range(n)] # uncorrelated src
target = [sum(pair) for pair in zip(
[covariance * y for y in src_corr[0:n]],
[(1-covariance) * y for y in [
rn.normalvariate(0, 1) for r in range(n)]])]
# Make everything numpy arrays so jpype understands it. Add an additional
# axis if requested (MI/CMI estimators accept 2D arrays, TE/AIS only 1D).
if expand:
src_corr = np.expand_dims(np.array(src_corr), axis=1)
src_uncorr = np.expand_dims(np.array(src_uncorr), axis=1)
target = np.expand_dims(np.array(target), axis=1)
else:
src_corr = np.array(src_corr)
src_uncorr = np.array(src_uncorr)
target = np.array(target)
return expected_mi, src_corr, src_uncorr, target
示例2: heston_construct_correlated_path
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def heston_construct_correlated_path(params: ModelParameters,
brownian_motion_one: np.array):
"""
This method is a simplified version of the Cholesky decomposition method
for just two assets. It does not make use of matrix algebra and is therefore
quite easy to implement.
Arguments:
params : ModelParameters
The parameters for the stochastic model.
brownian_motion_one : np.array
(Not filled)
Returns:
A correlated brownian motion path.
"""
# We do not multiply by sigma here, we do that in the Heston model
sqrt_delta = np.sqrt(params.all_delta)
# Construct a path correlated to the first path
brownian_motion_two = []
for i in range(params.all_time - 1):
term_one = params.cir_rho * brownian_motion_one[i]
term_two = np.sqrt(1 - pow(params.cir_rho, 2)) * random.normalvariate(0, sqrt_delta)
brownian_motion_two.append(term_one + term_two)
return np.array(brownian_motion_one), np.array(brownian_motion_two)
示例3: random_rectangle
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def random_rectangle(max_side, min_side, sigma=0.5, ratio=1.0, coherce=True):
assert min_side <= max_side
#
half_side = (max_side-min_side)/2
center = max_side-half_side
width = random.normalvariate(0, sigma)*half_side
height = random.normalvariate(0, sigma)*half_side
#
if ratio > 1:
height = height/ratio
else:
width = width*ratio
# Coherce value to max
if coherce:
width = coherce_to(max_side, min_side, width+center)
height = coherce_to(max_side, min_side, height+center)
return width, height
示例4: n_rolls
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def n_rolls(count, n):
"""roll an n-sided die count times
:type count: int
:type n: int | str
"""
if n in ('f', 'F'):
return [random.randint(-1, 1) for _ in range(min(count, 100))]
if count < 100:
return [random.randint(1, n) for _ in range(count)]
# Calculate a random sum approximated using a randomized normal variate with the midpoint used as the mu
# and an approximated standard deviation based on variance as the sigma
mid = .5 * (n + 1) * count
var = (n ** 2 - 1) / 12
adj_var = (var * count) ** 0.5
return [int(random.normalvariate(mid, adj_var))]
示例5: test_single_source_storage_gaussian
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def test_single_source_storage_gaussian():
n = 1000
proc_1 = [rn.normalvariate(0, 1) for r in range(n)] # correlated src
proc_2 = [rn.normalvariate(0, 1) for r in range(n)] # correlated src
# Cast everything to numpy so the idtxl estimator understands it.
data = Data(np.array([proc_1, proc_2]), dim_order='ps')
settings = {
'cmi_estimator': 'JidtKraskovCMI',
'alpha_mi': 0.05,
'tail_mi': 'one_bigger',
'n_perm_max_stat': 21,
'n_perm_min_stat': 21,
'n_perm_mi': 21,
'max_lag': 5,
'tau': 1
}
processes = [1]
network_analysis = ActiveInformationStorage()
results = network_analysis.analyse_network(settings, data, processes)
print('AIS for random normal data without memory (expected is NaN): '
'{0}'.format(results._single_process[1].ais))
assert results._single_process[1].ais is np.nan, (
'Estimator did not return nan for memoryless data.')
示例6: testDependentGridSearchCallable
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def testDependentGridSearchCallable(self):
class Normal:
def __call__(self, _config):
return random.normalvariate(mu=0, sigma=1)
class Single:
def __call__(self, _config):
return 20
trials = self.generate_trials({
"run": "PPO",
"config": {
"x": grid_search(
[tune.sample_from(Normal()),
tune.sample_from(Normal())]),
"y": tune.sample_from(Single()),
},
}, "dependent_grid_search")
trials = list(trials)
self.assertEqual(len(trials), 2)
self.assertEqual(trials[0].config["y"], 20)
self.assertEqual(trials[1].config["y"], 20)
示例7: generate_tokens
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def generate_tokens(mean, std_dev, num_tokens):
tokens = {}
cnt = 0
while cnt < num_tokens:
length = int(round(random.normalvariate(mean,
std_dev)))
if length < 2:
continue
flag = True
while flag:
new_token = ''.join(random.choice(string.ascii_lowercase)
for i in range(length))
if tokens.get(new_token) is None:
tokens[new_token] = True
flag = False
cnt += 1
return list(tokens.keys())
示例8: generate_table
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def generate_table(mean, std_dev, tokens, num_records,
id_col_name, attr_col_name):
records = []
cnt = 0
num_tokens = len(tokens)
while cnt < num_records:
size = int(round(random.normalvariate(mean,
std_dev)))
new_string = ''
for i in range(size):
rand = random.randint(0, num_tokens - 1)
if i == 0:
new_string += tokens[rand]
else:
new_string += ' ' + tokens[rand]
records.append([cnt, new_string])
cnt += 1
return pd.DataFrame(records, columns=[id_col_name, attr_col_name])
示例9: n_rolls
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def n_rolls(count, n):
"""roll an n-sided die count times
:type count: int
:type n: int | str
"""
if n == "F":
return [random.randint(-1, 1) for x in range(min(count, 100))]
if n < 2: # it's a coin
if count < 100:
return [random.randint(0, 1) for x in range(count)]
else: # fake it
return [int(random.normalvariate(.5 * count, (.75 * count) ** .5))]
else:
if count < 100:
return [random.randint(1, n) for x in range(count)]
else: # fake it
return [int(random.normalvariate(.5 * (1 + n) * count,
(((n + 1) * (2 * n + 1) / 6. -
(.5 * (1 + n)) ** 2) * count) ** .5))]
示例10: coin
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def coin(text, notice, action):
"""[amount] - flips [amount] coins
:type text: str
"""
if text:
try:
amount = int(text)
except (ValueError, TypeError):
notice("Invalid input '{}': not a number".format(text))
return
else:
amount = 1
if amount == 1:
action("flips a coin and gets {}.".format(random.choice(["heads", "tails"])))
elif amount == 0:
action("makes a coin flipping motion")
else:
heads = int(random.normalvariate(.5 * amount, (.75 * amount) ** .5))
tails = amount - heads
action("flips {} coins and gets {} heads and {} tails.".format(amount, heads, tails))
示例11: get_dist
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def get_dist(d):
return {
'randrange': random.randrange, # start, stop, step
'randint': random.randint, # a, b
'random': random.random,
'uniform': random, # a, b
'triangular': random.triangular, # low, high, mode
'beta': random.betavariate, # alpha, beta
'expo': random.expovariate, # lambda
'gamma': random.gammavariate, # alpha, beta
'gauss': random.gauss, # mu, sigma
'lognorm': random.lognormvariate, # mu, sigma
'normal': random.normalvariate, # mu, sigma
'vonmises': random.vonmisesvariate, # mu, kappa
'pareto': random.paretovariate, # alpha
'weibull': random.weibullvariate # alpha, beta
}.get(d)
示例12: jump_diffusion_process
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def jump_diffusion_process(params: ModelParameters):
"""
Produces a sequence of Jump Sizes which represent a jump
diffusion process. These jumps are combined with a geometric brownian
motion (log returns) to produce the Merton model.
Arguments:
params : ModelParameters
The parameters for the stochastic model.
Returns:
jump sizes for each point in time (mostly zeroes if jumps are infrequent)
"""
s_n = time = 0
small_lamda = -(1.0 / params.lamda)
jump_sizes = []
for k in range(params.all_time):
jump_sizes.append(0.0)
while s_n < params.all_time:
s_n += small_lamda * np.log(np.random.uniform(0, 1))
for j in range(params.all_time):
if time * params.all_delta <= s_n * params.all_delta <= (j + 1) * params.all_delta:
jump_sizes[j] += random.normalvariate(params.jumps_mu, params.jumps_sigma)
break
time += 1
return jump_sizes
示例13: get_correlated_geometric_brownian_motions
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def get_correlated_geometric_brownian_motions(params: ModelParameters,
correlation_matrix: np.array,
n: int):
"""
Constructs a basket of correlated asset paths using the Cholesky
decomposition method.
Arguments:
params : ModelParameters
The parameters for the stochastic model.
correlation_matrix : np.array
An n x n correlation matrix.
n : int
Number of assets (number of paths to return)
Returns:
n correlated log return geometric brownian motion processes
"""
decomposition = sp.linalg.cholesky(correlation_matrix, lower=False)
uncorrelated_paths = []
sqrt_delta_sigma = np.sqrt(params.all_delta) * params.all_sigma
# Construct uncorrelated paths to convert into correlated paths
for i in range(params.all_time):
uncorrelated_random_numbers = []
for j in range(n):
uncorrelated_random_numbers.append(random.normalvariate(0, sqrt_delta_sigma))
uncorrelated_paths.append(np.array(uncorrelated_random_numbers))
uncorrelated_matrix = np.asmatrix(uncorrelated_paths)
correlated_matrix = uncorrelated_matrix * decomposition
assert isinstance(correlated_matrix, np.matrix)
# The rest of this method just extracts paths from the matrix
extracted_paths = []
for i in range(1, n + 1):
extracted_paths.append([])
for j in range(0, len(correlated_matrix) * n - n, n):
for i in range(n):
extracted_paths[i].append(correlated_matrix.item(j + i))
return extracted_paths
示例14: initialize_v
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def initialize_v(n: int, k: int):
"""初始化交叉項
:param n: 特征個數
:param k: FM模型的度
:return: 交叉項的係數權重
"""
v = np.mat(np.zeros(shape=(n, k)))
for i in range(n):
for j in range(k):
v[i, j] = normalvariate(0, 0.2)
return v
示例15: random_resize
# 需要導入模塊: import random [as 別名]
# 或者: from random import normalvariate [as 別名]
def random_resize(image, gt_image, lower_size, upper_size, sig):
factor = random.normalvariate(1, sig)
if factor < lower_size:
factor = lower_size
if factor > upper_size:
factor = upper_size
image = scipy.misc.imresize(image, factor)
shape = gt_image.shape
gt_zero = np.zeros([shape[0], shape[1], 1])
gt_image = np.concatenate((gt_image, gt_zero), axis=2)
gt_image = scipy.misc.imresize(gt_image, factor, interp='nearest')
gt_image = gt_image[:, :, 0:2]/255
return image, gt_image