Here are the examples of the python api numpy.random.rand taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
7198 Examples
5
Source : test_tensor_network.py
with MIT License
from alibaba
with MIT License
from alibaba
def test_copy(self):
a = TensorNetwork()
a.add_node(0, [0, 1], numpy.random.rand(10, 8))
a.add_node(1, [1, 2], numpy.random.rand(8, 9))
a.add_node(2, [2, 0], numpy.random.rand(9, 10))
b = a.copy()
c = deepcopy(a)
self.assertNotEqual(b.identifier, a.identifier)
self.assertNotEqual(c.identifier, a.identifier)
node = list(b.nodes_by_name)[0]
self.assertTrue(a.nodes[(0, node)]['tensor']._data is b.nodes[(0, node)]['tensor']._data)
self.assertFalse(a.nodes[(0, node)]['tensor']._data is c.nodes[(0, node)]['tensor']._data)
b.update_node(0, numpy.random.rand(10, 8))
self.assertNotEqual(a.contract(), b.contract())
def test_shape(self):
5
Source : test_tensor_sum.py
with MIT License
from alibaba
with MIT License
from alibaba
def setUp(self):
self.a = TensorNetwork()
for i in range(5):
self.a.open_edge(i)
for i in range(5):
for j in range(5, 10):
self.a.add_node((i, j), [i, j], numpy.random.rand(2, 2))
self.b = TensorNetwork()
for i in range(5):
self.b.open_edge(i)
for i in range(5):
for j in range(5, 10):
self.b.add_node((i, j), [i, j], 1j * numpy.random.rand(2, 3))
self.c = Tensor(numpy.random.rand(2, 2, 2, 2, 2))
def test_addition(self):
5
Source : bilinear_test.py
with GNU General Public License v3.0
from dair-iitd
with GNU General Public License v3.0
from dair-iitd
def test_forward_works_with_higher_order_tensors(self):
# pylint: disable=protected-access
bilinear = BilinearSimilarity(4, 7)
weights = numpy.random.rand(4, 7)
bilinear._weight_matrix = Parameter(torch.from_numpy(weights).float())
bilinear._bias = Parameter(torch.from_numpy(numpy.asarray([0])).float())
a_vectors = numpy.random.rand(5, 4, 3, 6, 4)
b_vectors = numpy.random.rand(5, 4, 3, 6, 7)
a_variables = torch.from_numpy(a_vectors).float()
b_variables = torch.from_numpy(b_vectors).float()
result = bilinear(a_variables, b_variables).data.numpy()
assert result.shape == (5, 4, 3, 6)
expected_result = numpy.dot(numpy.dot(numpy.transpose(a_vectors[3, 2, 1, 3]), weights),
b_vectors[3, 2, 1, 3])
assert_almost_equal(result[3, 2, 1, 3], expected_result, decimal=5)
def test_can_construct_from_params(self):
5
Source : linear_test.py
with GNU General Public License v3.0
from dair-iitd
with GNU General Public License v3.0
from dair-iitd
def test_forward_works_with_higher_order_tensors(self):
linear = LinearSimilarity(7, 7, combination='x,y')
weights = numpy.random.rand(14)
linear._weight_vector = Parameter(torch.from_numpy(weights).float())
linear._bias = Parameter(torch.FloatTensor([0.]))
a_vectors = numpy.random.rand(5, 4, 3, 6, 7)
b_vectors = numpy.random.rand(5, 4, 3, 6, 7)
result = linear(torch.from_numpy(a_vectors).float(),
torch.from_numpy(b_vectors).float())
result = result.data.numpy()
assert result.shape == (5, 4, 3, 6)
combined_vectors = numpy.concatenate([a_vectors[3, 2, 1, 3, :], b_vectors[3, 2, 1, 3, :]])
expected_result = numpy.dot(combined_vectors, weights)
assert_almost_equal(result[3, 2, 1, 3], expected_result, decimal=6)
def test_forward_works_with_multiply_combinations(self):
5
Source : extending_theano_solution_1.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_gradient(self):
def output_0(x, y):
return self.op_class()(x, y)[0]
def output_1(x, y):
return self.op_class()(x, y)[1]
utt.verify_grad(output_0, [numpy.random.rand(5, 4),
numpy.random.rand(5, 4)],
n_tests=1, rng=TestSumDiffOp.rng)
utt.verify_grad(output_1, [numpy.random.rand(5, 4),
numpy.random.rand(5, 4)],
n_tests=1, rng=TestSumDiffOp.rng)
def test_infer_shape(self):
5
Source : test_conv_cuda_ndarray.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_stack_rows_segfault_070312():
seed_rng()
# 07/03/2012
# Running this unittest with cuda-memcheck exposes an illegal read.
# THEANO_FLAGS=device=gpu cuda-memcheck nosetests \
# test_conv_cuda_ndarray.py:test_stack_rows_segfault_070312
img = theano.shared(numpy.random.rand(1, 80, 96, 96).astype('float32'))
kern = theano.shared(numpy.random.rand(1, 80, 9, 9).astype('float32'))
out = theano.shared(numpy.random.rand(1, 2, 2, 3).astype('float32'))
op = theano.tensor.nnet.conv.ConvOp(imshp=(80, 96, 96), kshp=(9, 9),
nkern=1, bsize=1)
f = theano.function([], [], updates=[(out, op(img, kern))], mode=theano_mode)
f()
5
Source : test_blas.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_A_plus_outer(self):
f = self.function([self.A, self.x, self.y],
self.A + T.outer(self.x, self.y))
self.assertFunctionContains(f, self.ger)
f(numpy.random.rand(5, 4).astype(self.dtype),
numpy.random.rand(5).astype(self.dtype),
numpy.random.rand(4).astype(self.dtype))
f(numpy.random.rand(5, 4).astype(self.dtype)[::-1, ::-1],
numpy.random.rand(5).astype(self.dtype),
numpy.random.rand(4).astype(self.dtype))
def test_A_plus_scaled_outer(self):
5
Source : test_blas.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_A_plus_scaled_outer(self):
f = self.function([self.A, self.x, self.y],
self.A + 0.1 * T.outer(self.x, self.y))
self.assertFunctionContains(f, self.ger)
f(numpy.random.rand(5, 4).astype(self.dtype),
numpy.random.rand(5).astype(self.dtype),
numpy.random.rand(4).astype(self.dtype))
f(numpy.random.rand(5, 4).astype(self.dtype)[::-1, ::-1],
numpy.random.rand(5).astype(self.dtype),
numpy.random.rand(4).astype(self.dtype))
def test_scaled_A_plus_scaled_outer(self):
5
Source : test_blas.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def given_dtype(self, dtype, M, N):
""" test corner case shape and dtype"""
f = self.function([self.A, self.x, self.y],
self.A + 0.1 * T.outer(self.x, self.y))
self.assertFunctionContains(f, self.ger)
f(numpy.random.rand(M, N).astype(self.dtype),
numpy.random.rand(M).astype(self.dtype),
numpy.random.rand(N).astype(self.dtype))
f(numpy.random.rand(M, N).astype(self.dtype)[::-1, ::-1],
numpy.random.rand(M).astype(self.dtype),
numpy.random.rand(N).astype(self.dtype))
def test_f32_0_0(self):
5
Source : test_blas.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_inplace(self):
A = self.shared(numpy.random.rand(4, 5).astype(self.dtype))
f = self.function([self.x, self.y], [],
updates=[(A, A + T.constant(0.1, dtype=self.dtype) *
T.outer(self.x, self.y))])
self.assertFunctionContains(f, self.ger_destructive)
f(numpy.random.rand(4).astype(self.dtype),
numpy.random.rand(5).astype(self.dtype))
A.set_value(
A.get_value(borrow=True, return_internal_type=True)[::-1, ::-1],
borrow=True)
f(numpy.random.rand(4).astype(self.dtype),
numpy.random.rand(5).astype(self.dtype))
class TestBlasStrides(TestCase):
5
Source : test_blas_c.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_multiple_inplace(self):
x = tensor.dmatrix('x')
y = tensor.dvector('y')
z = tensor.dvector('z')
f = theano.function([x, y, z],
[tensor.dot(y, x), tensor.dot(z,x)],
mode=mode_blas_opt)
vx = numpy.random.rand(3, 3)
vy = numpy.random.rand(3)
vz = numpy.random.rand(3)
out = f(vx, vy, vz)
assert numpy.allclose(out[0], numpy.dot(vy, vx))
assert numpy.allclose(out[1], numpy.dot(vz, vx))
assert len([n for n in f.maker.fgraph.apply_nodes
if isinstance(n.op, tensor.AllocEmpty)]) == 2
class TestCGemvFloat32(TestCase, BaseGemv, TestOptimizationMixin):
5
Source : test_extra_ops.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_gradient(self):
utt.verify_grad(fill_diagonal, [numpy.random.rand(5, 8),
numpy.random.rand()],
n_tests=1, rng=TestFillDiagonal.rng)
utt.verify_grad(fill_diagonal, [numpy.random.rand(8, 5),
numpy.random.rand()],
n_tests=1, rng=TestFillDiagonal.rng)
def test_infer_shape(self):
5
Source : test_extra_ops.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_infer_shape(self):
z = tensor.dtensor3()
x = tensor.dmatrix()
y = tensor.dscalar()
self._compile_and_check([x, y], [self.op(x, y)],
[numpy.random.rand(8, 5),
numpy.random.rand()],
self.op_class)
self._compile_and_check([z, y], [self.op(z, y)],
# must be square when nd>2
[numpy.random.rand(8, 8, 8),
numpy.random.rand()],
self.op_class,
warn=False)
class TestFillDiagonalOffset(utt.InferShapeTester):
5
Source : test_extra_ops.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_gradient(self):
for test_offset in (-5, -4, -1, 0, 1, 4, 5):
# input 'offset' will not be tested
def fill_diagonal_with_fix_offset( a, val):
return fill_diagonal_offset( a, val, test_offset)
utt.verify_grad(fill_diagonal_with_fix_offset,
[numpy.random.rand(5, 8), numpy.random.rand()],
n_tests=1, rng=TestFillDiagonalOffset.rng)
utt.verify_grad(fill_diagonal_with_fix_offset,
[numpy.random.rand(8, 5), numpy.random.rand()],
n_tests=1, rng=TestFillDiagonalOffset.rng)
utt.verify_grad(fill_diagonal_with_fix_offset,
[numpy.random.rand(5, 5), numpy.random.rand()],
n_tests=1, rng=TestFillDiagonalOffset.rng)
def test_infer_shape(self):
5
Source : test_extra_ops.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_infer_shape(self):
x = tensor.dmatrix()
y = tensor.dscalar()
z = tensor.iscalar()
for test_offset in (-5, -4, -1, 0, 1, 4, 5):
self._compile_and_check([x, y, z], [self.op(x, y, z)],
[numpy.random.rand(8, 5),
numpy.random.rand(),
test_offset],
self.op_class )
self._compile_and_check([x, y, z], [self.op(x, y, z)],
[numpy.random.rand(5, 8),
numpy.random.rand(),
test_offset],
self.op_class )
def test_to_one_hot():
5
Source : test_fourier.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_infer_shape(self):
a = tensor.dvector()
self._compile_and_check([a], [self.op(a, 16, 0)],
[numpy.random.rand(12)],
self.op_class)
a = tensor.dmatrix()
for var in [self.op(a, 16, 1), self.op(a, None, 1),
self.op(a, 16, None), self.op(a, None, None)]:
self._compile_and_check([a], [var],
[numpy.random.rand(12, 4)],
self.op_class)
b = tensor.iscalar()
for var in [self.op(a, 16, b), self.op(a, None, b)]:
self._compile_and_check([a, b], [var],
[numpy.random.rand(12, 4), 0],
self.op_class)
@dec.skipif(True, "Complex grads not enabled, see #178")
5
Source : test_basic.py
with MIT License
from dmitriy-serdyuk
with MIT License
from dmitriy-serdyuk
def test_correct_answer(self):
a = T.matrix()
b = T.matrix()
x = T.tensor3()
y = T.tensor3()
A = numpy.cast[theano.config.floatX](numpy.random.rand(5, 3))
B = numpy.cast[theano.config.floatX](numpy.random.rand(7, 2))
X = numpy.cast[theano.config.floatX](numpy.random.rand(5, 6, 1))
Y = numpy.cast[theano.config.floatX](numpy.random.rand(1, 9, 3))
make_list((3., 4.))
c = make_list((a, b))
z = make_list((x, y))
fc = theano.function([a, b], c)
fz = theano.function([x, y], z)
self.assertTrue((m == n).all() for m, n in zip(fc(A, B), [A, B]))
self.assertTrue((m == n).all() for m, n in zip(fz(X, Y), [X, Y]))
5
Source : sample.py
with GNU General Public License v3.0
from econtal
with GNU General Public License v3.0
from econtal
def sample(d=1, size=40, ns=1000, nt=10, kernel=None, basis=None, noise=1e-2):
if kernel is None:
kernel = KernelSEnormiso(d)
Xs = size * numpy.random.rand(ns, d)
Xt = Xs[:nt, :]
Kss = kernel(Xs, Xs)
Fs = numpy.dot(cholpsd(Kss).T, numpy.random.randn(ns, 1))
if basis is not None:
B = basis(Xs)
Fs = Fs + numpy.dot(B, numpy.randomrandn(B.shape[1], 1))
f = lambda X: Fs[X] + noise * numpy.random.randn(X.shape[0], 1)
Yt = f(numpy.arange(nt))
return f, Xs, Fs, Xt, Yt, Kss
5
Source : test_cml_AllNeuralNetworkConverters.py
with Apache License 2.0
from onnx
with Apache License 2.0
from onnx
def test_gru_converter(self):
input_dim = (1, 8)
output_dim = (1, 2)
inputs = [('input', datatypes.Array(*input_dim))]
outputs = [('output', datatypes.Array(*output_dim))]
builder = NeuralNetworkBuilder(inputs, outputs)
W_h = [numpy.random.rand(2, 2), numpy.random.rand(2, 2), numpy.random.rand(2, 2)]
W_x = [numpy.random.rand(2, 8), numpy.random.rand(2, 8), numpy.random.rand(2, 8)]
b = [numpy.random.rand(2, 1), numpy.random.rand(2, 1), numpy.random.rand(2, 1)]
builder.add_gru(name='GRU', W_h=W_h, W_x=W_x, b=b, hidden_size=2, input_size=8, input_names=['input'],
output_names=['output'], activation='TANH', inner_activation='SIGMOID_HARD', output_all=False,
reverse_input=False)
model_onnx = convert_coreml(builder.spec, target_opset=TARGET_OPSET)
self.assertTrue(model_onnx is not None)
def test_simple_recurrent_converter(self):
5
Source : test_cml_AllNeuralNetworkConverters.py
with Apache License 2.0
from onnx
with Apache License 2.0
from onnx
def test_simple_recurrent_converter(self):
input_dim = (1, 8)
output_dim = (1, 2)
inputs = [('input', datatypes.Array(*input_dim))]
outputs = [('output', datatypes.Array(*output_dim))]
builder = NeuralNetworkBuilder(inputs, outputs)
W_h = numpy.random.rand(2, 2)
W_x = numpy.random.rand(2, 8)
b = numpy.random.rand(2, 1)
builder.add_simple_rnn(name='RNN', W_h=W_h, W_x=W_x, b=b, hidden_size=2, input_size=8,
input_names=['input', 'h_init'], output_names=['output', 'h'], activation='TANH',
output_all=False, reverse_input=False)
model_onnx = convert_coreml(builder.spec, target_opset=TARGET_OPSET)
self.assertTrue(model_onnx is not None)
def test_unidirectional_lstm_converter(self):
5
Source : test_fixed_pattern.py
with BSD 3-Clause "New" or "Revised" License
from royerlab
with BSD 3-Clause "New" or "Revised" License
from royerlab
def add_patterned_noise(image, n):
image = image.copy()
image *= 1 + 0.1 * (numpy.random.rand(n, n) - 0.5)
image += 0.1 * numpy.random.rand(n, n)
# image += 0.1*numpy.random.rand(n)[]
image = random_noise(image, mode="gaussian", var=0.00001, seed=0)
image = random_noise(image, mode="s&p", amount=0.000001, seed=0)
return image
def test_fixed_pattern_real():
5
Source : test_aap_correction.py
with BSD 3-Clause "New" or "Revised" License
from royerlab
with BSD 3-Clause "New" or "Revised" License
from royerlab
def add_patterned_noise(image, n):
image = image.copy()
image *= 1 + 0.1 * (numpy.random.rand(n, n) - 0.5)
image += 0.1 * numpy.random.rand(n, n)
# image += 0.1*numpy.random.rand(n)[]
image = random_noise(image, mode="gaussian", var=0.00001, seed=0)
image = random_noise(image, mode="s&p", amount=0.000001, seed=0)
return image
def test_aap_correction_numpy():
5
Source : test_distributions.py
with MIT License
from williamjameshandley
with MIT License
from williamjameshandley
def random_phi_theta_sigma():
phi = numpy.random.rand()*numpy.pi*2
theta = numpy.random.rand()*numpy.pi
sigma = numpy.random.rand()
return phi, theta, sigma
def random_VonMisesFisher_distribution():
3
Source : Socoban_DQN_TF_Kyushik.py
with MIT License
from 170928
with MIT License
from 170928
def get_action(self,state,train_mode=True):
if train_mode == True and self.epsilon > np.random.rand():
return np.random.randint(0,self.action_size)
else:
predict = self.sess.run(self.model.predict,feed_dict={self.model.input:state})
return np.asscalar(predict)
def append_sample(self,state,action,reward,next_state,done):
3
Source : mixup.py
with Apache License 2.0
from 1chimaruGin
with Apache License 2.0
from 1chimaruGin
def _params_per_batch(self):
lam = 1.
use_cutmix = False
if self.mixup_enabled and np.random.rand() < self.mix_prob:
if self.mixup_alpha > 0. and self.cutmix_alpha > 0.:
use_cutmix = np.random.rand() < self.switch_prob
lam_mix = np.random.beta(self.cutmix_alpha, self.cutmix_alpha) if use_cutmix else \
np.random.beta(self.mixup_alpha, self.mixup_alpha)
elif self.mixup_alpha > 0.:
lam_mix = np.random.beta(self.mixup_alpha, self.mixup_alpha)
elif self.cutmix_alpha > 0.:
use_cutmix = True
lam_mix = np.random.beta(self.cutmix_alpha, self.cutmix_alpha)
else:
assert False, "One of mixup_alpha > 0., cutmix_alpha > 0., cutmix_minmax not None should be true."
lam = float(lam_mix)
return lam, use_cutmix
def _mix_elem(self, x):
3
Source : DateAxisItem_QtDesigner.py
with MIT License
from 3fon3fonov
with MIT License
from 3fon3fonov
def __init__(self):
super().__init__()
self.setupUi(self)
now = time.time()
# Plot random values with timestamps in the last 6 months
timestamps = np.linspace(now - 6*30*24*3600, now, 100)
self.curve = self.plotWidget.plot(x=timestamps, y=np.random.rand(100),
symbol='o', symbolSize=5, pen=BLUE)
# 'o' circle 't' triangle 'd' diamond '+' plus 's' square
self.plotWidget.setAxisItems({'bottom': pg.DateAxisItem()})
self.plotWidget.showGrid(x=True, y=True)
app = pg.mkQApp("DateAxisItem_QtDesigner Example")
3
Source : DE_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def Creat_child(moead):
# 创建一个个体
# (就是一个向量,长度为Dimention,范围在moead.Test_fun.Bound中设定)
child = moead.Test_fun.Bound[0] + (moead.Test_fun.Bound[1] - moead.Test_fun.Bound[0]) * np.random.rand(
moead.Test_fun.Dimention)
return child
def Creat_Pop(moead):
3
Source : DE_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def mutate(moead, best, p1, p2):
f = 0.5 + 1.5 * np.random.rand() # 缩放因子
d = f * (p1 - p2)
temp_p = best + d
temp_p[temp_p > moead.Test_fun.Bound[1]] = moead.Test_fun.Bound[0] + (
moead.Test_fun.Bound[1] - moead.Test_fun.Bound[0]) * np.random.rand()
temp_p[temp_p < moead.Test_fun.Bound[0]] = moead.Test_fun.Bound[0] + (
moead.Test_fun.Bound[1] - moead.Test_fun.Bound[0]) * np.random.rand()
return temp_p
def crossover(moead, p1, vi):
3
Source : GA_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def Creat_child(moead):
# 创建一个个体
child = moead.Test_fun.Bound[0] + (moead.Test_fun.Bound[1] - moead.Test_fun.Bound[0]) * np.random.rand(
moead.Test_fun.Dimention)
return child
def Creat_Pop(moead):
3
Source : GA_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def mutate(moead, p1):
# 突变个体的策略1
var_num = moead.Test_fun.Dimention
for i in range(int(var_num * 0.1)):
d = moead.Test_fun.Bound[0] + (moead.Test_fun.Bound[1] - moead.Test_fun.Bound[0]) * np.random.rand()
d = d * np.random.randint(-1, 1)
d = d / 10
j = np.random.randint(0, var_num, size=1)[0]
p1[j] = p1[j] + d
return p1
def mutate2(moead, y1):
3
Source : GA_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def mutate2(moead, y1):
# 突变个体的策略2
dj = 0
uj = np.random.rand()
if uj < 0.5:
dj = (2 * uj) ** (1 / 6) - 1
else:
dj = 1 - 2 * (1 - uj) ** (1 / 6)
y1 = y1 + dj
y1[y1 > moead.Test_fun.Bound[1]] = moead.Test_fun.Bound[1]
y1[y1 < moead.Test_fun.Bound[0]] = moead.Test_fun.Bound[0]
return y1
def crossover(moead, pop1, pop2):
3
Source : GA_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def crossover(moead, pop1, pop2):
# 交叉个体的策略1
var_num = moead.Test_fun.Dimention
r1 = int(var_num * np.random.rand())
if np.random.rand() < 0.5:
pop1[:r1], pop2[:r1] = pop2[:r1], pop1[:r1]
else:
pop1[r1:], pop2[r1:] = pop2[r1:], pop1[r1:]
return pop1, pop2
def crossover2(moead, y1, y2):
3
Source : GA_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def crossover2(moead, y1, y2):
# 交叉个体的策略2
var_num = moead.Test_fun.Dimention
yj = 0
uj = np.random.rand()
if uj < 0.5:
yj = (2 * uj) ** (1 / 3)
else:
yj = (1 / (2 * (1 - uj))) ** (1 / 3)
y1 = 0.5 * (1 + yj) * y1 + (1 - yj) * y2
y2 = 0.5 * (1 - yj) * y1 + (1 + yj) * y2
y1[y1 > moead.Test_fun.Bound[1]] = moead.Test_fun.Bound[1]
y1[y1 < moead.Test_fun.Bound[0]] = moead.Test_fun.Bound[0]
y2[y2 > moead.Test_fun.Bound[1]] = moead.Test_fun.Bound[1]
y2[y2 < moead.Test_fun.Bound[0]] = moead.Test_fun.Bound[0]
return y1, y2
def EO(moead, wi, p1):
3
Source : MOEAD_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def cpt_Z2(moead):
# 初始化Z集,最小问题0,0,..
Z = moead.Pop_FV[0][:]
dz = np.random.rand()
for fi in range(moead.Test_fun.Func_num):
for Fpi in moead.Pop_FV:
if moead.problem_type == 0:
if Fpi[fi] < Z[fi]:
Z[fi] = Fpi[fi] - dz
if moead.problem_type == 1:
if Fpi[fi] > Z[fi]:
Z[fi] = Fpi[fi] + dz
moead.Z = Z
return Z
# 计算初始化前沿
def init_EP(moead):
3
Source : MOEAD_Utils.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def update_Z(moead, Y):
# 根据Y更新Z坐标。。ps:实验结论:如果你知道你的目标,比如是极小化了,且理想极小值(假设2目标)是[0,0],
# 那你就一开始的时候就写死moead.Z=[0,0]把
dz = np.random.rand()
F_y = moead.Test_fun.Func(Y)
for j in range(moead.Test_fun.Func_num):
if moead.problem_type == 0: # minimize
if moead.Z[j] > F_y[j]:
moead.Z[j] = F_y[j] - dz
if moead.problem_type == 1: # maximize
if moead.Z[j] < F_y[j]:
moead.Z[j] = F_y[j] + dz
def update_EP_By_Y(moead, id_Y):
3
Source : TSP_GA.py
with Apache License 2.0
from 425776024
with Apache License 2.0
from 425776024
def mutate(self, gene):
"""突变"""
if np.random.rand() > self.m_rate:
return gene
index1 = np.random.randint(0, self.city_size - 1)
index2 = np.random.randint(index1, self.city_size - 1)
newGene = self.reverse_gen(gene, index1, index2)
if newGene.shape[0] != self.city_size:
print('m error')
return self.creat_pop(1)
return newGene
def reverse_gen(self, gen, i, j):
3
Source : util.py
with MIT License
from 524243642
with MIT License
from 524243642
def zsl_random_level():
level = 1
while random.rand() < ZSKIPLIST_P:
level += 1
return level if (level < ZSKIPLIST_MAXLEVEL) else ZSKIPLIST_MAXLEVEL
def elecmp(s1, s2):
3
Source : SGD.py
with MIT License
from 93xiaoming
with MIT License
from 93xiaoming
def gradient_descent(x, dim, learning_rate, num_iterations):
for i in range(num_iterations):
v=np.random.rand(dim)
xp=x+v*delta
xm=x-v*delta
error_derivative = (cost(xp) - cost(xm))/(2*delta)
x = x - (learning_rate) * error_derivative*v
cost_hist.append(cost(xp))
return cost(x)
N = 20
3
Source : async_bo.py
with MIT License
from a5a
with MIT License
from a5a
def draw_gp_samples(self, x, n_samples):
"""
Draw GP samples
:param num_sample: number of samples to be draw
:param x: test inputs (Nxd)
:return: a sample from GP (Nx1)
"""
mu, cov = self.surrogate.predict(x, full_cov=True)
# draw GP sample
L = stable_cholesky(cov)
U = np.random.rand(x.shape[0], n_samples)
f_samples = L.dot(U) + mu
return f_samples
def rand_maximiser(self, obj_f, gridSize=10000):
3
Source : executor.py
with MIT License
from a5a
with MIT License
from a5a
def _add_running_time_to_job(self, job) -> dict:
if self._time_func is not None:
job['t'] = self._time_func()
else:
job['t'] = np.random.rand()
return job
class SimExecutorIntegerTicks(SimExecutor):
3
Source : train.py
with MIT License
from abeja-inc
with MIT License
from abeja-inc
def transform(in_data):
img, label = in_data
if np.random.rand() > 0.5:
img = img[:, :, ::-1]
label = label[:, ::-1]
return img, label
def calc_weight(dataset):
3
Source : train.py
with MIT License
from abeja-inc
with MIT License
from abeja-inc
def __call__(self, image):
image *= (2.0 / 255.0)
image -= 1
if self._train and np.random.rand() > 0.5:
image = image[:, ::-1, :]
return image
class ToTensor(object):
3
Source : common.py
with MIT License
from abrazinskas
with MIT License
from abrazinskas
def generate_data_chunk(data_attrs_number, data_size):
"""Generated a data-chunk with random 1D values of data_size."""
data = {str(i): np.random.rand(data_size) for
i in range(data_attrs_number)}
data_chunk = DataChunk(**data)
return data_chunk
def read_data_from_csv_file(file_path, **kwargs):
3
Source : test_data_chunks.py
with MIT License
from abrazinskas
with MIT License
from abrazinskas
def test_field_values_access(self):
arrays_size = 40
names = ["one", "two", "three", "four"]
for _ in range(10):
data = {name: np.random.rand(arrays_size, 1) for name in names}
data_chunk = DataChunk(**deepcopy(data))
for name in names:
self.assertTrue((data_chunk[name] == data[name]).all())
def test_specific_fvalues_access(self):
3
Source : test_data_chunks.py
with MIT License
from abrazinskas
with MIT License
from abrazinskas
def test_specific_fvalues_access(self):
arrays_size = 40
names = ["one", "two", "three", "four"]
for _ in range(10):
data = {name: np.random.rand(arrays_size) for name in names}
data_chunk = DataChunk(**deepcopy(data))
for r_name in np.random.choice(names, size=10, replace=True):
for r_indx in np.random.randint(0, 40, size=100):
res = (data_chunk[r_indx, r_name] == data[r_name][r_indx])
self.assertTrue(res)
def test_data_units_inval_access(self):
3
Source : ea.py
with GNU General Public License v3.0
from acamero
with GNU General Public License v3.0
from acamero
def gaussianMutation(encoded,
p_mutation,
mutation_scale_factor=1):
""" Element-wise Gaussian mutation
Performs a Gaussian mutation on the i-th encoded variable
with a probability p_mutation.
"""
for i in range(len(encoded)):
if np.random.rand() < p_mutation:
encoded[i] += np.random.normal(
scale=mutation_scale_factor)
def uniformMutation(encoded,
3
Source : ea.py
with GNU General Public License v3.0
from acamero
with GNU General Public License v3.0
from acamero
def uniformMutation(encoded,
p_mutation,
mutation_max_step=1):
""" Element-wise uniform mutation
Performs a uniform step mutation on the i-th encoded variable
with a probability p_mutation.
"""
for i in range(len(encoded)):
if np.random.rand() < p_mutation:
step = np.max([1, np.random.randint(0, mutation_max_step)])
if np.random.rand() < 0.5:
step = -1 * step
encoded[i] += step
def uniformLengthMutation(encoded,
3
Source : ea.py
with GNU General Public License v3.0
from acamero
with GNU General Public License v3.0
from acamero
def uniformLengthMutation(encoded,
p_mutation):
""" With p_mutation probability copy/delete an encoded variable
"""
if np.random.rand() < p_mutation:
position = np.random.randint(0,
len(encoded))
if np.random.rand() < 0.5:
encoded.pop(position)
else:
encoded.insert(position,
encoded[position])
def binaryTournament(population):
3
Source : algorithms.py
with GNU General Public License v3.0
from acamero
with GNU General Public License v3.0
from acamero
def _mate(self, ind1, ind2):
if np.random.rand() < self.config.cx_prob:
tools.cxOnePoint(ind1, ind2)
del ind1.fitness.values
del ind2.fitness.values
def _mutate(self, ind):
3
Source : texture.py
with Apache License 2.0
from achao2013
with Apache License 2.0
from achao2013
def random_tex_para(n_tex_para = 199):
tp = np.random.rand(n_tex_para, 1)
#C = sio.loadmat('Data/para.mat')
#sp = C['alpha']
return tp
def generate_texture(model, tex_para = np.zeros((199, 1))):
See More Examples