Python numpy.identity() Examples

The following are 30 code examples for showing how to use numpy.identity(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: padasip   Author: matousc89   File: ap.py    License: MIT License 6 votes vote down vote up
def __init__(self, n, order=5, mu=0.1, eps=0.001, w="random"):
        self.kind = "AP filter"
        self.n = self.check_int(
            n,'The size of filter must be an integer')
        self.order = self.check_int(
            order, 'The order of projection must be an integer')
        self.mu = self.check_float_param(mu, 0, 1000, "mu")
        self.eps = self.check_float_param(eps, 0, 1000, "eps")
        self.init_weights(w, self.n)
        self.w_history = False
        self.x_mem = np.zeros((self.n, self.order))
        self.d_mem = np.zeros(order)
        self.ide_eps = self.eps * np.identity(self.order)
        self.ide = np.identity(self.order)
        self.y_mem = False
        self.e_mem = False 
Example 2
Project: DOTA_models   Author: ringringyi   File: optimizers.py    License: Apache License 2.0 6 votes vote down vote up
def optimize(self, sess, feed_dict):
    reg_input, reg_weight, old_values, targets = sess.run(
        [self.inputs, self.regression_weight, self.values, self.targets],
        feed_dict=feed_dict)

    intended_values = targets * self.mix_frac + old_values * (1 - self.mix_frac)

    # taken from rllab
    reg_coeff = 1e-5
    for _ in range(5):
      best_fit_weight = np.linalg.lstsq(
          reg_input.T.dot(reg_input) +
          reg_coeff * np.identity(reg_input.shape[1]),
          reg_input.T.dot(intended_values))[0]
      if not np.any(np.isnan(best_fit_weight)):
        break
      reg_coeff *= 10

    if len(best_fit_weight.shape) == 1:
      best_fit_weight = np.expand_dims(best_fit_weight, -1)

    sess.run(self.update_regression_weight,
             feed_dict={self.new_regression_weight: best_fit_weight}) 
Example 3
Project: OpenNRE   Author: thunlp   File: max_pool.py    License: MIT License 6 votes vote down vote up
def __init__(self, kernel_size, segment_num=None):
        """
        Args:
            input_size: dimention of input embedding
            kernel_size: kernel_size for CNN
            padding: padding for CNN
        hidden_size: hidden size
        """
        super().__init__()
        self.segment_num = segment_num
        if self.segment_num != None:
            self.mask_embedding = nn.Embedding(segment_num + 1, segment_num)
            self.mask_embedding.weight.data.copy_(torch.FloatTensor(np.concatenate([np.zeros((1, segment_num)), np.identity(segment_num)], axis=0)))
            self.mask_embedding.weight.requires_grad = False
            self._minus = -100
        self.pool = nn.MaxPool1d(kernel_size) 
Example 4
Project: robosuite   Author: StanfordVL   File: transform_utils.py    License: MIT License 6 votes vote down vote up
def quat2mat(quaternion):
    """
    Converts given quaternion (x, y, z, w) to matrix.

    Args:
        quaternion: vec4 float angles

    Returns:
        3x3 rotation matrix
    """
    q = np.array(quaternion, dtype=np.float32, copy=True)[[3, 0, 1, 2]]
    n = np.dot(q, q)
    if n < EPS:
        return np.identity(3)
    q *= math.sqrt(2.0 / n)
    q = np.outer(q, q)
    return np.array(
        [
            [1.0 - q[2, 2] - q[3, 3], q[1, 2] - q[3, 0], q[1, 3] + q[2, 0]],
            [q[1, 2] + q[3, 0], 1.0 - q[1, 1] - q[3, 3], q[2, 3] - q[1, 0]],
            [q[1, 3] - q[2, 0], q[2, 3] + q[1, 0], 1.0 - q[1, 1] - q[2, 2]],
        ]
    ) 
Example 5
def test_linear_sum_assignment_input_validation():
    assert_raises(ValueError, linear_sum_assignment, [1, 2, 3])

    C = [[1, 2, 3], [4, 5, 6]]
    assert_array_equal(linear_sum_assignment(C), linear_sum_assignment(np.asarray(C)))
    # assert_array_equal(linear_sum_assignment(C),
    #                    linear_sum_assignment(matrix(C)))

    I = np.identity(3)
    assert_array_equal(linear_sum_assignment(I.astype(np.bool)), linear_sum_assignment(I))
    assert_raises(ValueError, linear_sum_assignment, I.astype(str))

    I[0][0] = np.nan
    assert_raises(ValueError, linear_sum_assignment, I)

    I = np.identity(3)
    I[1][1] = np.inf
    assert_raises(ValueError, linear_sum_assignment, I) 
Example 6
Project: pyscf   Author: pyscf   File: pmloc.py    License: Apache License 2.0 6 votes vote down vote up
def lowdin(s):
   e, v = numpy.linalg.eigh(s)
   return numpy.dot(v/numpy.sqrt(e), v.T.conj())

#def scdmU(coeff,ova):
#   aux = numpy.identity(ova.shape[0])
#   #aux = lowdin(ova)
#   no = coeff.shape[1]	
#   ova = reduce(numpy.dot,(coeff.T,ova,aux))
#   # ova = no*nb
#   q,r,piv = scipy.linalg.qr(ova, pivoting=True)
#   # In fact, it is just "Lowdin-orthonormalized PAO".
#   bc = ova[:,piv[:no]]
#   ova = numpy.dot(bc.T,bc)
#   s12inv = lowdin(ova)
#   u = numpy.dot(bc,s12inv)
#   return u

#------------------------------------------------
# Boys/PM-Localization
#------------------------------------------------ 
Example 7
Project: pyscf   Author: pyscf   File: ulocal.py    License: Apache License 2.0 6 votes vote down vote up
def lowdinPop(mol,coeff,ova,enorb,occ):
   print '\nLowdin population for LMOs:'
   nb,nc = coeff.shape
   s12 = sqrtm(ova)
   lcoeff = s12.dot(coeff)
   diff = reduce(numpy.dot,(lcoeff.T,lcoeff)) - numpy.identity(nc)
   print 'diff=',numpy.linalg.norm(diff)
   pthresh = 0.05
   labels = mol.ao_labels(None)
   nelec = 0.0
   for iorb in range(nc):
      vec = lcoeff[:,iorb]**2
      idx = list(numpy.argwhere(vec>pthresh))
      print ' iorb=',iorb,' occ=',occ[iorb],' <i|F|i>=',enorb[iorb]
      for iao in idx:
         print '    iao=',labels[iao],' pop=',vec[iao]
      nelec += occ[iorb]
   print 'nelec=',nelec
   return 0 
Example 8
Project: pyscf   Author: pyscf   File: test_eom_kuccsd_diag.py    License: Apache License 2.0 6 votes vote down vote up
def _test_ip_diag(self,kmf,kshift=0):
        cc = kccsd.KUCCSD(kmf)
        Ecc = cc.kernel()[0]

        eom = kccsd_uhf.EOMIP(cc)
        imds = eom.make_imds()
        t1a,t1b = imds.t1
        nkpts, nocc_a, nvir_a = t1a.shape
        nkpts, nocc_b, nvir_b = t1b.shape
        nocc = nocc_a + nocc_b
        diag = kccsd_uhf.ipccsd_diag(eom,kshift,imds=imds)

        I = np.identity(diag.shape[0],dtype=complex)
        indices = np.arange(diag.shape[0])
        H = np.zeros((I.shape[0],len(indices)),dtype=complex)
        for j,idx in enumerate(indices):
            H[:,j] = kccsd_uhf.ipccsd_matvec(eom,I[:,idx],kshift,imds=imds)

        diag_ref = np.zeros(len(indices),dtype=complex)
        diag_out = np.zeros(len(indices),dtype=complex)
        for j,idx in enumerate(indices):
            diag_ref[j] = H[idx,j]
            diag_out[j] = diag[idx]
        diff = np.linalg.norm(diag_ref - diag_out)
        self.assertTrue(abs(diff) < KGCCSD_TEST_THRESHOLD,"Difference in IP diag: {}".format(diff)) 
Example 9
Project: pyscf   Author: pyscf   File: test_eom_kgccsd_diag.py    License: Apache License 2.0 6 votes vote down vote up
def _test_ip_diag(self,cc):
        eom = kccsd_ghf.EOMIP(cc)
        imds = eom.make_imds()
        nkpts, nocc, nvir = imds.t1.shape
        diag = kccsd_ghf.ipccsd_diag(eom,0,imds=imds)

        I = np.identity(diag.shape[0],dtype=complex)
        indices = np.arange(len(diag))
        H = np.zeros((I.shape[0],len(indices)),dtype=complex)
        for j,idx in enumerate(indices):
            H[:,j] = kccsd_ghf.ipccsd_matvec(eom,I[:,idx],0,imds=imds)

        diag_ref = np.zeros(len(indices),dtype=complex)
        diag_out = np.zeros(len(indices),dtype=complex)
        for j,idx in enumerate(indices):
            diag_ref[j] = H[idx,j]
            diag_out[j] = diag[idx]
        diff = np.linalg.norm(diag_ref - diag_out)
        self.assertTrue(abs(diff) < KGCCSD_TEST_THRESHOLD,"Difference in IP diag: {}".format(diff)) 
Example 10
Project: pyscf   Author: pyscf   File: test_eom_kgccsd_diag.py    License: Apache License 2.0 6 votes vote down vote up
def _test_ea_diag(self,cc):
       eom = kccsd_ghf.EOMEA(cc)
       imds = eom.make_imds()
       nkpts, nocc, nvir = imds.t1.shape
       diag = kccsd_ghf.eaccsd_diag(eom,0,imds=imds)

       I = np.identity(diag.shape[0],dtype=complex)
       indices = np.arange(len(diag))
       H = np.zeros((I.shape[0],len(indices)),dtype=complex)
       for j,idx in enumerate(indices):
           H[:,j] = kccsd_ghf.eaccsd_matvec(eom,I[:,idx],0,imds=imds)

       diag_ref = np.zeros(len(indices),dtype=complex)
       diag_out = np.zeros(len(indices),dtype=complex)
       for j,idx in enumerate(indices):
           diag_ref[j] = H[idx,j]
           diag_out[j] = diag[idx]
       diff = np.linalg.norm(diag_ref - diag_out)
       self.assertTrue(abs(diff) < KGCCSD_TEST_THRESHOLD,"Difference in EA diag: {}".format(diff)) 
Example 11
Project: pyscf   Author: pyscf   File: make_test_cell.py    License: Apache License 2.0 6 votes vote down vote up
def test_cell_n2(L=5, mesh=[9]*3):
    cell = pbcgto.Cell()
    cell.unit = 'B'
    cell.atom.extend([['O', (L/2., L/2., L/2.)],
                      ['H', (L/2.-0.689440, L/2.+0.578509, L/2.)],
                      ['H', (L/2.+0.689440, L/2.-0.578509, L/2.)],
        ])
    cell.a = L * np.identity(3)

    cell.basis = 'sto-3g'
    cell.pseudo = 'gth-pade'
    cell.mesh = mesh

    cell.output = '/dev/null'
    cell.build()
    return cell 
Example 12
Project: pyscf   Author: pyscf   File: shci.py    License: Apache License 2.0 6 votes vote down vote up
def _make_dm123(self, state, norb, nelec, link_index=None, **kwargs):
        r"""Note this function does NOT compute the standard density matrix.
        The density matrices are reordered to match the the fci.rdm.make_dm123
        function (used by NEVPT code).
        The returned "2pdm" is :math:`\langle p^\dagger q r^\dagger s\rangle`;
        The returned "3pdm" is :math:`\langle p^\dagger q r^\dagger s t^\dagger u\rangle`.
        """
        onepdm, twopdm, threepdm = self.make_rdm123(state, norb, nelec, None, **kwargs)
        threepdm = numpy.einsum("mkijln->ijklmn", threepdm).copy()
        threepdm += numpy.einsum("jk,lm,in->ijklmn", numpy.identity(norb), numpy.identity(norb), onepdm)
        threepdm += numpy.einsum("jk,miln->ijklmn", numpy.identity(norb), twopdm)
        threepdm += numpy.einsum("lm,kijn->ijklmn", numpy.identity(norb), twopdm)
        threepdm += numpy.einsum("jm,kinl->ijklmn", numpy.identity(norb), twopdm)

        twopdm = numpy.einsum("iklj->ijkl", twopdm) + numpy.einsum("li,jk->ijkl", onepdm, numpy.identity(norb))

        return onepdm, twopdm, threepdm 
Example 13
Project: pyscf   Author: pyscf   File: dmrgci.py    License: Apache License 2.0 6 votes vote down vote up
def _make_dm123(self, state, norb, nelec, link_index=None, **kwargs):
        r'''Note this function does NOT compute the standard density matrix.
        The density matrices are reordered to match the the fci.rdm.make_dm123
        function (used by NEVPT code).
        The returned "2pdm" is :math:`\langle p^\dagger q r^\dagger s\rangle`;
        The returned "3pdm" is :math:`\langle p^\dagger q r^\dagger s t^\dagger u\rangle`.
        '''
        onepdm, twopdm, threepdm = self.make_rdm123(state, norb, nelec, None, **kwargs)
        threepdm = numpy.einsum('mkijln->ijklmn',threepdm).copy()
        threepdm += numpy.einsum('jk,lm,in->ijklmn',numpy.identity(norb),numpy.identity(norb),onepdm)
        threepdm += numpy.einsum('jk,miln->ijklmn',numpy.identity(norb),twopdm)
        threepdm += numpy.einsum('lm,kijn->ijklmn',numpy.identity(norb),twopdm)
        threepdm += numpy.einsum('jm,kinl->ijklmn',numpy.identity(norb),twopdm)

        twopdm =(numpy.einsum('iklj->ijkl',twopdm)
               + numpy.einsum('li,jk->ijkl',onepdm,numpy.identity(norb)))

        return onepdm, twopdm, threepdm 
Example 14
Project: pyscf   Author: pyscf   File: uadc.py    License: Apache License 2.0 6 votes vote down vote up
def get_init_guess(self, nroots=1, diag=None, ascending = True):
       if diag is None :
           diag = self.ea_adc_diag()
       idx = None
       if ascending:
           idx = np.argsort(diag)
       else:
           idx = np.argsort(diag)[::-1]
       guess = np.zeros((diag.shape[0], nroots))
       min_shape = min(diag.shape[0], nroots)
       guess[:min_shape,:min_shape] = np.identity(min_shape)
       g = np.zeros((diag.shape[0], nroots))
       g[idx] = guess.copy()
       guess = []
       for p in range(g.shape[1]):
           guess.append(g[:,p])
       return guess 
Example 15
Project: pyscf   Author: pyscf   File: uadc.py    License: Apache License 2.0 6 votes vote down vote up
def get_init_guess(self, nroots=1, diag=None, ascending = True):
        if diag is None :
            diag = self.ip_adc_diag()
        idx = None
        if ascending:
            idx = np.argsort(diag)
        else:
            idx = np.argsort(diag)[::-1]
        guess = np.zeros((diag.shape[0], nroots))
        min_shape = min(diag.shape[0], nroots)
        guess[:min_shape,:min_shape] = np.identity(min_shape)
        g = np.zeros((diag.shape[0], nroots))
        g[idx] = guess.copy()
        guess = []
        for p in range(g.shape[1]):
            guess.append(g[:,p])
        return guess 
Example 16
Project: pyscf   Author: pyscf   File: dmrgci.py    License: Apache License 2.0 6 votes vote down vote up
def _make_dm123(self, state, norb, nelec, link_index=None, **kwargs):
        r'''Note this function does NOT compute the standard density matrix.
        The density matrices are reordered to match the the fci.rdm.make_dm123
        function (used by NEVPT code).
        The returned "2pdm" is :math:`\langle p^\dagger q r^\dagger s\rangle`;
        The returned "3pdm" is :math:`\langle p^\dagger q r^\dagger s t^\dagger u\rangle`.
        '''
        onepdm, twopdm, threepdm = self.make_rdm123(state, norb, nelec, None, **kwargs)
        threepdm = numpy.einsum('mkijln->ijklmn',threepdm).copy()
        threepdm += numpy.einsum('jk,lm,in->ijklmn',numpy.identity(norb),numpy.identity(norb),onepdm)
        threepdm += numpy.einsum('jk,miln->ijklmn',numpy.identity(norb),twopdm)
        threepdm += numpy.einsum('lm,kijn->ijklmn',numpy.identity(norb),twopdm)
        threepdm += numpy.einsum('jm,kinl->ijklmn',numpy.identity(norb),twopdm)

        twopdm =(numpy.einsum('iklj->ijkl',twopdm)
               + numpy.einsum('li,jk->ijkl',onepdm,numpy.identity(norb)))

        return onepdm, twopdm, threepdm 
Example 17
Project: razzy-spinner   Author: rafasashi   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def cluster(self, vectors, assign_clusters=False, trace=False):
        assert len(vectors) > 0

        # normalise the vectors
        if self._should_normalise:
            vectors = map(self._normalise, vectors)

        # use SVD to reduce the dimensionality
        if self._svd_dimensions and self._svd_dimensions < len(vectors[0]):
            [u, d, vt] = linalg.svd(numpy.transpose(array(vectors)))
            S = d[:self._svd_dimensions] * \
                numpy.identity(self._svd_dimensions, numpy.Float64)
            T = u[:,:self._svd_dimensions]
            Dt = vt[:self._svd_dimensions,:]
            vectors = numpy.transpose(numpy.matrixmultiply(S, Dt))
            self._Tt = numpy.transpose(T)
            
        # call abstract method to cluster the vectors
        self.cluster_vectorspace(vectors, trace)

        # assign the vectors to clusters
        if assign_clusters:
            print self._Tt, vectors
            return [self.classify(vector) for vector in vectors] 
Example 18
Project: razzy-spinner   Author: rafasashi   File: util.py    License: GNU General Public License v3.0 6 votes vote down vote up
def cluster(self, vectors, assign_clusters=False, trace=False):
        assert len(vectors) > 0

        # normalise the vectors
        if self._should_normalise:
            vectors = list(map(self._normalise, vectors))

        # use SVD to reduce the dimensionality
        if self._svd_dimensions and self._svd_dimensions < len(vectors[0]):
            [u, d, vt] = numpy.linalg.svd(numpy.transpose(numpy.array(vectors)))
            S = d[:self._svd_dimensions] * \
                numpy.identity(self._svd_dimensions, numpy.float64)
            T = u[:,:self._svd_dimensions]
            Dt = vt[:self._svd_dimensions,:]
            vectors = numpy.transpose(numpy.dot(S, Dt))
            self._Tt = numpy.transpose(T)

        # call abstract method to cluster the vectors
        self.cluster_vectorspace(vectors, trace)

        # assign the vectors to clusters
        if assign_clusters:
            return [self.classify(vector) for vector in vectors] 
Example 19
Project: kvae   Author: simonkamronn   File: nn.py    License: MIT License 6 votes vote down vote up
def __call__(self, shape, dtype=None, partition_info=None):
        if dtype is None:
            dtype = self.dtype

        if len(shape) == 1:
            return constant_op.constant(0., dtype=dtype, shape=shape)
        elif len(shape) == 2 and shape[0] == shape[1]:
            return constant_op.constant(np.identity(shape[0], dtype))
        elif len(shape) == 4 and shape[2] == shape[3]:
            array = np.zeros(shape, dtype=float)
            cx, cy = shape[0]/2, shape[1]/2
            for i in range(shape[2]):
                array[cx, cy, i, i] = 1
            return constant_op.constant(array, dtype=dtype)
        else:
            constant_op.constant(0., dtype=dtype, shape=shape) 
Example 20
Project: striatum   Author: ntucllab   File: test_linucb.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_add_action(self):
        policy = self.policy
        context1 = {1: [1, 1], 2: [2, 2], 3: [3, 3]}
        history_id, _ = policy.get_action(context1, 2)
        new_actions = [Action() for i in range(2)]
        policy.add_action(new_actions)
        self.assertEqual(len(new_actions) + len(self.actions),
                         policy._action_storage.count())
        policy.reward(history_id, {3: 1})
        model = policy._model_storage.get_model()
        for action in new_actions:
            self.assertTrue((model['A'][action.id]
                             == np.identity(self.context_dimension)).all())

        context2 = {1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4], 5: [5, 5]}
        history_id2, recommendations = policy.get_action(context2, 4)
        self.assertEqual(len(recommendations), 4)
        policy.reward(history_id2, {new_actions[0].id: 4, new_actions[1].id: 5})
        model = policy._model_storage.get_model()
        for action in new_actions:
            self.assertFalse((model['A'][action.id] == np.identity(2)).all()) 
Example 21
Project: pyGSTi   Author: pyGSTio   File: gaugegroup.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, dim):
        """
        Create a new gauge group with gauge-transform dimension `dim`, which
        should be the same as `mdl.dim` where `mdl` is a :class:`Model` you
        might gauge-transform.
        """
        from . import operation as _op  # b/c operation.py imports gaugegroup
        ltrans = _np.identity(dim, 'd')
        rtrans = _np.identity(dim, 'd')
        baseMx = _np.identity(dim, 'd')
        parameterArray = _np.zeros(dim, 'd')
        parameterToBaseIndicesMap = {i: [(i, i)] for i in range(dim)}
        gate = _op.LinearlyParamDenseOp(baseMx, parameterArray,
                                        parameterToBaseIndicesMap,
                                        ltrans, rtrans, real=True)
        OpGaugeGroup.__init__(self, gate, DiagGaugeGroupElement, "Diagonal") 
Example 22
Project: pyGSTi   Author: pyGSTio   File: gaugegroup.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, dim):
        """
        Create a new gauge group with gauge-transform dimension `dim`, which
        should be the same as `mdl.dim` where `mdl` is a :class:`Model` you
        might gauge-transform.
        """
        from . import operation as _op  # b/c operation.py imports gaugegroup
        ltrans = _np.identity(dim, 'd')
        rtrans = _np.identity(dim, 'd')
        baseMx = _np.identity(dim, 'd')
        parameterArray = _np.zeros(dim - 1, 'd')
        parameterToBaseIndicesMap = {i: [(i + 1, i + 1)] for i in range(dim - 1)}
        gate = _op.LinearlyParamDenseOp(baseMx, parameterArray,
                                        parameterToBaseIndicesMap,
                                        ltrans, rtrans, real=True)
        OpGaugeGroup.__init__(self, gate, TPDiagGaugeGroupElement, "TP Diagonal") 
Example 23
Project: pyGSTi   Author: pyGSTio   File: gaugegroup.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, dim):
        """
        Create a new gauge group with gauge-transform dimension `dim`, which
        should be the same as `mdl.dim` where `mdl` is a :class:`Model` you
        might gauge-transform.
        """
        from . import operation as _op  # b/c operation.py imports gaugegroup
        ltrans = _np.identity(dim, 'd')
        rtrans = _np.identity(dim, 'd')
        baseMx = _np.identity(dim, 'd')
        parameterArray = _np.zeros(1, 'd')
        parameterToBaseIndicesMap = {0: [(i, i) for i in range(1, dim)]}
        gate = _op.LinearlyParamDenseOp(baseMx, parameterArray,
                                        parameterToBaseIndicesMap,
                                        ltrans, rtrans, real=True)
        OpGaugeGroup.__init__(self, gate, TPSpamGaugeGroupElement, "TP Spam") 
Example 24
Project: pyGSTi   Author: pyGSTio   File: povm.py    License: Apache License 2.0 6 votes vote down vote up
def depolarize(self, amount):
        """
        Depolarize this POVM by the given `amount`.

        Parameters
        ----------
        amount : float or tuple
            The amount to depolarize by.  If a tuple, it must have length
            equal to one less than the dimension of the gate. All but the
            first element of each spam vector (often corresponding to the
            identity element) are multiplied by `amount` (if a float) or
            the corresponding `amount[i]` (if a tuple).

        Returns
        -------
        None
        """
        raise ValueError("Cannot depolarize a %s object" % self.__class__.__name__)
        #self.dirty = True 
Example 25
Project: pyGSTi   Author: pyGSTio   File: povm.py    License: Apache License 2.0 6 votes vote down vote up
def _rebuild_complement(self, identity_for_complement=None):
        """ Rebuild complement vector (in case other vectors have changed) """

        if self.complement_label is not None and self.complement_label in self:
            non_comp_effects = [v for k, v in self.items()
                                if k != self.complement_label]

            if identity_for_complement is None:
                identity_for_complement = self[self.complement_label].identity

            complement_effect = _sv.ComplementSPAMVec(
                identity_for_complement, non_comp_effects)
            complement_effect.set_gpindices(slice(0, self.Np), self)  # all parameters

            #Assign new complement effect without calling our __setitem__
            old_ro = self._readonly; self._readonly = False
            POVM.__setitem__(self, self.complement_label, complement_effect)
            self._readonly = old_ro 
Example 26
Project: Att-ChemdNER   Author: lingluodlut   File: initializations.py    License: Apache License 2.0 5 votes vote down vote up
def identity(shape, scale=1, name=None):
    if len(shape) != 2 or shape[0] != shape[1]:
        raise ValueError('Identity matrix initialization can only be used '
                         'for 2D square matrices.')
    else:
        return K.variable(scale * np.identity(shape[0]), name=name) 
Example 27
Project: padasip   Author: matousc89   File: rls.py    License: MIT License 5 votes vote down vote up
def __init__(self, n, mu=0.99, eps=0.1, w="random"):
        self.kind = "RLS filter"
        if type(n) == int:
            self.n = n
        else:
            raise ValueError('The size of filter must be an integer') 
        self.mu = self.check_float_param(mu, 0, 1, "mu")
        self.eps = self.check_float_param(eps, 0, 1, "eps")
        self.init_weights(w, self.n)
        self.R = 1/self.eps * np.identity(n)
        self.w_history = False 
Example 28
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: model.py    License: Apache License 2.0 5 votes vote down vote up
def get_distance(F, x):
    """Helper function for margin-based loss. Return a distance matrix given a matrix."""
    n = x.shape[0]

    square = F.sum(x ** 2.0, axis=1, keepdims=True)
    distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose()))

    # Adding identity to make sqrt work.
    return F.sqrt(distance_square + F.array(np.identity(n))) 
Example 29
Project: OpenFermion-Cirq   Author: quantumlib   File: ffft_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_ffft_inverse(size):

    qubits = LineQubit.range(size)

    ffft_circuit = cirq.Circuit(ffft(qubits),
                                strategy=cirq.InsertStrategy.EARLIEST)
    ffft_circuit.append(cirq.inverse(ffft(qubits)))
    ffft_matrix = ffft_circuit.unitary(
        qubits_that_should_be_present=qubits)

    cirq.testing.assert_allclose_up_to_global_phase(
        ffft_matrix, np.identity(1 << size), atol=1e-8
    ) 
Example 30
Project: OpenNRE   Author: thunlp   File: avg_pool.py    License: MIT License 5 votes vote down vote up
def __init__(self, kernel_size, segment_num=None):
        """
        Args:
            input_size: dimention of input embedding
            kernel_size: kernel_size for CNN
            padding: padding for CNN
        hidden_size: hidden size
        """
        super().__init__()
        self.segment_num = segment_num
        if self.segment_num != None:
            self.mask_embedding = nn.Embedding(segment_num + 1, segment_num)
            self.mask_embedding.weight.data.copy_(torch.FloatTensor(np.concatenate([np.zeros(segment_num), np.identity(segment_num)], axis = 0)))
            self.mask_embedding.weight.requires_grad = False
        self.pool = nn.AvgPool1d(kernel_size)