Ejemplo n.º 1
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)
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)