Skip to content
Snippets Groups Projects
ex11_2_2.py 927 B
Newer Older
  • Learn to ignore specific revisions
  • bjje's avatar
    bjje committed
    # exercise 11.2.2
    import numpy as np
    
    Stas Syrota's avatar
    Stas Syrota committed
    from matplotlib.pyplot import figure, hist, plot, show, subplot, title
    
    from scipy.stats import gaussian_kde
    
    bjje's avatar
    bjje committed
    
    # Draw samples from mixture of gaussians (as in exercise 11.1.1)
    
    Stas Syrota's avatar
    Stas Syrota committed
    N = 1000
    M = 1
    
    bjje's avatar
    bjje committed
    x = np.linspace(-10, 10, 50)
    
    Stas Syrota's avatar
    Stas Syrota committed
    X = np.empty((N, M))
    m = np.array([1, 3, 6])
    s = np.array([1, 0.5, 2])
    c_sizes = np.random.multinomial(N, [1.0 / 3, 1.0 / 3, 1.0 / 3])
    
    bjje's avatar
    bjje committed
    for c_id, c_size in enumerate(c_sizes):
    
    Stas Syrota's avatar
    Stas Syrota committed
        X[
            c_sizes.cumsum()[c_id] - c_sizes[c_id] : c_sizes.cumsum()[c_id], :
        ] = np.random.normal(m[c_id], np.sqrt(s[c_id]), (c_size, M))
    
    bjje's avatar
    bjje committed
    
    
    # x-values to evaluate the KDE
    xe = np.linspace(-10, 10, 100)
    
    # Compute kernel density estimate
    kde = gaussian_kde(X.ravel())
    
    # Plot kernel density estimate
    
    Stas Syrota's avatar
    Stas Syrota committed
    figure(figsize=(6, 7))
    subplot(2, 1, 1)
    hist(X, x)
    title("Data histogram")
    subplot(2, 1, 2)
    
    bjje's avatar
    bjje committed
    plot(xe, kde.evaluate(xe))
    
    Stas Syrota's avatar
    Stas Syrota committed
    title("Kernel density estimate")
    
    bjje's avatar
    bjje committed
    show()
    
    
    Stas Syrota's avatar
    Stas Syrota committed
    print("Ran Exercise 11.2.2")