Skip to content
Snippets Groups Projects
ex4_1_5.py 1.03 KiB
Newer Older
  • Learn to ignore specific revisions
  • bjje's avatar
    bjje committed
    # exercise 4.1.5
    
    import numpy as np
    
    Stas Syrota's avatar
    Stas Syrota committed
    from matplotlib.pyplot import (
        cm,
        colorbar,
        figure,
        hist,
        imshow,
        plot,
        show,
        subplot,
        suptitle,
        title,
        xlabel,
        xticks,
        ylabel,
        yticks,
    )
    
    bjje's avatar
    bjje committed
    
    # Number of samples
    N = 1000
    
    # Standard deviation of x1
    s1 = 2
    
    # Standard deviation of x2
    s2 = 3
    
    # Correlation between x1 and x2
    corr = 0.5
    
    # Covariance matrix
    
    Stas Syrota's avatar
    Stas Syrota committed
    S = np.matrix([[s1 * s1, corr * s1 * s2], [corr * s1 * s2, s2 * s2]])
    
    bjje's avatar
    bjje committed
    
    # Mean
    mu = np.array([13, 17])
    
    # Number of bins in histogram
    nbins = 20
    
    # Generate samples from multivariate normal distribution
    X = np.random.multivariate_normal(mu, S, N)
    
    
    # Plot scatter plot of data
    
    Stas Syrota's avatar
    Stas Syrota committed
    figure(figsize=(12, 8))
    suptitle("2-D Normal distribution")
    
    bjje's avatar
    bjje committed
    
    
    Stas Syrota's avatar
    Stas Syrota committed
    subplot(1, 2, 1)
    plot(X[:, 0], X[:, 1], "x")
    xlabel("x1")
    ylabel("x2")
    title("Scatter plot of data")
    
    bjje's avatar
    bjje committed
    
    
    Stas Syrota's avatar
    Stas Syrota committed
    subplot(1, 2, 2)
    x = np.histogram2d(X[:, 0], X[:, 1], nbins)
    imshow(x[0], cmap=cm.gray_r, interpolation="None", origin="lower")
    
    bjje's avatar
    bjje committed
    colorbar()
    
    Stas Syrota's avatar
    Stas Syrota committed
    xlabel("x1")
    ylabel("x2")
    xticks([])
    yticks([])
    title("2D histogram")
    
    bjje's avatar
    bjje committed
    
    show()