Skip to content
Snippets Groups Projects
ex4_1_6.py 1.1 KiB
Newer Older
  • Learn to ignore specific revisions
  • bjje's avatar
    bjje committed
    # exercise 4.1.6
    
    
    Stas Syrota's avatar
    Stas Syrota committed
    import importlib_resources
    import numpy as np
    
    bjje's avatar
    bjje committed
    import scipy.linalg as linalg
    
    Stas Syrota's avatar
    Stas Syrota committed
    from matplotlib.pyplot import cm, figure, imshow, show, subplot, title, xticks, yticks
    
    bjje's avatar
    bjje committed
    from scipy.io import loadmat
    
    
    Stas Syrota's avatar
    Stas Syrota committed
    filename = importlib_resources.files("dtuimldmtools").joinpath("data/zipdata.mat")
    
    bjje's avatar
    bjje committed
    # Digits to include in analysis (to include all: n = range(10))
    n = [0]
    
    # Load Matlab data file to python dict structure
    # and extract variables of interest
    
    Stas Syrota's avatar
    Stas Syrota committed
    traindata = loadmat(filename)["traindata"]
    X = traindata[:, 1:]
    y = traindata[:, 0]
    
    bjje's avatar
    bjje committed
    N, M = X.shape
    C = len(n)
    
    # Remove digits that are not to be inspected
    class_mask = np.zeros(N).astype(bool)
    for v in n:
    
    Stas Syrota's avatar
    Stas Syrota committed
        cmsk = y == v
    
    bjje's avatar
    bjje committed
        class_mask = class_mask | cmsk
    
    Stas Syrota's avatar
    Stas Syrota committed
    X = X[class_mask, :]
    
    bjje's avatar
    bjje committed
    y = y[class_mask]
    N = np.shape(X)[0]
    
    mu = X.mean(axis=0)
    s = X.std(ddof=1, axis=0)
    S = np.cov(X, rowvar=0, ddof=1)
    
    figure()
    
    Stas Syrota's avatar
    Stas Syrota committed
    subplot(1, 2, 1)
    I = np.reshape(mu, (16, 16))
    
    bjje's avatar
    bjje committed
    imshow(I, cmap=cm.gray_r)
    
    Stas Syrota's avatar
    Stas Syrota committed
    title("Mean")
    xticks([])
    yticks([])
    subplot(1, 2, 2)
    I = np.reshape(s, (16, 16))
    
    bjje's avatar
    bjje committed
    imshow(I, cmap=cm.gray_r)
    
    Stas Syrota's avatar
    Stas Syrota committed
    title("Standard deviation")
    xticks([])
    yticks([])
    
    bjje's avatar
    bjje committed
    
    show()
    
    
    Stas Syrota's avatar
    Stas Syrota committed
    print("Ran Exercise 4.1.6")