Example #1
0
def run_experiment(index, dataset_name, name, constraint_getter, master_tree, X, y, out_dir, n_iters=1000, add_constraint=200, add_score=200,
                   add_likelihood=200, should_continue=False):


    N, D = X.shape
    df = Inverse(c=1)

    if dataset_name == 'iris':
        lm = GaussianLikelihoodModel(sigma=np.eye(D) / 9.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile()
    elif dataset_name == 'zoo':
        lm = GaussianLikelihoodModel(sigma=np.diag(np.diag(np.cov(X.T))) / 4.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile()
    else:
        lm = GaussianLikelihoodModel(sigma=np.diag(np.diag(np.cov(X.T))) / 2.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile()
    if should_continue:
        with open(out_dir / name / 'scores-%u.pkl' % index, 'r') as fp:
            scores = pickle.load(fp)
        with open(out_dir / name / 'costs-%u.pkl' % index, 'r') as fp:
            costs = pickle.load(fp)
        with open(out_dir / name / 'final-tree-%u.pkl' % index, 'r') as fp:
            tree = DirichletDiffusionTree(df=df, likelihood_model=lm)
            tree.set_state(pickle.load(fp))
        sampler = MetropolisHastingsSampler(tree, X)
    else:
        scores = []
        costs = []
        tree = DirichletDiffusionTree(df=df, likelihood_model=lm)
        sampler = MetropolisHastingsSampler(tree, X)
        sampler.initialize_assignments()
        if dataset_name == 'zoo':
            sampler.tree = sampler.tree.induced_subtree(master_tree.points())

    current_run = []
    for i in tqdm(xrange(n_iters + 1)):
        sampler.sample()
        current_run.append(sampler.tree)
        if i % add_score == 0:
            scores.append(dist(master_tree, sampler.tree))
        if i % add_likelihood == 0:
            costs.append(sampler.tree.marg_log_likelihood())
        if i != 0 and i % add_constraint == 0:
            if constraint_getter is not None:
                constraint = constraint_getter.get_constraint(current_run)
                if constraint is not None:
                    sampler.add_constraint(constraint)
            current_run = []
    # plot_tree(sampler.tree, y)

    (out_dir / name).mkdir_p()
    with open(out_dir / name / 'scores-%u.pkl' % index, 'w') as fp:
        pickle.dump(scores, fp)
    print len(costs)
    with open(out_dir / name / 'costs-%u.pkl' % index, 'w') as fp:
        pickle.dump(costs, fp)
    # with open(out_dir / name / 'trees-%u.pkl' % index, 'r') as fp:
        # previous_trees = pickle.load(fp)
    # with open(out_dir / name / 'trees-%u.pkl' % index, 'w') as fp:
        # pickle.dump(previous_trees + [t.get_state() for t in trees], fp)
    with open(out_dir / name / 'final-tree-%u.pkl' % index, 'w') as fp:
        pickle.dump(sampler.tree.get_state(), fp)
    return costs, scores, sampler
Example #2
0
lm = GaussianLikelihoodModel(sigma=np.cov(X.T) / 2.0,
                             sigma0=np.eye(D) / 2.0,
                             mu0=X.mean(axis=0)).compile()

model = DirichletDiffusionTree(df=df,
                               likelihood_model=lm,
                               constraints=train_constraints)
sampler = MetropolisHastingsSampler(model, X)
sampler.initialize_assignments()

n_iters = 2000000

scores = []
for i in tqdm(xrange(n_iters)):
    sampler.sample()
    if i % 100 == 0:
        wat = sampler.tree.score_constraints(train_constraints)
        assert wat == len(train_constraints), (wat, len(train_constraints))
        scores.append(
            float(sampler.tree.score_constraints(test_constraints)) /
            len(test_constraints))

fontsize = 18
plt.figure()
plt.xlim([0, n_iters / 100])
plt.ylim([0, 1])
plt.xlabel("Iterations", fontsize=fontsize)
plt.ylabel("Constraint Score", fontsize=fontsize)
plt.plot(scores)
plt.legend(loc='best', fontsize=12)
Example #3
0
from trees.util import plot_tree, plot_tree_2d
from trees.ddt import DirichletDiffusionTree, Inverse, GaussianLikelihoodModel
from trees.mcmc import MetropolisHastingsSampler
from tqdm import tqdm


if __name__ == "__main__":
    D = 2
    N = 100
    X = np.random.multivariate_normal(mean=np.zeros(D), cov=np.eye(D), size=N).astype(np.float32)
    df = Inverse(c=1)
    lm = GaussianLikelihoodModel(sigma=np.eye(D) / 4.0, mu0=np.zeros(D), sigma0=np.eye(D))
    ddt = DirichletDiffusionTree(df=df,
                                 likelihood_model=lm)
    mh = MetropolisHastingsSampler(ddt, X)
    mh.initialize_assignments()

    for _ in tqdm(xrange(1000)):
        mh.sample()

    plt.figure()
    plt.plot(mh.likelihoods)

    plt.figure()
    plot_tree(mh.tree)

    plt.figure()
    plot_tree_2d(mh.tree, X)

    plt.show()
Example #4
0
test_constraints = test_constraints[:10000]

df = Inverse(c=1)

lm = GaussianLikelihoodModel(sigma=np.cov(X.T) / 2.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile()

model = DirichletDiffusionTree(df=df, likelihood_model=lm, constraints=train_constraints)
sampler = MetropolisHastingsSampler(model, X)
sampler.initialize_assignments()

n_iters = 2000000

scores = []
for i in tqdm(xrange(n_iters)):
    sampler.sample()
    if i % 100 == 0:
        wat = sampler.tree.score_constraints(train_constraints)
        assert wat == len(train_constraints), (wat, len(train_constraints))
        scores.append(float(sampler.tree.score_constraints(test_constraints))
                            / len(test_constraints))

fontsize = 18
plt.figure()
plt.xlim([0, n_iters/ 100])
plt.ylim([0, 1])
plt.xlabel("Iterations", fontsize=fontsize)
plt.ylabel("Constraint Score", fontsize=fontsize)
plt.plot(scores)
plt.legend(loc='best', fontsize=12)
plt.savefig("wat.png")
Example #5
0
from trees.ddt import DirichletDiffusionTree, Inverse, GaussianLikelihoodModel
from trees.mcmc import MetropolisHastingsSampler
from tqdm import tqdm

if __name__ == "__main__":
    D = 2
    N = 100
    X = np.random.multivariate_normal(mean=np.zeros(D), cov=np.eye(D),
                                      size=N).astype(np.float32)
    df = Inverse(c=1)
    lm = GaussianLikelihoodModel(sigma=np.eye(D) / 4.0,
                                 mu0=np.zeros(D),
                                 sigma0=np.eye(D))
    ddt = DirichletDiffusionTree(df=df, likelihood_model=lm)
    mh = MetropolisHastingsSampler(ddt, X)
    mh.initialize_assignments()

    for _ in tqdm(range(1000)):
        mh.sample()

    plt.figure()
    plt.plot(mh.likelihoods)

    #plt.figure()
    #plot_tree(mh.tree)

    #plt.figure()
    #plot_tree_2d(mh.tree, X)

    plt.show()
Example #6
0
def run_experiment(index,
                   dataset_name,
                   name,
                   constraint_getter,
                   master_tree,
                   X,
                   y,
                   out_dir,
                   n_iters=1000,
                   add_constraint=200,
                   add_score=200,
                   add_likelihood=200,
                   should_continue=False):

    N, D = X.shape
    df = Inverse(c=1)

    if dataset_name == 'iris':
        lm = GaussianLikelihoodModel(sigma=np.eye(D) / 9.0,
                                     sigma0=np.eye(D) / 2.0,
                                     mu0=X.mean(axis=0)).compile()
    elif dataset_name == 'zoo':
        lm = GaussianLikelihoodModel(sigma=np.diag(np.diag(np.cov(X.T))) / 4.0,
                                     sigma0=np.eye(D) / 2.0,
                                     mu0=X.mean(axis=0)).compile()
    else:
        lm = GaussianLikelihoodModel(sigma=np.diag(np.diag(np.cov(X.T))) / 2.0,
                                     sigma0=np.eye(D) / 2.0,
                                     mu0=X.mean(axis=0)).compile()
    if should_continue:
        with open(out_dir / name / 'scores-%u.pkl' % index, 'r') as fp:
            scores = pickle.load(fp)
        with open(out_dir / name / 'costs-%u.pkl' % index, 'r') as fp:
            costs = pickle.load(fp)
        with open(out_dir / name / 'final-tree-%u.pkl' % index, 'r') as fp:
            tree = DirichletDiffusionTree(df=df, likelihood_model=lm)
            tree.set_state(pickle.load(fp))
        sampler = MetropolisHastingsSampler(tree, X)
    else:
        scores = []
        costs = []
        tree = DirichletDiffusionTree(df=df, likelihood_model=lm)
        sampler = MetropolisHastingsSampler(tree, X)
        sampler.initialize_assignments()
        if dataset_name == 'zoo':
            sampler.tree = sampler.tree.induced_subtree(master_tree.points())

    current_run = []
    for i in tqdm(xrange(n_iters + 1)):
        sampler.sample()
        current_run.append(sampler.tree)
        if i % add_score == 0:
            scores.append(dist(master_tree, sampler.tree))
        if i % add_likelihood == 0:
            costs.append(sampler.tree.marg_log_likelihood())
        if i != 0 and i % add_constraint == 0:
            if constraint_getter is not None:
                constraint = constraint_getter.get_constraint(current_run)
                if constraint is not None:
                    sampler.add_constraint(constraint)
            current_run = []
    # plot_tree(sampler.tree, y)

    (out_dir / name).mkdir_p()
    with open(out_dir / name / 'scores-%u.pkl' % index, 'w') as fp:
        pickle.dump(scores, fp)
    print len(costs)
    with open(out_dir / name / 'costs-%u.pkl' % index, 'w') as fp:
        pickle.dump(costs, fp)
    # with open(out_dir / name / 'trees-%u.pkl' % index, 'r') as fp:
    # previous_trees = pickle.load(fp)
    # with open(out_dir / name / 'trees-%u.pkl' % index, 'w') as fp:
    # pickle.dump(previous_trees + [t.get_state() for t in trees], fp)
    with open(out_dir / name / 'final-tree-%u.pkl' % index, 'w') as fp:
        pickle.dump(sampler.tree.get_state(), fp)
    return costs, scores, sampler