numpy.eye

Here are the examples of the python api numpy.eye taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

173 Examples 7

Example 1

Project: krypy Source File: test_utils.py
Function: test_projection
def test_projection():
    Xs = [numpy.eye(10, 1),
          numpy.eye(10, 5),
          numpy.eye(10, 5) + 1e-1*numpy.ones((10, 5)),
          numpy.eye(10),
          numpy.zeros((10, 0))
          ]
    ip_Bs = get_ip_Bs()
    its = [1, 2, 3]
    for (X, ip_B, iterations) in itertools.product(Xs, ip_Bs, its):
        Ys = [None, X, X + numpy.ones((10, X.shape[1]))]
        for Y in Ys:
            yield run_projection, X, Y, ip_B, iterations

Example 2

Project: ikpy Source File: test_poppy_robots.py
    def test_ergo(self):
        a = chain.Chain.from_urdf_file(params.resources_path + "/poppy_ergo.URDF")
        target = [0.1, -0.2, 0.1]
        frame_target = np.eye(4)
        frame_target[:3, 3] = target
        joints = [0] * len(a.links)
        ik = a.inverse_kinematics(frame_target, initial_position=joints)

        if plot:
            ax = plot_utils.init_3d_figure()

        if plot:
            a.plot(ik, ax, target=target)
            plot_utils.show_figure()

Example 3

Project: glumpy Source File: transform.py
Function: matrix
    @property
    def matrix(self):
        M = np.eye(3)
        for transform in self._transforms:
            M = np.dot(M,transform)
        return M

Example 4

Project: orange Source File: orngMisc.py
Function: init
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.render_state = {}
        self.render_state["font"] = ("Times-Roman", 10)
        self.render_state["fill_color"] = (0, 0, 0)
        self.render_state["gradient"] = {}
        self.render_state["stroke_color"] = (0, 0, 0)
        self.render_state["stroke_width"] = 1
        self.render_state["text_alignment"] = self.ALIGN_LEFT
        self.render_state["transform"] = numpy.matrix(numpy.eye(3))
        self.render_state["view_transform"] = numpy.matrix(numpy.eye(3))
        self.render_state["render_hints"] = {}
        self.render_state_stack = []

Example 5

Project: rayopt Source File: elements.py
    def paraxial_matrix(self, n0, l):
        m = np.eye(4)
        # 4x4 block matrix, M = [[A, B], [C, D]], A is 2x2 tan sag
        d = self.distance
        m[0, 2] = m[1, 3] = d/n0
        return n0, m

Example 6

Project: fos Source File: vsml.py
Function: init
    def __init__(self):
        self.projection = np.eye(4)
        self.modelview = np.eye(4)

        # setting up the stacks
        self.mMatrixStack = {}

        # use list as stack
        self.mMatrixStack[self.MatrixTypes.MODELVIEW] = []
        self.mMatrixStack[self.MatrixTypes.PROJECTION] = []

Example 7

Project: kombine Source File: tests.py
Function: init
    def __init__(self, nmodes=1, ndim=2):
        self.nmodes = nmodes
        self.ndim = ndim

        dx = 1./(self.nmodes + 1)
        self.cov = .005*dx*np.eye(self.ndim)
        means = (1.+np.arange(nmodes))*dx
        self.means = np.column_stack([means for dim in range(self.ndim)])

Example 8

Project: python-rl Source File: lstd.py
    def updateWeights(self):
        B = numpy.eye(self.weights.size) * self.precond
        b = numpy.zeros(self.weights.size)
        for sample in self.samples[:self.lstd_counter]:
            s, s_p, r = self.extractSample(sample)
            B = matrix.SMInv(B, s, (s - self.lstd_gamma * s_p), 1.0)
            b += s * r
        self.weights = numpy.dot(B, b).reshape(self.weights.shape)

Example 9

Project: PyParticles Source File: transformations.py
Function: init
    def __init__(self):
        self.__cmatrix = np.matrix( np.eye( 4 ) )
        self.__stack = list( [] )
        self.__points = deque( [] )
        
        self.__p = np.matrix( np.zeros( ( 4,1 ) ) )
        self.__nr = 1

Example 10

Project: instaseis Source File: rotations.py
def rotate_vector_xyz_src_to_xyz_rec(vec, srclon, srccolat, reclon, reccolat):
    rotmat = np.eye(3)
    rotmat = rotate_vector_xyz_src_to_xyz_earth(rotmat, srclon, srccolat)
    rotmat = rotate_vector_xyz_earth_to_xyz_src(rotmat, reclon, reccolat)

    return np.dot(rotmat, vec)

Example 11

Project: pyhawkes Source File: standard_bfgs_demo.py
Function: sample_from_network_hawkes
def sample_from_network_hawkes(C, K, T, dt, dt_max, B):
    # Create a true model
    p = 0.8 * np.eye(C)
    v = 10.0 * np.eye(C) + 20.0 * (1-np.eye(C))
    c = (0.0 * (np.arange(K) < 10) + 1.0 * (np.arange(K)  >= 10)).astype(np.int)
    true_model = DiscreteTimeNetworkHawkesModelSpikeAndSlab(C=C, K=K, dt=dt, dt_max=dt_max,
                                                            B=B, c=c, p=p, v=v)

    # Plot the true network
    plt.ion()
    plot_network(true_model.weight_model.A,
                 true_model.weight_model.W,
                 vmax=0.5)

    # Sample from the true model
    S,R = true_model.generate(T=T)

    # Return the spike count matrix
    return S, true_model

Example 12

Project: APGL Source File: Parameter.py
    @staticmethod
    def checkOrthogonal(A, tol=10**-6, softCheck = False, investigate = False, arrayInfo = "?"):
        """
        Takes as input a matrix A and checks if it is orthogonal by verifying whether
        ||A*A.T - Id||_F < tol.
        """
        diff = numpy.linalg.norm(A.conj().T.dot(A) - numpy.eye(A.shape[1]))
        if diff > tol:
            try :
                return Parameter.whatToDo("Non-orthogonal matrix A=" + arrayInfo + ": ||A*A.T - Id||_F = " + str(diff), softCheck)
            finally : # s.t. when raising an error, the investigation appears after
                if investigate:
                    Diff = A.conj().T.dot(A) - numpy.eye(A.shape[1])
                    print("indexes:\n", (abs(Diff)>tol).nonzero())
                    print("values\n", Diff[abs(Diff)>tol])
        return True

Example 13

Project: decoding-brain-challenge-2016 Source File: tangentspace.py
    def _check_reference_points(self, X):
        """Check reference point status, and force it to identity if not."""
        if not hasattr(self, 'reference_'):
            self.reference_ = numpy.eye(self._check_data_dim(X))
        else:
            shape_cr = self.reference_.shape[0]
            shape_X = self._check_data_dim(X)

            if shape_cr != shape_X:
                raise ValueError('Data must be same size of reference point.')

Example 14

Project: pi-tracking-telescope Source File: common.py
def mtx2rvec(R):
    w, u, vt = cv2.SVDecomp(R - np.eye(3))
    p = vt[0] + u[:,0]*w[0]    # same as np.dot(R, vt[0])
    c = np.dot(vt[0], p)
    s = np.dot(vt[1], p)
    axis = np.cross(vt[0], vt[1])
    return axis * np.arctan2(s, c)

Example 15

Project: pycortex Source File: mayavi_aligner.py
    @on_trait_change("flip_ud")
    def update_flipud(self):
        #self.epi_src.scalar_data = self.epi_src.scalar_data[:,:,::-1]
        flip = np.eye(4)
        flip[2,2] = -1
        mat = self.xfm.transform.matrix.to_array()
        self.set_xfm(np.dot(mat, flip), "base")

Example 16

Project: scikit-learn Source File: test_gmm.py
Function: set_up
    def _setUp(self):
        self.n_components = 10
        self.n_features = 4
        self.weights = rng.rand(self.n_components)
        self.weights = self.weights / self.weights.sum()
        self.means = rng.randint(-20, 20, (self.n_components, self.n_features))
        self.threshold = -0.5
        self.I = np.eye(self.n_features)
        self.covars = {
            'spherical': (0.1 + 2 * rng.rand(self.n_components,
                                             self.n_features)) ** 2,
            'tied': (make_spd_matrix(self.n_features, random_state=0)
                     + 5 * self.I),
            'diag': (0.1 + 2 * rng.rand(self.n_components,
                                        self.n_features)) ** 2,
            'full': np.array([make_spd_matrix(self.n_features, random_state=0)
                              + 5 * self.I for x in range(self.n_components)])}

Example 17

Project: FreeCAD_assembly2 Source File: lib3D.py
Function: euler_rotation
def euler_rotation(p, angle1, angle2, angle3, axis1=3, axis2=2, axis3=3 ):
    ''' http://en.wikipedia.org/wiki/Rotation_matrix ,
    axis1=1, axis2=2, axis3=3 is the same as euler_ZYX_rotation'''
    R = numpy.eye(3)
    for angle,axis in zip([angle1,angle2,angle3],[axis1,axis2,axis3]):
        s = sin(angle)
        c = cos(angle)
        if axis == 1: #x rotation
            R_i = numpy.array([ [ 1, 0, 0], [ 0, c,-s], [ 0, s, c] ])
        elif axis == 2: # y rotation
            R_i = numpy.array([ [ c, 0, s], [ 0, 1, 0], [-s, 0, c] ])
        else: #z rotation
            R_i = numpy.array([ [ c,-s, 0], [ s, c, 0], [ 0, 0, 1] ])
        #print(R_i)
        R = dotProduct(R_i, R)
        #print(R)
    #print('generic euler_rotation R')
    #print(R)
    return dotProduct(R, p)

Example 18

Project: tracer Source File: test_objects.py
    def test_retransform_object(self):
        """Changing an object's transform yield's correct resaults after retransform"""
        self.obj.set_transform(N.eye(4))
        self.assembly.transform_children()
        
        # Surface transforms:
        N.testing.assert_array_almost_equal(self.surf._transform, N.eye(4))
        N.testing.assert_array_almost_equal(self.surf._temp_frame, 
            self.eighth_circle_trans)
        
        # Object transform:
        N.testing.assert_array_almost_equal(self.obj.get_transform(),
            N.eye(4))
        
        # Subassembly transform:
        N.testing.assert_array_almost_equal(self.sub_assembly.get_transform(),
            self.eighth_circle_trans)

Example 19

Project: pythonGPLVM Source File: GP.py
Function: update
	def update(self):
		"""do the Cholesky decomposition as required to make predictions and calculate the marginal likelihood"""
		self.K = self.kernel(self.X,self.X) 
		self.K += np.eye(self.K.shape[0])/self.beta
		self.L = np.linalg.cholesky(self.K)
		self.A = linalg.cho_solve((self.L,1),self.Y)

Example 20

Project: discomll Source File: linear_svm.py
Function: reduce_fit
def reduce_fit(interface, state, label, inp):
    """
    Function joins all partially calculated matrices ETE and ETDe, aggregates them and it calculates final parameters.
    """
    import numpy as np

    out = interface.output(0)
    sum_etde = 0
    sum_ete = [0 for _ in range(len(state["X_indices"]) + 1)]
    for key, value in inp:
        if key == "etde":
            sum_etde += value
        else:
            sum_ete[key] += value

    sum_ete += np.true_divide(np.eye(len(sum_ete)), state["nu"])
    out.add("params", np.linalg.lstsq(sum_ete, sum_etde)[0])

Example 21

Project: jsonpickle Source File: numpy_test.py
Function: test_strides
    def test_strides(self):
        """test that cases with non-standard strides and offsets work correctly"""
        arr = np.eye(3)
        view = arr[1:, 1:]
        self.assertTrue(view.base is arr)
        data = [arr, view]

        _data = self.roundtrip(data)

        # test that the deserialized arrays indeed view the same memory
        _arr, _view = _data
        _arr[1, 2] = -1
        self.assertEqual(_view[0, 1], -1)
        self.assertTrue(_view.base is _arr)

Example 22

Project: hadoop_vision Source File: compose_test.py
Function: test_map
    def test_map(self):
        self.reset_first()
        e = np.eye(3)
        test_in = [(0, [(0, 0, e), (0, 1, e)]),
                   (1, [(1, 0, e), (1, 1, e), (1, 2, e)]),
                   (2, [(2, 1, e), (2, 2, e), (2, 3, e)]),
                   (3, [(3, 2, e), (3, 3, e)])]
        test_out = [('0\t0', [(0, 0, e), (0, 1, e)]),
                    ('1\t0', [(1, 0, e), (1, 1, e), (1, 2, e)]),
                    ('2\t0', [(2, 1, e), (2, 2, e), (2, 3, e)]),
                    ('3\t0', [(3, 2, e), (3, 3, e)])]
        self.assertEqual(self.call_map(Mapper, test_in), test_out)

Example 23

Project: yatsm Source File: _ewma.py
@try_jit(nopython=True, nogil=True)
def _ewma_smooth(y, start, lambda_=0.2):
    n = y.shape[0]

    S1 = np.eye(n)
    for i in range(n - 1):
        for j in range(i, n):
            S1[j, i] = (1 - lambda_) ** (j - i)
    S2 = (1 - lambda_) ** np.arange(1, n + 1)
    z = lambda_ * np.dot(S1, y) + S2 * start

    return z

Example 24

Project: SALib Source File: morris_util.py
def generate_P_star(g):
    '''
    Matrix P* - size (g-by-g) - describes order in which groups move
    '''
    P_star = np.eye(g, g)
    np.random.shuffle(P_star)
    return P_star

Example 25

Project: CyLP Source File: test_modeling.py
    def test_constraint_1(self):
        model = self.model
        x = self.x
        b = self.b

        model.addConstraint(2 <= -x <= 4.5)

        cons = model.constraints[0]

        m, cl, cu, vl, vu = model.makeMatrices()
        self.assertTrue((abs(m.todense() +
                        np.eye(5, 5)) < 0.000001).all())

Example 26

Project: theano_pyglm Source File: basis.py
def create_identity_basis(prms):
    """
    Create a basis of Gaussian bumps.
    This is primarily for spatial filters.
    """
    # Set default parameters. These can be overriden by kwargs

    # Default to a raised cosine basis
    n_eye = prms['n_eye']   # Number of identity basis functions
    basis = np.eye(n_eye)

    return basis

Example 27

Project: cvxpy Source File: test_domain.py
Function: test_log_det
    def test_log_det(self):
        """Test domain for log_det.
        """
        dom = log_det(self.A + np.eye(2)).domain
        prob = Problem(Minimize(sum_entries(diag(self.A))), dom)
        prob.solve(solver=cvxpy.SCS)
        self.assertAlmostEquals(prob.value, -2, places=3)

Example 28

Project: conceptors Source File: feature_net.py
Function: init
  def __init__(self,
               feature_size):
    """
    init a feature net
    
    @param feature_size: size of input feature
    """
    
    self.feature_size=feature_size;
    
    self.I=np.eye(feature_size);

Example 29

Project: tvb-framework Source File: tract_importer.py
Function: init
    def __init__(self, hdr):
        # this is an affine transform mapping the voxel space in which the tracts live to the surface space
        # see http://www.grahamwideman.com/gw/brain/fs/coords/fscoords.htm
        self.vox_to_ras = hdr['vox_to_ras']

        if self.vox_to_ras[3][3] == 0:
            # according to http://www.trackvis.org/docs/?subsect=fileformat this means that the matrix cannot be trusted
            self.vox_to_ras = numpy.eye(4)

Example 30

Project: pyRiemann Source File: test_utils_distance.py
def test_distance_kullback():
    """Test kullback divergence"""
    A = 2*np.eye(3)
    B = 2*np.eye(3)
    assert_array_almost_equal(distance_kullback(A, B), 0)
    assert_array_almost_equal(distance_kullback_right(A, B), 0)
    assert_array_almost_equal(distance_kullback_sym(A, B), 0)

Example 31

Project: scikit-image Source File: test_pil.py
Function: test_png_round_trip
def test_png_round_trip():
    f = NamedTemporaryFile(suffix='.png')
    fname = f.name
    f.close()
    I = np.eye(3)
    imsave(fname, I)
    Ip = img_as_float(imread(fname))
    os.remove(fname)
    assert np.sum(np.abs(Ip-I)) < 1e-3

Example 32

Project: fos-legacy Source File: cubes.py
Function: create_cubes
    def create_cubes(self, location, edge_size, color=None):
        e2 = edge_size  / 2.0
        verts = list(product(*repeat([-e2, +e2], 3)))
        faces = [
            [0, 1, 3, 2], # left
            [4, 6, 7, 5], # right
            [7, 3, 1, 5], # front
            [0, 2, 6, 4], # back
            [3, 7, 6, 2], # top
            [1, 0, 4, 5], # bottom
        ]
        aff= np.eye(4)
        aff[3,:3] = location
        oc = Polyhedron(verts, faces, affine = aff)
        return oc

        '''

Example 33

Project: mxnet-gan Source File: ops.py
def minibatch_layer(data, batch_size, num_kernels, num_dim=5):
    net = mx.sym.FullyConnected(data,
                                num_hidden=num_kernels*num_dim,
                                no_bias=True)
    net = mx.sym.Reshape(net, shape=(-1, num_kernels, num_dim))
    a = mx.sym.expand_dims(net, axis=3)
    b = mx.sym.expand_dims(
        mx.sym.transpose(net, axes=(1, 2, 0)), axis=0)
    abs_dif = mx.sym.abs(mx.sym.broadcast_minus(a, b))
    # batch, num_kernels, batch
    abs_dif = mx.sym.sum(abs_dif, axis=2)
    mask = np.eye(batch_size)
    mask = np.expand_dims(mask, 1)
    mask = 1.0 - mask
    rscale = 1.0 / np.sum(mask)
    # multiply by mask and rescale
    out = mx.sym.sum(mx.sym.broadcast_mul(abs_dif, constant(mask)), axis=2) * rscale

    return mx.sym.Concat(data, out)

Example 34

Project: misvm Source File: quadprog.py
    def _ensure_pd(self, epsilon):
        """
        Add epsilon times identity matrix
        to P to ensure numerically it is P.D.
        """
        n = self.P.size[0]
        self.P = self.P + cvxmat(epsilon * eye(n))

Example 35

Project: pymanopt Source File: test_manifold_grassmann.py
Function: test_rand
    def test_rand(self):
        # Just make sure that things generated are on the manifold and that
        # if you generate two they are not equal.
        X = self.man.rand()
        np_testing.assert_allclose(multiprod(multitransp(X), X),
                                   np.eye(self.n), atol=1e-10)
        Y = self.man.rand()
        assert la.norm(X - Y) > 1e-6

Example 36

Project: metric-learn Source File: lmnn.py
    def fit(self, X, labels):
      self.X = X
      self.L = np.eye(X.shape[1])
      labels = MulticlassLabels(labels.astype(np.float64))
      self._lmnn = shogun_LMNN(RealFeatures(X.T), labels, self.params['k'])
      self._lmnn.set_maxiter(self.params['max_iter'])
      self._lmnn.set_obj_threshold(self.params['convergence_tol'])
      self._lmnn.set_regularization(self.params['regularization'])
      self._lmnn.set_stepsize(self.params['learn_rate'])
      if self.params['use_pca']:
        self._lmnn.train()
      else:
        self._lmnn.train(self.L)
      self.L = self._lmnn.get_linear_transform()
      return self

Example 37

Project: drmad Source File: exact.py
Function: make_transform
def make_transform(layer_corr):
    diag = np.eye(N_scripts)
    full = np.full((N_scripts, N_scripts), 1.0 / N_scripts)
    transform_parser = VectorParser()
    for i_layer, corr in  enumerate(layer_corr):
        transform_parser[i_layer] = (1 - corr) * diag + corr * full
    return transform_parser

Example 38

Project: robothon Source File: test_regression.py
    def test_matrix_multiply_by_1d_vector(self, level=rlevel) :
        """Ticket #473"""
        def mul() :
            np.mat(np.eye(2))*np.ones(2)

        self.failUnlessRaises(ValueError,mul)

Example 39

Project: scot Source File: connectivity.py
Function: a
    @memoize
    def A(self):
        """Spectral VAR coefficients.

        .. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)}
                  \mathrm{e}^{-2\pi f}
        """
        return fft(np.dstack([np.eye(self.m), -self.b]),
                   self.nfft * 2 - 1)[:, :, :self.nfft]

Example 40

Project: pyNCS Source File: mapping.py
    def __connect_one2one__(self, groupsrc, groupdst, p=1.0):
        """
        Connects in a one to one fashion, from the first of the source to the
        last of the source.  If the sizes are different it just raises a
        warning!
        """

        if len(groupsrc) != len(groupdst):
            print("WARNING: source and destination have different sizes")
            if len(groupdst) > len(groupsrc):
                groupdst = groupdst[:len(groupsrc)]
            else:
                groupsrc = groupsrc[:len(groupdst)]
        connect_dist = np.eye(len(groupsrc))*p
        return self.__connect_by_probability_matrix__(groupsrc, groupdst, connect_dist)

Example 41

Project: Z2Pack Source File: hm_systems.py
@pytest.fixture(params=[False, True])
def simple_system(request):
    res = z2pack.hm.System(lambda k: np.eye(4))
    if request.param:
        res = OverlapMockSystem(res)
    return res

Example 42

Project: pyParticleEst Source File: mlnlg_model.py
Function: init
    def __init__(self, P0_xi, P0_z, Q_xi, Q_z, Q_xiz, R):
        Axi = numpy.eye(1)
        Az = numpy.eye(1)
        self.pn_count = 0
        P0_xi = numpy.copy(P0_xi)
        P0_z = numpy.copy(P0_z)
        z0 = numpy.zeros((1,))
        xi0 = numpy.zeros((1,))
        super(Model, self).__init__(z0=z0, Pz0=P0_z,
                                    Pxi0=P0_xi, xi0=xi0,
                                    Axi=Axi, Az=Az,
                                    Qxi=Q_xi, Qxiz=Q_xiz,
                                    Qz=Q_z, R=R)

Example 43

Project: refinery Source File: GaussObsModel.py
Function: update_obs_params_em
  def update_obs_params_EM( self, SS, **kwargs):
    I = np.eye(self.D)
    for k in xrange(self.K):
      mean    = SS.x[k] / SS.N[k]
      covMat  = SS.xxT[k] / SS.N[k] - np.outer(mean,mean)
      covMat  += self.min_covar * I      
      precMat = np.linalg.solve( covMat, I )
      self.comp[k] = GaussDistr(m=mean, L=precMat)

Example 44

Project: sugartensor Source File: sg_initializer.py
def identity(name, dim, scale=1, dtype=tf.sg_floatx):
    x = tf.get_variable(name,
                        initializer=tf.constant(np.eye(dim) * scale, dtype=dtype))
    # add summary
    if not tf.get_variable_scope().reuse:
        tf.sg_summary_param(x)
    return x

Example 45

Project: Lasagne-CTC Source File: test_ctc.py
def test_log_dot_matrix_zeros():
    x = T.matrix()
    y = T.matrix()
    z = ctc_cost._log_dot_matrix(y, x)
    X = np.log(np.asarray(np.eye(5), dtype=floatX))
    Y = np.asarray(np.random.normal(0, 1, (3, 5)), dtype=floatX)
    #Y = np.ones((3, 5), dtype=floatX) * 3
    value = z.eval({x: X, y: Y})
    np_value = np.log(np.dot(np.exp(Y), np.exp(X)))
    assert np.mean((value - np_value)**2) < 1e5

Example 46

Project: chainer Source File: test_inv.py
Function: set_up
    def setUp(self):
        self.x = (numpy.eye(self.shape[-1]) +
                  numpy.random.uniform(-0.01, 0.01, self.shape)).astype(
            numpy.float32)
        self.gy = numpy.random.uniform(-1, 1, self.shape).astype(numpy.float32)
        self.check_forward_options = {'atol': 1e-3, 'rtol': 1e-4}
        self.check_backward_options = {'atol': 1e-3, 'rtol': 1e-4}

Example 47

Project: pykalman Source File: test_unscented.py
def test_unscented_initialize_parameters():
    check_dims(1, 1, 2, UnscentedKalmanFilter,
        {'transition_functions': [lambda x, y: x, lambda x, y: x]})
    check_dims(3, 5, 2, UnscentedKalmanFilter,
        {'n_dim_state': 3, 'n_dim_obs': 5})
    check_dims(1, 3, 2, UnscentedKalmanFilter,
        {'observation_covariance': np.eye(3)})
    check_dims(2, 1, 2, UnscentedKalmanFilter,
        {'initial_state_mean': np.zeros(2)})

Example 48

Project: pymdptoolbox Source File: test_utils.py
def test_checkSquareStochastic_NonNegativeError():
    P = np.eye(STATES)
    P[0, 0] = -0.5
    P[0, 1] = 1.5
    assert_raises(mdptoolbox.error.NonNegativeError,
                  mdptoolbox.util.checkSquareStochastic, matrix=P)

Example 49

Project: bdol-ml Source File: MLP.py
  def dpp_dropin_uniform(self, dropoutProb):
    if dropoutProb == 0:
      return

    p = (1-dropoutProb)
    L = (p/(1-p))*np.eye(self.W.shape[0]-1)
    D, V = dpp.decompose_kernel(L)
    J = dpp.sample(D, V)
    d_idx = np.zeros((self.W.shape[0]-1, 1))
    d_idx[J.astype(int)] = 1
  
    self.prevZ[:, 0:-1] = self.prevZ[:, 0:-1]*d_idx.T

Example 50

Project: dit Source File: optutil.py
    def build_linear_inequality_constraints(self):
        from cvxopt import matrix

        # Dimension of optimization variable
        n = self.n

        # Nonnegativity constraint
        #
        # We have M = N = 0 (no 2nd order cones or positive semidefinite cones)
        # So, K = l where l is the dimension of the nonnegative orthant. Thus,
        # we have l = n.
        G = matrix(-1 * np.eye(n))   # G should have shape: (K,n) = (n,n)
        h = matrix(np.zeros((n,1)))  # h should have shape: (K,1) = (n,1)

        self.G = G
        self.h = h
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4