Set random seed for numpy and tensorflow packages
16578
def _set_seed(self):
        
        if self.flags['SEED'] is not None:
            tf.set_random_seed(self.flags['SEED'])
            np.random.seed(self.flags['SEED'])
1056404
def randomize(self, force = 0):
        
        if force or not self.frozen:
            self.weight = randomArray(self.size, self._maxRandom)
407197
def random_normal(attrs, inputs, proto_obj):
    """"""
    try:
        from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
    except ImportError:
        raise ImportError("Onnx and protobuf need to be installed. "
                          "Instructions to install - https://github.com/onnx/onnx")
    new_attr = translation_utils._remove_attributes(attrs, ['seed'])
    new_attr = translation_utils._fix_attribute_names(new_attr, {'mean': 'loc'})
    new_attr['dtype'] = TENSOR_TYPE_TO_NP_TYPE[int(new_attr.get('dtype', 1))]
    return 'random_normal', new_attr, inputs
985675
def _init_parameters_random(self, X_bin):
        

        _, n_features = X_bin.shape

        # The parameter class_log_prior_ has shape (2,). The values represent
        # 'match' and 'non-match'.
        rand_vals = np.random.rand(2)
        class_prior = rand_vals / np.sum(rand_vals)

        # make empty array of feature log probs
        # dimensions 2xn_features
        feature_prob = np.zeros((2, n_features))

        feat_i = 0

        for i, bin in enumerate(self._binarizers):

            bin_len = bin.classes_.shape[0]

            rand_vals_0 = np.random.rand(bin_len)
            feature_prob[0, feat_i:feat_i + bin_len] = \
                rand_vals_0 / np.sum(rand_vals_0)

            rand_vals_1 = np.random.rand(bin_len)
            feature_prob[1, feat_i:feat_i + bin_len] = \
                rand_vals_1 / np.sum(rand_vals_1)

            feat_i += bin_len

        return np.log(class_prior), np.log(feature_prob)
879916
def set_state(seed_value=None, step=None):
    """"""
    global RANDOM_SEED  # pylint: disable=global-statement
    if seed_value is not None:
        RANDOM_SEED = seed_value
    if step is not None:
        RANDOM_SEED += step
1050076
def RandomUniformInt(shape, minval, maxval, seed):
    
    if seed:
        np.random.seed(seed)
    return np.random.randint(minval, maxval, size=shape),
827017
def ensure_rng(random_state=None):
    
    if random_state is None:
        random_state = np.random.RandomState()
    elif isinstance(random_state, int):
        random_state = np.random.RandomState(random_state)
    else:
        assert isinstance(random_state, np.random.RandomState)
    return random_state
651599
@Override
    public INDArray randn(int[] shape, long seed) {
        Nd4j.getRandom().setSeed(seed);
        return randn(shape, Nd4j.getRandom());
    }
35910
def _fully_random_weights(n_features, lam_scale, prng):
    """"""
    weights = np.zeros((n_features, n_features))
    n_off_diag = int((n_features ** 2 - n_features) / 2)
    weights[np.triu_indices(n_features, k=1)] = 0.1 * lam_scale * prng.randn(
        n_off_diag
    ) + (0.25 * lam_scale)
    weights[weights < 0] = 0
    weights = weights + weights.T
    return weights
579731
def make_random_MLdataset(max_num_classes = 20,
                          min_class_size = 20,
                          max_class_size = 50,
                          max_dim = 100,
                          stratified = True):
    ""

    smallest = min(min_class_size, max_class_size)
    max_class_size = max(min_class_size, max_class_size)
    largest = max(50, max_class_size)
    largest = max(smallest+3,largest)

    if max_num_classes != 2:
        num_classes = np.random.randint(2, max_num_classes, 1)
    else:
        num_classes = 2

    if type(num_classes) == np.ndarray:
        num_classes = num_classes[0]
    if not stratified:
        class_sizes = np.random.random_integers(smallest, largest, num_classes)
    else:
        class_sizes = np.repeat(np.random.randint(smallest, largest), num_classes)

    num_features = np.random.randint(min(3, max_dim), max(3, max_dim), 1)[0]
    # feat_names = [ str(x) for x in range(num_features)]

    class_ids = list()
    labels = list()
    for cl in range(num_classes):
        class_ids.append('class-{}'.format(cl))
        labels.append(int(cl))

    ds = MLDataset()
    for cc, class_ in enumerate(class_ids):
        subids = [ 's{}-c{}'.format(ix,cc) for ix in range(class_sizes[cc]) ]
        for sid in subids:
            ds.add_sample(sid, feat_generator(num_features), int(cc), class_)

    return ds
494489
def generator(ngf, nc, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12, z_dim=100, activation='sigmoid'):
    '''
    '''
    BatchNorm = mx.sym.BatchNorm
    rand = mx.sym.Variable('rand')

    rand = mx.sym.Reshape(rand, shape=(-1, z_dim, 1, 1))

    g1 = mx.sym.Deconvolution(rand, name='gen1', kernel=(5,5), stride=(2,2),target_shape=(2,2), num_filter=ngf*8, no_bias=no_bias)
    gbn1 = BatchNorm(g1, name='genbn1', fix_gamma=fix_gamma, eps=eps)
    gact1 = mx.sym.Activation(gbn1, name="genact1", act_type="relu")

    g2 = mx.sym.Deconvolution(gact1, name='gen2', kernel=(5,5), stride=(2,2),target_shape=(4,4), num_filter=ngf*4, no_bias=no_bias)
    gbn2 = BatchNorm(g2, name='genbn2', fix_gamma=fix_gamma, eps=eps)
    gact2 = mx.sym.Activation(gbn2, name='genact2', act_type='relu')

    g3 = mx.sym.Deconvolution(gact2, name='gen3', kernel=(5,5), stride=(2,2), target_shape=(8,8), num_filter=ngf*2, no_bias=no_bias)
    gbn3 = BatchNorm(g3, name='genbn3', fix_gamma=fix_gamma, eps=eps)
    gact3 = mx.sym.Activation(gbn3, name='genact3', act_type='relu')

    g4 = mx.sym.Deconvolution(gact3, name='gen4', kernel=(5,5), stride=(2,2), target_shape=(16,16), num_filter=ngf, no_bias=no_bias)
    gbn4 = BatchNorm(g4, name='genbn4', fix_gamma=fix_gamma, eps=eps)
    gact4 = mx.sym.Activation(gbn4, name='genact4', act_type='relu')

    g5 = mx.sym.Deconvolution(gact4, name='gen5', kernel=(5,5), stride=(2,2), target_shape=(32,32), num_filter=nc, no_bias=no_bias)
    gout = mx.sym.Activation(g5, name='genact5', act_type=activation)

    return gout
125275
def random_mini_batches(X, Y, minibatch_size, seed=None):
  
  d    = X.shape[1]
  size = minibatch_size
  minibatches = []

  if Y is None:
      Y = np.zeros((1, d))

  np.random.seed(seed)
  perm = np.random.permutation(d)

  for t in range(0, d, size):
      subset = perm[t: t+size]
      minibatches.append((X[:, subset], Y[:, subset]))

  return minibatches
942048
def _rand_init(x_bounds, x_types, selection_num_starting_points):
    '''
    
    '''
    return [lib_data.rand(x_bounds, x_types) for i \
                    in range(0, selection_num_starting_points)]
1192341
def __gen_random_values(self):
        '''
        '''

        values = []
        if self._value_ranges is None:
            self._logger.log(
                'crit',
                'Must set the type/range of possible values'
            )
            raise RuntimeError("Must set the type/range of possible values")
        else:
            for t in self._value_ranges:
                if t[0] == 'int':
                    values.append(randint(t[1][0], t[1][1]))
                elif t[0] == 'float':
                    values.append(np.random.uniform(t[1][0], t[1][1]))
                else:
                    self._logger.log(
                        'crit',
                        'Value type must be either an `int` or a `float`'
                    )
                    raise RuntimeError(
                        'Value type must be either an `int` or a `float`'
                    )
        return values
1107720
private void setUp(Random rand)
    {
        Ws = new ArrayList<>(npl.length);
        bs = new ArrayList<>(npl.length);
        
        //First Hiden layer takes input raw
        DenseMatrix W = new DenseMatrix(npl[0], inputSize);
        Vec b = new DenseVector(W.rows());
        initializeWeights(W, rand);
        initializeWeights(b, W.cols(), rand);
        Ws.add(W);
        bs.add(b);
        
        //Other Hiden Layers Layers 
        for(int i = 1; i < npl.length; i++)
        {
            W = new DenseMatrix(npl[i], npl[i-1]);
            b = new DenseVector(W.rows());
            initializeWeights(W, rand);
            initializeWeights(b, W.cols(), rand);
            Ws.add(W);
            bs.add(b);
        }
        
        //Output layer
        W = new DenseMatrix(outputSize, npl[npl.length-1]);
        b = new DenseVector(W.rows());
        initializeWeights(W, rand);
        initializeWeights(b, W.cols(), rand);
        Ws.add(W);
        bs.add(b);
        
    }
123084
def run_mnist():
  """"""
  mnist_classifier = tf.estimator.Estimator(
      model_fn=model_fn,
      model_dir=FLAGS.model_dir)

  # Set up training and evaluation input functions.
  def train_input_fn():
    """Prepare data for training."""

    # When choosing shuffle buffer sizes, larger sizes result in better
    # randomness, while smaller sizes use less memory. MNIST is a small
    # enough dataset that we can easily shuffle the full epoch.
    ds = dataset.train(FLAGS.data_dir)
    ds_batched = ds.cache().shuffle(buffer_size=50000).batch(FLAGS.batch_size)

    # Iterate through the dataset a set number (`epochs_between_evals`) of times
    # during each training session.
    ds = ds_batched.repeat(FLAGS.epochs_between_evals)
    return ds

  def eval_input_fn():
    return dataset.test(FLAGS.data_dir).batch(
        FLAGS.batch_size).make_one_shot_iterator().get_next()

  # Train and evaluate model.
  for _ in range(FLAGS.train_epochs // FLAGS.epochs_between_evals):
    mnist_classifier.train(input_fn=train_input_fn, hooks=None)
    eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)
    print("\nEvaluation results:\n\t%s\n" % eval_results)
99931
def run(self):
        """"""
        random.seed(self.seed)
        np.random.seed(self.np_seed)
        if not isinstance(self, multiprocessing.Process):
            # Calling mxnet methods in a subprocess will raise an exception if
            # mxnet is built with GPU support
            # https://github.com/apache/incubator-mxnet/issues/4659
            mx.random.seed(self.mx_seed)

        # Startup - Master waits for this
        try:
            stream_iter = iter(self.stream)
            self._errorq.put(None)
        except Exception as e:  # pylint: disable=broad-except
            tb = traceback.format_exc()
            self._errorq.put((e, tb))

        # Async work
        while True:
            try:  # Check control queue
                c = self._controlq.get(False)
                if c is None:
                    break
                else:
                    raise RuntimeError('Got unexpected control code {}'.format(repr(c)))
            except queue.Empty:
                pass
            except RuntimeError as e:
                tb = traceback.format_exc()
                self._errorq.put((e, tb))
                self._dataq.put(None)

            try:
                data = next(stream_iter)
                error = None
            except Exception as e:  # pylint: disable=broad-except
                tb = traceback.format_exc()
                error = (e, tb)
                data = None
            finally:
                self._errorq.put(error)
                self._dataq.put(data)