本文整理匯總了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))
示例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
示例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]
示例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
示例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
示例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
示例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))
示例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
示例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
示例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
示例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
示例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)
示例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))
示例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
示例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