Simple 1D classification example using EP approximation

    :param seed: seed value for data generation (default is 4).
    :type seed: int
778032
def toy_linear_1d_classification(seed=default_seed, optimize=True, plot=True):
    
    try:import pods
    except ImportError:raise ImportWarning('Need pods for example datasets. See https://github.com/sods/ods, or pip install pods.')
    data = pods.datasets.toy_linear_1d_classification(seed=seed)
    Y = data['Y'][:, 0:1]
    Y[Y.flatten() == -1] = 0

    # Model definition
    m = GPy.models.GPClassification(data['X'], Y)

    # Optimize
    if optimize:
        #m.update_likelihood_approximation()
        # Parameters optimization:
        m.optimize()
        #m.update_likelihood_approximation()
        #m.pseudo_EM()

    # Plot
    if plot:
        from matplotlib import pyplot as plt
        fig, axes = plt.subplots(2, 1)
        m.plot_f(ax=axes[0])
        m.plot(ax=axes[1])

    print(m)
    return m
1368935
def oil(num_inducing=50, max_iters=100, kernel=None, optimize=True, plot=True):
    
    try:import pods
    except ImportError:raise ImportWarning('Need pods for example datasets. See https://github.com/sods/ods, or pip install pods.')
    data = pods.datasets.oil()
    X = data['X']
    Xtest = data['Xtest']
    Y = data['Y'][:, 0:1]
    Ytest = data['Ytest'][:, 0:1]
    Y[Y.flatten()==-1] = 0
    Ytest[Ytest.flatten()==-1] = 0

    # Create GP model
    m = GPy.models.SparseGPClassification(X, Y, kernel=kernel, num_inducing=num_inducing)
    m.Ytest = Ytest

    # Contrain all parameters to be positive
    #m.tie_params('.*len')
    m['.*len'] = 10.

    # Optimize
    if optimize:
        m.optimize(messages=1)
    print(m)

    #Test
    probs = m.predict(Xtest)[0]
    GPy.util.classification.conf_matrix(probs, Ytest)
    return m
1186363
def check_manual_seed(seed):
    

    seed = seed or random.randint(1, 10000)
    random.seed(seed)
    torch.manual_seed(seed)

    print('Using manual seed: {seed}'.format(seed=seed))
1252934
def smart_initialize(self):
        ''''''
        if self.seed is not None: # useful for obtaining consistent results
            np.random.seed(self.seed)
        centroids = np.zeros((self.k, self.data.shape[1]))
        # Randomly choose the first centroid.
        # Since we have no prior knowledge, choose uniformly at random
        idx = np.random.randint(self.data.shape[0])
        centroids[0] = self.data[idx,:].toarray()
        # Compute distances from the first centroid chosen to all the other data points
        squared_distances = pairwise_distances(self.data, centroids[0:1], metric='euclidean').flatten()**2
        for i in range(1, self.k):
            # Choose the next centroid randomly, so that the probability for each data point to be chosen
            # is directly proportional to its squared distance from the nearest centroid.
            # Roughtly speaking, a new centroid should be as far as from ohter centroids as possible.
            idx = np.random.choice(self.data.shape[0], 1, p=squared_distances/sum(squared_distances))
            centroids[i] = self.data[idx,:].toarray()
            # Now compute distances from the centroids to all data points
            squared_distances = np.min(pairwise_distances(self.data, centroids[0:i+1], metric='euclidean')**2,axis=1)
        self.centroids=centroids
        return centroids
562361
def set_seed(self, rho_seed, mu_seed):

        

        self.rho = rho_seed
        self.mu = mu_seed
494070
public Random getNewRandomInstance(long seed, long size) {
        try {
            Class<?> c = randomClass;
            Constructor<?> constructor = c.getConstructor(long.class, long.class);
            Random t = (Random) constructor.newInstance(seed, size);
            return t;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
859576
def get_seeds(self, threshold):
        
        seeds = []
        for e1, e2 in self.superArcs:
            # Because we did some extra work in _process_tree, we can
            # safely assume e1 is lower than e2
            if self.Y[e1] <= threshold <= self.Y[e2]:
                if (e1, e2) in self.augmentedEdges:
                    # These should be sorted
                    edgeList = self.augmentedEdges[(e1, e2)]
                elif (e2, e1) in self.augmentedEdges:
                    e1, e2 = e2, e1
                    # These should be reverse sorted
                    edgeList = list(reversed(self.augmentedEdges[(e1, e2)]))
                else:
                    continue

                startNode = e1
                for endNode in edgeList + [e2]:
                    if self.Y[endNode] >= threshold:
                        # Stop when you find the first point above the
                        # threshold
                        break
                    startNode = endNode

                seeds.append(startNode)
                seeds.append(endNode)
        return seeds
1145235
def seed_rngs(seed: int) -> None:
    
    np.random.seed(seed)
    random.seed(seed)
    mx.random.seed(seed)
482315
private final void setSeed(int seed) {

		// Annoying runtime check for initialisation of internal data
		// caused by java.util.Random invoking setSeed() during init.
		// This is unavoidable because no fields in our instance will
		// have been initialised at this point, not even if the code
		// were placed at the declaration of the member variable.
		if (mt == null) mt = new int[N];

		// ---- Begin Mersenne Twister Algorithm ----
		mt[0] = seed;
		for (mti = 1; mti < N; mti++) {
			mt[mti] = (MAGIC_FACTOR1 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti);
		}
		// ---- End Mersenne Twister Algorithm ----
	}
17224
def _append_seed_handle_nodes(self, seed_type: str, nodes: MaybeNodeList) -> 'Seeding':
        
        return self._append_seed(seed_type, _handle_nodes(nodes))
238810
public static CipherUtil buildInstance(Algorithms algorithms, String seed) {
        int keySize = 0;
        if (algorithms == Algorithms.AES) {
            keySize = 128;
        } else if (algorithms == Algorithms.DES) {
            keySize = 56;
        }
        return buildInstance(algorithms, seed, keySize);
    }
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'])
283991
public static void seed(long seed) {
        System.out.println("SEED="+seed);
        Prng.seed = seed;
        curRandom.setSeed(seed);
    }
647082
def _set_random_seeds():
    
    try:
        import numpy as np
        np.random.seed()
    except:
        pass

    try:
        import scipy as sp
        sp.random.seed()
    except:
        pass

    import random
    random.seed()
453779
def append_sample(self, **kwargs) -> 'Seeding':
        
        data = {
            'seed': random.randint(0, 1000000)
        }
        data.update(kwargs)

        return self._append_seed(SEED_TYPE_SAMPLE, data)
1044213
def bootstrap(self, mc_bit=0x10, seed=None):
        
        if seed is not None: np.random.seed(seed)
        data = copy.deepcopy(self.data)
        idx = np.random.randint(0,len(data),len(data))
        data[self.config['catalog']['mag_1_field']][:] = self.mag_1[idx]
        data[self.config['catalog']['mag_err_1_field']][:] = self.mag_err_1[idx]
        data[self.config['catalog']['mag_2_field']][:] = self.mag_2[idx]
        data[self.config['catalog']['mag_err_2_field']][:] = self.mag_err_2[idx]
        data[self.config['catalog']['mc_source_id_field']][:] |= mc_bit
        return Catalog(self.config, data=data)
906029
def expand_seed(self, start_seed, num_iterations, val):
        
        self.grd.set_tile(start_seed[0], start_seed[1], val)
        cur_pos = [start_seed[0], start_seed[1]]
        while num_iterations > 0:   # don't use loop as it will hit boundaries often
            num_iterations -= 1
            for y in range(cur_pos[0]-randint(0,2), cur_pos[0] + randint(0,2)):
                for x in range(cur_pos[1]-randint(0,2), cur_pos[1] + randint(0,2)):
                    if x < self.grd.grid_width and x >= 0 and y >= 0 and y < self.grd.grid_height:
                        #print(x,y,val)
                        if self.grd.get_tile(y,x) != val:
                            self.grd.set_tile(y, x, TERRAIN_LAND)
                            num_iterations -= 1
            new_x = cur_pos[0] + randint(0,3)-2
            new_y = cur_pos[1] + randint(0,3)-2
            if new_x > self.grd.grid_width - 1:
                new_x = 0
            if new_y > self.grd.grid_height - 1:
                new_y = 0
            if new_x < 0:
                new_x = self.grd.grid_width - 1
            if new_y < 0:
                new_y = self.grd.grid_height - 1
            cur_pos = [new_y, new_x]