with pm.Model() as model:
                beta0 = pm.Normal('beta0', mu=0., tau=1e-2)
                tau = pm.Gamma('tau_c', alpha=1.0, beta=1.0)
                mu_phi = CAR2('mu_phi', w=wmat, a=amat, tau=tau, shape=N)
                phi = pm.Deterministic('phi', mu_phi -
                                       tt.mean(mu_phi))  # zero-center phi

                mu = pm.Deterministic('mu', beta0 + phi)
                Yi = pm.LogitNormal('Yi', mu=mu, observed=pad(pixel_values))

                max_a_post = pm.find_MAP()
                step = pm.NUTS()
                trace = pm.sample(draws=N_SAMPLES,
                                  step=step,
                                  start=max_a_post,
                                  cores=2,
                                  tune=N_TUNE,
                                  chains=N_CHAINS)
                posterior_pred = pm.sample_posterior_predictive(trace)

                prefix_file_name = 'mnist_digit{}(label{})_'.format(i, label)

                np.save(
                    new_name(name=prefix_file_name + 'phi_values',
                             suffix='.npy',
                             directory=DIRECTORY), trace.get_values('phi'))

        print('Finished fitting models on digit ' + str(i))
        print('Took {} seconds'.format(np.around(time.time() - start, 0)))
        print('\n')
Ejemplo n.º 2
0
    image = image / np.max(image)
    x_dim, y_dim = image.shape
    pixel_values = np.concatenate(image)  # grey scale between 0 and 1
    print('The image is {} by {}\n'.format(x_dim, y_dim))

    N, wmat, amat = create_matrices(x_dim, y_dim)

    with pm.Model() as model:
        beta0 = pm.Normal('beta0', mu=0., tau=1e-2)
        tau = pm.Gamma('tau_c', alpha=1.0, beta=1.0)
        mu_phi = CAR2('mu_phi', w=wmat, a=amat, tau=tau, shape=N)
        phi = pm.Deterministic('phi',
                               mu_phi - tt.mean(mu_phi))  # zero-center phi

        mu = pm.Deterministic('mu', beta0 + phi)
        Yi = pm.LogitNormal('Yi', mu=mu, observed=pad(pixel_values))

        trace = pm.sample(draws=N_SAMPLES, cores=8, tune=500, chains=N_CHAINS)
        posterior_pred = pm.sample_posterior_predictive(trace)

    if args.file_name is None:
        prefix_file_name = 'mnist_'
    else:
        prefix_file_name = args.file_name

    np.save(
        new_name(name=prefix_file_name + 'phi_values',
                 suffix='.npy',
                 directory='results/'), trace.get_values('phi'))