示例#1
0
 def initial_ipeps(self):
     dim = (self.d, ) + (self.chi, ) * self.nVirtual
     if self.iniWay is 'random':
         tensor = tm.symmetrical_rand_peps_tensor(self.d, self.chi,
                                                  self.nVirtual)
         if self.stateType is 'mixed':
             bond = (self.d0, self.d0) + (self.chi, ) * self.nVirtual
             tensor = tensor.reshape(bond)
             ind = (1, 0) + tuple(range(2, self.nVirtual + 2))
             tensor = (tensor + tensor.transpose(ind)) / 2
             bond = (self.d, ) + (self.chi, ) * self.nVirtual
             tensor = tensor.reshape(bond)
         for n in range(0, self.nTensor):
             self.tensors[n] = tensor.copy()
     elif self.iniWay is 'ones':
         for n in range(0, self.nTensor):
             self.tensors[n] = np.ones(dim)
     elif self.iniWay is 'id':
         if self.stateType is 'mixed':
             if self._is_debug:
                 if abs(self.d0**2 - self.d) > 1e-10:
                     bf.print_error('For mixed state, d should be as d0^2. '
                                    'Check self.d or self.stateType')
             for n in range(0, self.nTensor):
                 self.tensors[n] = np.eye(
                     self.d0).reshape((self.d, ) + (1, ) * self.nVirtual)
         else:
             bf.print_error('Initial way "id" is only for thermal states')
示例#2
0
def decision_mps(para=None):
    if para is None:
        para = pm.parameters_decision_mps()
    a = TNmachineLearning.DecisionTensorNetwork(
        para['dataset'],
        2,
        para['chi'],
        'mps',
        para['classes'],
        para['numbers'],
        if_reducing_samples=para['if_reducing_samples'])
    a.images2vecs_test_samples(para['classes'])
    print(a.vLabel)
    for n in range(0, a.length):
        bf.print_sep()
        print('Calculating the %i-th tensor' % n)
        a.update_tensor_decision_mps_svd(n)
        # a.update_tensor_decision_mps_svd_threshold_algo(n)
        # a.update_tensor_decision_mps_gradient_algo(n)
        a.update_v_ctr_train(n)
        a.calculate_intermediate_accuracy_train(n)
        if a.remaining_samples_train.__len__() == 0:
            print('All samples are classified correctly. Training stopped.')
            break
        print('The current accuracy = %g' % a.intermediate_accuracy_train[n])
        print('Entanglement: ' + str(a.lm[n].reshape(1, -1)))
        if para['if_reducing_samples']:
            print('Number of remaining samples: ' +
                  str(a.remaining_samples_train.__len__()))
示例#3
0
 def show_image(self, n):
     # n can be a number or an image
     if type(n) is int:
         l_side = int(np.sqrt(self.length))
         bf.plot_surf(np.arange(0, l_side), np.arange(0, l_side),
                      self.images[:, n].reshape(l_side, l_side))
     else:
         l_side = n.shape[0]
         bf.plot_surf(np.arange(0, l_side), np.arange(0, l_side), n)
示例#4
0
    def __init__(self,
                 lattice,
                 chi,
                 state_type='pure',
                 spin='half',
                 ini_way='random',
                 operators=None,
                 is_symme_env=True,
                 is_debug=False):
        PepsBasic.__init__(self)
        """
        Order of bonds: (phys, virtual, virtual, ...)
        Lattices: 
        'honeycomb0' lattice: n-th virtual bond, n-th lambda
        0,lm0          1,lm1
          \            /
           -  2,lm2  -
         /            \
        1,lm1          0,lm0
        """
        self.lattice = lattice
        self.stateType = state_type  # pure or mixed
        self.spin = spin
        self.d0 = from_spin2phys_dim(spin)
        self.chi = chi
        self.nTensor = 0
        self.nLm = 0
        self.nVirtual = 0
        self.pos_lm = list()
        self.lm_ten_bond = None
        self.iniWay = ini_way
        self._is_debug = is_debug
        if self.stateType is 'mixed':
            self.d = self.d0**2
        else:
            self.d = self.d0

        self.initial_lattice()
        self.tensors = bf.empty_list(self.nTensor)
        self.lm = bf.empty_list(self.nLm)
        self.initial_ipeps()
        self.initial_lm()

        if operators is None:
            op_half = spin_operators(spin)
            self.operators = [
                op_half['id'], op_half['sx'], op_half['sy'], op_half['sz'],
                op_half['su'], op_half['sd']
            ]
        else:
            self.operators = operators

        # Below is for tree DMRG
        self.is_symme_env = is_symme_env
        self.env = None
        self.model_related = dict()
示例#5
0
 def check_consistency(self):
     if self.dataInfo['NumTotalTrain'] != sum(self.dataInfo['nClassNum']):
         bf.print_error('The total number in the dataset is NOT consistent '
                        'with the sum of the samples of all classes')
     for n in range(0, self.dataInfo['NumClass']):
         start = self.dataInfo['nStart'][n]
         end = start + self.dataInfo['nClassNum'][n]
         tmp = self.labels[start:end]
         if not np.prod(tmp == tmp[0]):
             bf.print_error('In the ' + str(tmp[0]) + '-th labels, not all labels are '
                            + str(tmp[0]))
             print(bf.arg_find_array(tmp != tmp[0]))
示例#6
0
 def rho_one_body_simple(self, which_t):
     if which_t is 'all':
         rho = bf.empty_list(self.nTensor)
         for nt in range(0, self.nTensor):
             rho[nt] = self.rho_one_body_simple_nt_tensor(nt)
     elif type(which_t) is int:
         rho = self.rho_one_body_simple_nt_tensor(which_t)
     else:
         rho = bf.empty_list(len(which_t))
         n = 0
         for nt in which_t:
             rho[n] = self.rho_one_body_simple_nt_tensor(nt)
             n += 1
     return rho
示例#7
0
 def rho_two_body_simple(self, which_lm):
     if which_lm is 'all':
         rho = bf.empty_list(self.nLm)
         for n_lm in range(0, self.nLm):
             rho[n_lm] = self.rho_two_body_nlm_simple(n_lm)
     elif type(which_lm) is int:
         rho = self.rho_two_body_nlm_simple(which_lm)
     else:
         rho = bf.empty_list(len(which_lm))
         n = 0
         for n_lm in which_lm:
             rho[n] = self.rho_two_body_nlm_simple(n_lm)
             n += 1
     return rho
示例#8
0
 def initial_lm(self):
     lm = np.random.rand(self.chi, )
     lm /= np.linalg.norm(lm)
     if self.iniWay is 'random':
         for n in range(0, self.nLm):
             self.lm[n] = lm.copy()
     elif self.iniWay is 'ones':
         for n in range(0, self.nLm):
             self.tensors[n] = np.ones((self.chi, )) / (self.chi**0.5)
     elif self.iniWay is 'id':
         if self.stateType is 'mixed':
             for n in range(0, self.nLm):
                 self.lm[n] = np.ones(1, )
         else:
             bf.print_error('Initial way "id" is only for thermal states')
示例#9
0
def gtnc(para_tot=None):
    print('Preparing parameters')
    if para_tot is None:
        para_tot = pm.parameters_gcmpm()
    n_class = len(para_tot['classes'])
    paras = bf.empty_list(n_class)
    for n in range(0, n_class):
        paras[n] = copy.deepcopy(para_tot)
        paras[n]['class'] = int(para_tot['classes'][n])
        paras[n]['chi'] = para_tot['chi'][n]
        paras[n]['theta'] = para_tot['theta']
        paras[n]['save_exp'] = save_exp_gtn_one_class(paras[n])
    classifiers = bf.empty_list(n_class)
    for n in range(0, n_class):
        print_dict(paras[n])
        data = para_tot['data_path'] + paras[n]['save_exp']
        if para_tot['if_load'] and os.path.isfile(data):
            print('The classifier already exists. Load directly')
            classifiers[n] = load_pr(data, 'a')
        else:
            print('Training the MPS of ' + str(para_tot['classes'][n]))
            classifiers[n] = gtn_one_class(paras[n])[0]
            # if para_tot['if_save']:
            #     save_pr('../data_tnml/gcmpm/', paras[n]['save_exp'],
            #             [classifiers[n]], ['classifier'])
        # classifiers[n].mps.check_orthogonality_by_tensors(tol=1e-12)
    # ==================== Testing accuracy ====================
    print('Calculating the testing accuracy')
    b = TNmachineLearning.MachineLearningFeatureMap(para_tot['d'])
    b.load_data(data_path='..\\..\\..\\MNIST\\',
                file_sample='t10k-images.idx3-ubyte',
                file_label='t10k-labels.idx1-ubyte',
                is_normalize=True)
    b.select_samples(para_tot['classes'])
    if classifiers[0].is_dct:
        b.dct(shift=para_tot['shift'], factor=para_tot['factor'])
    b.images2vecs(para_tot['theta'] * np.pi / 2)
    fid = bf.empty_list(n_class)
    for n in range(0, n_class):
        fid[n] = b.compute_fidelities(classifiers[n].mps.mps)
    max_fid = np.argmin(np.hstack(fid), axis=1)
    predict = np.zeros(max_fid.shape, dtype=int)
    for n in range(0, n_class):
        predict += (max_fid == n) * int(para_tot['classes'][n])
    # plot(predict)
    # plot(b.labels)
    accuracy = np.sum(predict == b.labels, dtype=float) / b.numVecSample
    print(accuracy)
示例#10
0
 def find_pos_of_lm(self):
     self.lm_ten_bond = np.zeros((self.nLm, 2, 2), dtype=int)
     for n_lm in range(0, self.nLm):
         n_found = 0
         for n in range(0, self.nTensor):
             if n_lm in self.pos_lm[n]:
                 self.lm_ten_bond[n_lm, n_found, 0] = n
                 self.lm_ten_bond[n_lm, n_found,
                                  1] = self.pos_lm[n].index(n_lm)
                 n_found += 1
             if n_found == 2:
                 break
         if self._is_debug and n_found < 2:
             bf.print_error(
                 'In "find_pos_of_one_lm", n_found is ony %g. It should 2' %
                 n_found)
示例#11
0
 def initialize_env(self):
     self.env = bf.empty_list(self.nVirtual)
     tmp = np.random.randn(self.chi, self.d0**2, self.chi)
     tmp = (tmp + tmp.transpose([2, 1, 0])) / 2
     tmp /= np.linalg.norm(tmp.reshape(-1, ))
     for n in range(0, self.nVirtual):
         self.env[n] = tmp.copy()
def read_mps(load,):

    load_path = load['path']
    load_exp = load['exp']
    if load['Is_continue']:
        data = bf.load_pr(load_path+load_exp+'_.pr')
    else:
        data = bf.load_pr(load_path+load_exp+'.pr')
    print(load_path+load_exp+'.pr')
    A = data['A']
    n = len(A.mps)
    dims=[1]
    for i in range(n-1):
        dims.append(A.mps[i].shape[2])
    dims.append(1)
    return A.mps, dims
示例#13
0
 def __init__(self, data, parity=0):
     self.parity = parity
     if type(data) is dict:
         self.data = data
         one_data = data['00']
         self.ndim = one_data.ndim
         self.shape = [one_data.shape[n] * 2 for n in range(0, self.ndim)]
     else:
         self.ndim = data.ndim
         self.shape = list(data.shape)
         self.data = dict()
         self.normal_to_z2(data)
     for n in range(0, self.ndim):
         if self.shape[n] % 2 == 1:
             bf.print_error(
                 'DimError: for a Z2 tensor, all bond dimensions should be even'
             )
示例#14
0
    def one_bond_so_transformation(self, nt1, vb1, nt2, vb2):
        # Super-orthogonal transformation on one virtual bond
        # vb does NOT count the physical bond
        if self._is_debug:
            if self.pos_lm[nt1][vb1] != self.pos_lm[nt2][vb2]:
                bf.print_error(
                    'In one_bond_so_transformation, the two virtual bonds must'
                    'correspond to the same lambda')
        m1 = self.bond_env_matrix_simple(nt1, vb1)
        m2 = self.bond_env_matrix_simple(nt2, vb2)

        flag = False
        if self._is_debug:
            _lm = self.lm[self.pos_lm[nt1][vb1]].copy()
            flag = (self.chi == self.tensors[nt1].shape[vb1 + 1])
        u1, u2, self.lm[self.pos_lm[nt1]
                        [vb1]] = tm.transformation_from_env_mats(
                            m1,
                            m2,
                            self.lm[self.pos_lm[nt1][vb1]],
                            self.chi,
                            norm_way=1)[:3]
        if self._is_debug and flag:
            _tmp = u1.dot(np.diag(self.lm[self.pos_lm[nt1][vb1]])).dot(u2.T)
            err = np.linalg.norm(tm.off_diagonal_mat(_tmp).reshape(-1, ))
            if err > 1e-10:
                print(
                    'Warning of the transformations from environment: not diagonal (%g)'
                    % err)
            _tmp = np.diag(_tmp)
            _tmp = _tmp / np.linalg.norm(_tmp)
            err = np.linalg.norm(_tmp - self.lm[self.pos_lm[nt1][vb1]])
            if err > 1e-10:
                print(
                    'Warning of the transformations from environment: not recover lm (%g)'
                    % err)
            print(self.lm[self.pos_lm[nt1][vb1]])
        self.tensors[nt1] = tm.absorb_matrix2tensor(self.tensors[nt1], u1,
                                                    vb1 + 1)
        self.tensors[nt2] = tm.absorb_matrix2tensor(self.tensors[nt2], u2,
                                                    vb2 + 1)
        self.tensors[nt1] /= max(abs(self.tensors[nt1].reshape(-1, 1)))
        self.tensors[nt2] /= max(abs(self.tensors[nt2].reshape(-1, 1)))
        # self.lm[self.pos_lm[nt1][vb1]] = tm.normalize_tensor(self.lm[self.pos_lm[nt1][vb1]])[0]
        return m1, m2
示例#15
0
    def images2vecs(self, classes, numbers, how='random'):
        self.vec_classes = classes
        num_class = classes.__len__()
        ntot = 0
        if numbers is None:
            numbers = ['all'] * num_class
        for n in range(0, num_class):
            if numbers[n] is 'all':
                ntot += self.dataInfo['nClassNum'][n]
            else:
                ntot += min(numbers[n], self.dataInfo['nClassNum'][n])
        self.numVecSample = ntot
        self.LabelNow = np.zeros((ntot,), dtype=int)
        self.tmp = np.zeros((self.length, ntot))

        n_now = 0
        for n in range(0, num_class):
            if numbers[n] is 'all':
                start = self.dataInfo['nStart'][n]
                end = start + self.dataInfo['nClassNum'][n]
                self.tmp[:, n_now:self.dataInfo['nClassNum'][n]] = self.images[:, start:end]
                self.LabelNow[n_now:self.dataInfo['nClassNum'][n]] = self.labels[start:end]
                n_now += self.dataInfo['nClassNum'][n]
            else:
                n_sample = numbers[n]
                start = self.dataInfo['nStart'][classes[n]]
                if n_sample >= self.dataInfo['nClassNum'][classes[n]]:
                    rand_p = range(start, self.dataInfo['nClassNum'][classes[n]] + start)
                elif how is 'random':
                    rand_p = np.random.permutation(self.dataInfo['nClassNum'][classes[n]])[
                             :n_sample] + start
                elif how is 'first':
                    rand_p = range(start, n_sample + start)
                else:
                    rand_p = range(self.dataInfo['nClassNum'][classes[n]] - n_sample + start,
                                   self.dataInfo['nClassNum'][classes[n]] + start)
                for ns in rand_p:
                    self.tmp[:, n_now] = self.images[:, ns]
                    self.LabelNow[n_now] = self.labels[ns]
                    n_now += 1
        self.multiple_images2vecs()
        self.clear_tmp_data()
        if is_debug and n_now != ntot:
            bf.print_error('In images2vecs_train_samples: total number of vectorized '
                           'images NOT consistent')
示例#16
0
 def initial_lattice(self):
     # pos_lm[nt][nb]=x denotes the x-th lm locates at the nb-th bond of the nt-th tensor
     if self.lattice is 'honeycomb0':
         self.nTensor = 2
         self.nLm = 3
         self.nVirtual = 3
         # means for the 0-the tensor, it is the 0, 1, and 2-th lm on the three virtual bonds
         self.pos_lm = [[], []]
         self.pos_lm[0] = [0, 1, 2]
         self.pos_lm[1] = [0, 1, 2]
     elif self.lattice is 'honeycombTreeDMRG':
         # for tree DMRG of honeycomb lattice; the TN is square (one tensor with two spins)
         self.nTensor = 5
         self.nVirtual = 4
         self.d = self.d0**2
     else:
         bf.print_error('Incorrect input of the lattice')
     self.find_pos_of_lm()
示例#17
0
    def __init__(self, dataset='mnist', data_path='..\\..\\..\\MNIST\\',
                 file_sample='train-images.idx3-ubyte', file_label='train-labels.idx1-ubyte',
                 is_normalize=True, par_pool=None):
        # MNIST files for training: 'train-images.idx3-ubyte', 'train-labels.idx1-ubyte'
        # MNIST files for testing:  't10k-images.idx3-ubyte',  't10k-labels.idx1-ubyte'
        self.dataset = dataset
        self.dataInfo = dict()
        self.images = bf.decode_idx3_ubyte(path.join(data_path, file_sample))
        self.labels = bf.decode_idx1_ubyte(path.join(data_path, file_label))
        self.length = self.images.shape[0]
        if is_normalize:
            self.images /= 256
        self.analyse_dataset()

        self.tmp = None
        self.nPool = par_pool
        self.parPool = None
        if is_debug:
            self.check_consistency()
示例#18
0
 def get_model_related_tree_dmrg(self, jx, jy, jz, hx, hz, tau=1e-6):
     if 'h2phys' not in self.model_related:
         self.model_related['h2phys'] = hamiltonian_heisenberg(
             self.spin, jx, jy, jz, hx, hz)
         self.model_related['h2_gate'] = expm(-tau / 2 *
                                              self.model_related['h2phys'])
     if 'tensor_gate' not in self.model_related:
         self.model_related['tensor_gate'] = hamiltonian2gate_tensors(
             self.model_related['h2phys'], tau)
     if 'hbath' not in self.model_related:
         self.model_related['hbath'] = bf.empty_list(self.nVirtual)
示例#19
0
 def load_data(self,
               data_path=None,
               file_sample=None,
               file_label=None,
               is_normalize=None):
     # MNIST files for training: 'train-images.idx3-ubyte', 'train-labels.idx1-ubyte'
     # MNIST files for testing:  't10k-images.idx3-ubyte',  't10k-labels.idx1-ubyte'
     if data_path is None:
         data_path = self.data_path
     if file_label is not None:
         self.data_samples = path.join(data_path, file_sample)
         if self.is_there_labels:
             self.data_labels = path.join(data_path, file_label)
     if not (is_normalize is None):
         self.is_normalize_data = is_normalize
     self.images = bf.decode_idx3_ubyte(self.data_samples)
     if self.is_there_labels:
         self.labels = bf.decode_idx1_ubyte(self.data_labels)
     self.length = self.images.shape[0]
     if self.is_normalize_data:
         self.images /= (254 * (self.images.max() > 2) + 1)
def gcmpm_one_class(para=None):
    if para is None:
        para = pm.parameters_gcmpm_one_class()
    para['save_exp'] = save_exp_gcmpm_one_class(para)
    if para['parallel'] is True:
        par_pool = para['n_nodes']
    else:
        par_pool = None
    if para['if_load'] and os.path.isfile(para['save_exp']):
        a = bf.load_pr(os.path.join(para['data_path'], para['save_exp']), 'a')
    else:
        a = TNmachineLearning.MachineLearningMPS(para['d'], para['chi'], para['dataset'],
                                                 par_pool=par_pool)
    a.images2vecs([para['class']], [100])
    a.initialize_virtual_vecs_train()
    a.update_virtual_vecs_train('all', 'all', 'both')
    a.mps.correct_orthogonal_center(0, normalize=True)
    a.mps.mps[0] /= np.linalg.norm(a.mps.mps[0].reshape(-1, ))
    mps0 = a.mps.mps.copy()
    for t in range(0, para['sweep_time']):
        # from left to right
        if para['if_print_detail']:
            print('At the ' + str(t) + '-th sweep, from left to right')
        for nt in range(0, a.length):
            a.update_tensor_gradient(nt, para['step'])
            if nt != a.length-1:
                a.update_virtual_vecs_train('all', nt, 'left')
        # from left to right
        print('At the ' + str(t) + '-th sweep, from right to left')
        for nt in range(a.length-1, -1, -1):
            a.update_tensor_gradient(nt, para['step'])
            if nt != 0:
                a.update_virtual_vecs_train('all', nt, 'right')
        if t > para['check_time0'] and ((t+1) % para['check_time'] == 0
                                        or t+1 == para['sweep_time']):
            fid = ln_fidelity_per_site(mps0, a.mps.mps)
            if fid < (para['step'] * para['ratio_step_tol']):
                print('After ' + str(t+1) + ' sweeps: fid = %g' % fid)
                para['step'] *= para['step_ratio']
            elif t+1 == para['sweep_time']:
                print('After all ' + str(t+1) + ' sweeps finished, fid = %g. '
                                                'Consider to increase the sweep times.' % fid)
            else:
                print('After ' + str(t+1) + ' sweeps, fid = %g.' % fid)
                mps0 = a.mps.mps.copy()
            if para['step'] < para['step_min']:
                print('Now step = ' + str(para['step']) + ' is sufficiently small. Break the loop')
                break
            else:
                print('Now step = ' + str(para['step']))
    if para['if_save']:
        save_pr(para['data_path'], para['save_exp'], [a, para], ['a', 'para'])
    return a, para
示例#21
0
 def update_by_given_effective_ops(psi, ops, bonds):
     indexes = bf.empty_list(1 + bonds.__len__())
     indexes[0] = list(range(psi.ndim))
     x = 1
     for n in range(psi.ndim):
         if n in bonds:
             indexes[0][n] = x
             indexes[bonds.index(n) + 1] = [-n - 1, x]
             x += 1
         else:
             indexes[0][n] = -n - 1
     return tm.cont([psi] + ops, indexes)
示例#22
0
 def show_image(self, n, title_way='which_class'):
     # n can be a number or an image
     if type(n) is int:
         l_side = int(np.sqrt(self.length))
         bf.show_multiple_images_v1(
             [self.images[:, n].reshape(l_side, l_side)], titles=[n])
     elif type(n) is np.ndarray:
         bf.show_multiple_images_v1([n])
     else:
         l_side = int(np.sqrt(self.length))
         num = n.__len__()
         n_now = 0
         while num > 0.5:
             dn = min(num, 100)
             if title_way is 'which_sample':
                 titles = [x for x in n[n_now:n_now + dn]]
             elif title_way is 'which_class':
                 titles = [int(self.labels[x]) for x in n[n_now:n_now + dn]]
             else:
                 titles = None
             # bf.show_multiple_images_v0(
             #     [self.images[:, x].reshape(l_side, l_side) for x in n[n_now:n_now + dn]],
             #     gap=0)
             bf.show_multiple_images_v1([
                 self.images[:, x].reshape(l_side, l_side)
                 for x in n[n_now:n_now + dn]
             ],
                                        titles=titles)
             n_now += dn
             num -= dn
def gcmpm(para_tot=None):
    print('Preparing parameters')
    if para_tot is None:
        para_tot = pm.parameters_gcmpm()
    n_class = len(para_tot['classes'])
    paras = bf.empty_list(n_class)
    for n in range(0, n_class):
        paras[n] = para_tot.copy()
        paras[n]['class'] = para_tot['classes'][n]
        paras[n]['chi'] = para_tot['chi'][n]
        paras[n]['save_exp'] = save_exp_gcmpm_one_class(paras[n])
    classifiers = bf.empty_list(n_class)
    for n in range(0, n_class):
        data = '../data_tnml/gcmpm/' + paras[n]['save_exp']
        if para_tot['if_load'] and os.path.isfile(data):
            print('The classifier already exists. Load directly')
            classifiers[n] = load_pr(data, 'classifier')
        else:
            print('Training the MPS of ' + str(para_tot['classes'][n]))
            classifiers[n] = gcmpm_one_class(paras[n])[0]
            if para_tot['if_save']:
                save_pr('../data_tnml/gcmpm/', paras[n]['save_exp'],
                        [classifiers[n]], ['classifier'])
    # Testing accuracy
    print('Calculating the testing accuracy')
    labels = para_tot['classes']
    b = TNmachineLearning.MachineLearningFeatureMap('MNIST', para_tot['d'],
                                                    file_sample='t10k-images.idx3-ubyte',
                                                    file_label='t10k-labels.idx1-ubyte')
    b.images2vecs(para_tot['classes'], ['all', 'all'])
    fid = np.zeros((n_class, ))
    num_wrong = 0
    for ni in range(0, b.numVecSample):
        for n in range(0, n_class):
            fid[n] = b.fidelity_mps_image(classifiers[n].mps.mps, ni)
        n_max = int(np.argmax(fid))
        if labels[n_max] != b.LabelNow[ni]:
            num_wrong += 1
    accuracy = num_wrong/b.numVecSample
    print(accuracy)
示例#24
0
 def initialize_virtual_vecs_train(self, way='contract'):
     self.norms = np.ones((self.length, self.numVecSample))
     self.vecsLeft = bf.empty_list(self.length)
     self.vecsRight = bf.empty_list(self.length)
     if way is 'random':
         for n in range(0, self.length):
             self.vecsLeft[n] = np.random.randn(self.mps.virtual_dim[n],
                                                self.numVecSample)
             self.vecsRight[n] = np.random.randn(
                 self.mps.virtual_dim[n + 1], self.numVecSample)
     elif way is 'ones':
         for n in range(0, self.length):
             self.vecsLeft[n] = np.ones(
                 (self.mps.virtual_dim[n], self.numVecSample))
             self.vecsRight[n] = np.ones(
                 (self.mps.virtual_dim[n + 1], self.numVecSample))
     else:
         self.vecsRight[self.length - 1] = np.ones(
             (self.mps.virtual_dim[self.length], self.numVecSample))
         self.update_virtual_vecs_train_all_tensors('right')
         self.vecsLeft[0] = np.ones(
             (self.mps.virtual_dim[0], self.numVecSample))
示例#25
0
 def initial_lattice(self):
     # pos_lm[nt][nb]=x denotes the x-th lm locates at the nb-th bond of the nt-th tensor
     if self.lattice is 'honeycomb0':
         self.nTensor = 2
         self.nLm = 3
         self.nVirtual = 3
         # self.pos_lm[x] means for the x-th tensor, it is the 0, 1, and 2-th lm on the three virtual bonds
         self.pos_lm = [[], []]
         self.pos_lm[0] = [0, 1, 2]
         self.pos_lm[1] = [0, 1, 2]
     elif self.lattice is 'honeycombTreeDMRG':
         # for tree DMRG of honeycomb lattice; the TN is square (one tensor with two spins)
         self.nTensor = 5
         self.nVirtual = 4
         self.d = self.d0**2
     elif self.lattice in ['kagome', 'husimi']:
         self.nTensor = 2  # use symmetrical environment: only one orthogonal tensor
         self.nVirtual = 3
         self.d = self.d0
         self.stateType = 'pure'
     else:
         bf.print_error('Incorrect input of the lattice')
     self.find_pos_of_lm()
示例#26
0
 def rho_two_body_nlm_simple(self, n_lm):
     nt1 = self.lm_ten_bond[n_lm, 0, 0]
     vb1 = self.lm_ten_bond[n_lm, 0, 1]
     nt2 = self.lm_ten_bond[n_lm, 1, 0]
     vb2 = self.lm_ten_bond[n_lm, 1, 1]
     if self._is_debug:
         if n_lm != self.pos_lm[nt2][vb2]:
             bf.print_error(
                 'In rho_two_body_simple, the two virtual bonds must'
                 'correspond to the same lambda')
     bonds = list(range(0, self.nVirtual))
     bonds.remove(vb1)
     tmp1 = self.absorb_lm(nt1, False, bonds)
     tmp2 = self.absorb_lm(nt2, False, 'all')
     if self.stateType is 'pure':
         bonds = list(range(1, self.nVirtual + 1))
         bonds.remove(vb1 + 1)
         tmp1 = np.tensordot(tmp1.conj(), tmp1, (bonds, bonds))
         bonds = list(range(1, self.nVirtual + 1))
         bonds.remove(vb2 + 1)
         tmp2 = np.tensordot(tmp2.conj(), tmp2, (bonds, bonds))
     elif self.stateType is 'mixed':
         s = tmp1.shape
         bonds = list(range(1, self.nVirtual + 2))
         bonds.remove(vb1 + 2)
         tmp1 = tmp1.reshape((self.d0, self.d0) + s[1:])
         tmp1 = np.tensordot(tmp1.conj(), tmp1, (bonds, bonds))
         s = tmp2.shape
         bonds = list(range(1, self.nVirtual + 2))
         bonds.remove(vb2 + 2)
         tmp2 = tmp2.reshape((self.d0, self.d0) + s[1:])
         tmp2 = np.tensordot(tmp2.conj(), tmp2, (bonds, bonds))
     rho = tm.cont([tmp1, tmp2], [[-1, 1, -3, 2], [-2, 1, -4, 2]])
     rho = rho.reshape(self.d0 * self.d0, self.d0 * self.d0)
     rho = (rho + rho.conj().T) / 2
     rho /= np.trace(rho)
     return rho
示例#27
0
 def observe_by_features(self, features, pos):
     if len(pos) == self.length:
         bf.print_error(
             'Input features cannot be as many as the total features')
     features = np.array(features).reshape(-1, 1)
     features = self.map_to_vectors(features).squeeze()
     data_mps = self.mps.wrap_data()
     mps = MPS(self.length, self.d, self.chi)
     mps.refresh_mps_properties(data_mps)
     for n in range(np.array(pos).size):
         mps.mps[pos[n]] = np.tensordot(mps.mps[pos[n]], features[:, n],
                                        [[1], [0]])
     pos = np.sort(pos)
     for n in pos[::-1]:
         if n > 0:
             mps.mps[n - 1] = np.tensordot(mps.mps[n - 1], mps.mps[n],
                                           [[mps.mps[n - 1].ndim - 1], [0]])
         else:
             mps.mps[n + 1] = np.tensordot(mps.mps[n], mps.mps[n + 1],
                                           [[1], [0]])
         mps.mps.__delitem__(n)
     mps.refresh_mps_properties()
     mps.correct_orthogonal_center(0, normalize=True)
     return mps
示例#28
0
 def analyse_dataset(self):
     # Total number of samples
     self.dataInfo['NumTotalTrain'] = self.labels.__len__()
     # Order the samples and labels
     order = np.argsort(self.labels)
     self.images = bf.sort_vecs(self.images, order, which=1)
     self.labels = np.array(sorted(self.labels))
     # Total number of classes
     self.dataInfo['NumClass'] = int(self.labels[-1] + 1)
     # Detailed information
     self.dataInfo['nStart'] = np.zeros((self.dataInfo['NumClass'], ), dtype=int)
     self.dataInfo['nClassNum'] = np.zeros((self.dataInfo['NumClass'],), dtype=int)
     self.dataInfo['nStart'][0] = 0
     for n in range(1, self.dataInfo['NumClass']):
         x = tm.arg_find_array(self.labels[self.dataInfo['nStart'][n-1] + 1:] == n,
                               1, 'first')
         self.dataInfo['nClassNum'][n-1] = x + 1
         self.dataInfo['nStart'][n] = x + self.dataInfo['nStart'][n-1] + 1
     self.dataInfo['nClassNum'][-1] = \
         self.dataInfo['NumTotalTrain'] - self.dataInfo['nStart'][-1]
示例#29
0
    def __init__(self, dataset='mnist'):
        self.dataset = dataset
        self.dataInfo = dict()
        self.is_normalize_data = True
        self.is_there_labels = True  # For generative tasks, no labels are needed
        self.data_samples = ''
        self.data_labels = ''
        self.images = np.zeros(0)
        self.labels = np.zeros(0, dtype=int)
        self.length = -1
        self.img_size = [0, 0]
        self.is_dct = False
        self.dct_info = dict()
        self.is_label_added = False
        self.project_path = bf.project_path()
        self.data_path = None

        self.identify_dataset()

        self.tmp = None
        if is_debug:
            self.check_consistency()
示例#30
0
 def initialize_virtual_vecs_train(self):
     self.vecsLeft = bf.empty_list(self.length, list())
     self.vecsRight = bf.empty_list(self.length, list())
     for n in range(0, self.length):
         self.vecsLeft[n] = np.ones((self.mps.virtual_dim[n], self.numVecSample))
         self.vecsRight[n] = np.ones((self.mps.virtual_dim[n+1], self.numVecSample))