Example #1
0
def test_sample_confidence_region():
    """Test sampling from confidence region."""
    random_state = check_random_state(0)

    means = np.array([[0.0, 1.0], [2.0, -1.0]])
    covariances = np.array([[[0.5, 0.0], [0.0, 5.0]], [[5.0, 0.0], [0.0,
                                                                    0.5]]])

    gmm = GMM(n_components=2,
              priors=np.array([0.5, 0.5]),
              means=means,
              covariances=covariances,
              random_state=random_state)
    samples = gmm.sample_confidence_region(100, 0.7)
    for sample in samples:
        assert_true(gmm.is_in_confidence_region(sample, 0.7))
n_samples = 1000

plt.figure(figsize=(20, 5))

ax = plt.subplot(141)
ax.set_title("Unconstrained Sampling")
samples = gmm.sample(n_samples)
ax.scatter(samples[:, 0], samples[:, 1], alpha=0.9, s=1, label="Samples")
plot_error_ellipses(ax, gmm, factors=(1.0, 2.0), colors=["orange", "orange"])
ax.set_xlim((-10, 10))
ax.set_ylim((-10, 10))

ax = plt.subplot(142)
ax.set_title(r"95.45 % Confidence Region ($2\sigma$)")
samples = gmm.sample_confidence_region(n_samples, 0.9545)
ax.scatter(samples[:, 0], samples[:, 1], alpha=0.9, s=1, label="Samples")
plot_error_ellipses(ax, gmm, factors=(1.0, 2.0), colors=["orange", "orange"])
ax.set_xlim((-10, 10))
ax.set_ylim((-10, 10))

ax = plt.subplot(143)
ax.set_title(r"68.27 % Confidence Region ($\sigma$)")
samples = gmm.sample_confidence_region(n_samples, 0.6827)
ax.scatter(samples[:, 0], samples[:, 1], alpha=0.9, s=1, label="Samples")
plot_error_ellipses(ax, gmm, factors=(1.0, 2.0), colors=["orange", "orange"])
ax.set_xlim((-10, 10))
ax.set_ylim((-10, 10))
ax.legend()

ax = plt.subplot(144)