Files
PSI/LAB5.ipynb

37 KiB

Laboratorium 5

In [2]:
import numpy as np
import struct
import scipy as sc
from numpy.lib.stride_tricks import sliding_window_view

Zadanie 1

In [3]:
input_image = np.array([
    [1, 1, 1, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 0],
    [0, 1, 1, 0, 0]
])

filter = np.array([
    [1, 0, 1],
    [0, 1, 0],
    [1, 0, 1]
])

output_image = np.array([
    [4, 3, 4],
    [2, 4, 3],
    [2, 3, 4]
])
In [4]:
def convulsion(image, filtr, step, padding):
    if padding != 0:
        image = np.pad(image, padding)
    h_img, w_img = image.shape
    h_filter, w_filter = filtr.shape
    h_out = (h_img - h_filter) // step + 1
    w_out = (w_img - w_filter) // step + 1

    output = np.zeros((h_out, w_out))

    for i in range(h_out):
        for j in range(w_out):
            h_idx = i * step
            w_idx = j * step

            window = image[h_idx:h_idx + h_filter, w_idx:w_idx + w_filter]
            output[i, j] = np.sum(window * filtr)
    return output


def convulsion(image, filtr, step=1, padding=0):
    if padding != 0:
        image = np.pad(image, padding)
    h_filter, w_filter = filtr.shape

    windows = sliding_window_view(image, (h_filter, w_filter))[::step, ::step]

    return np.sum(windows * filtr, axis=(2, 3))
In [32]:
convulsion(input_image, filter, 1, 0)
Out [32]:
array([[4, 3, 4],
       [2, 4, 3],
       [2, 3, 4]])

Zadanie 2

In [6]:
def ReLu(x):
    return np.maximum(x, 0)


def ReLu_deriv(x):
    return np.where(x > 0, 1, 0)


def softmax(x):
    return sc.special.softmax(x)


def softmax_deriv(x):
    return np.ones_like(x)


def load_mnist_images(filename):
    with open(filename, 'rb') as f:
        magic, num_images, rows, cols = struct.unpack('>IIII', f.read(16))
        image_data = np.frombuffer(f.read(), dtype=np.uint8)
        images = image_data.reshape(num_images, rows * cols).astype(np.float32) / 255.0
    return images


def load_mnist_labels(filename):
    with open(filename, 'rb') as f:
        magic, num_labels = struct.unpack('>II', f.read(8))
        labels = np.frombuffer(f.read(), dtype=np.uint8)
    return labels


def to_one_hot(label, num_classes=10):
    one_hot = np.zeros((num_classes, 1))
    one_hot[label] = 1.0
    return one_hot

1000 obrazow, a= 0.01, 50 iteracji

In [34]:
# 1 Warstwa konwulcyjna, z 16 filtrami 3x3  10 neuronow w wartswie wyjsciowej, ReLu

kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]

train_image = load_mnist_images('train-images.idx3-ubyte')
train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')

# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy

output = np.zeros((16, 676))
W = np.random.uniform(-0.1, 0.1, (10816, 10))

bok = int(np.sqrt(train_image[0].size))
alpha = 0.01
nsamples = 1000
epochs = 50

one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]

for b in range(epochs):
    correct = 0
    for j in range(nsamples):
        x = train_image[j].reshape(bok, bok)
        y = one_hot_label[j]
        for i in range(16):
            new_row = convulsion(x, kernel[i], 1, 0)
            new_row_flat = new_row.flatten()
            output[i, :] = new_row_flat

        output = ReLu(output)
        output_flat = output.flatten()

        # teraz trzeba pomnozyc wektor przez dense layer.
        raw = np.dot(output_flat, W)

        if np.argmax(raw) == train_image_labels[j]:
            correct += 1

        # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.
        delta = (2 * 1 / 10) * (raw - y)
        weight_delta = np.outer(output_flat, delta)

        conv_raw = np.dot(delta, W.T).reshape((16, 26, 26))
        delta_relu = conv_raw * ReLu_deriv(output.reshape((16, 26, 26)))
        W = W - alpha * weight_delta

        for i in range(16):
            kernel_delta = convulsion(x, delta_relu[i], 1, 0)
            kernel[i] = kernel[i] - alpha * kernel_delta

    if (b + 1) % 10 == 0 or b == 0:
        print(f"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%")
Epoka 1/50 - Skutecznosc treningowa: 27.50%
Epoka 10/50 - Skutecznosc treningowa: 86.30%
Epoka 20/50 - Skutecznosc treningowa: 90.30%
Epoka 30/50 - Skutecznosc treningowa: 92.80%
Epoka 40/50 - Skutecznosc treningowa: 95.10%
Epoka 50/50 - Skutecznosc treningowa: 97.10%
In [35]:
test_image = load_mnist_images('t10k-images.idx3-ubyte')
test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')

pred = 0
test_output = np.zeros((16, 676))

for i in range(nsamples):
    x = test_image[i].reshape(bok, bok)

    for k in range(16):
        new_row = convulsion(x, kernel[k], 1, 0)
        test_output[k, :] = new_row.flatten()

    test_output_relu = ReLu(test_output)
    raw = np.dot(test_output_relu.flatten(), W)

    przewidziana_cyfra = np.argmax(raw)
    prawdziwa_cyfra = test_image_labels[i]

    if przewidziana_cyfra == prawdziwa_cyfra:
        pred += 1

proc = (pred / nsamples) * 100
print(f"Skutecznosc: {proc:.2f}%")
Skutecznosc: 84.50%

10000 obrazow, a= 0.01, 50 iteracji

In [36]:
# 1 Warstwa konwulcyjna, z 16 filtrami 3x3  10 neuronow w wartswie wyjsciowej, ReLu

kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]

train_image = load_mnist_images('train-images.idx3-ubyte')
train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')

# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy

output = np.zeros((16, 676))
W = np.random.uniform(-0.1, 0.1, (10816, 10))

bok = int(np.sqrt(train_image[0].size))
alpha = 0.01
nsamples = 10000
epochs = 50

one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]

for b in range(epochs):
    correct = 0
    for j in range(nsamples):
        x = train_image[j].reshape(bok, bok)
        y = one_hot_label[j]
        for i in range(16):
            new_row = convulsion(x, kernel[i], 1, 0)
            new_row_flat = new_row.flatten()
            output[i, :] = new_row_flat

        output = ReLu(output)
        output_flat = output.flatten()

        # teraz trzeba pomnozyc wektor przez dense layer.
        raw = np.dot(output_flat, W)

        if np.argmax(raw) == train_image_labels[j]:
            correct += 1

        # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.
        delta = (2 * 1 / 10) * (raw - y)
        weight_delta = np.outer(output_flat, delta)

        conv_raw = np.dot(delta, W.T).reshape((16, 26, 26))
        delta_relu = conv_raw * ReLu_deriv(output.reshape((16, 26, 26)))
        W = W - alpha * weight_delta

        for i in range(16):
            kernel_delta = convulsion(x, delta_relu[i], 1, 0)
            kernel[i] = kernel[i] - alpha * kernel_delta

    if (b + 1) % 10 == 0 or b == 0:
        print(f"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%")
Epoka 1/50 - Skutecznosc treningowa: 73.07%
Epoka 10/50 - Skutecznosc treningowa: 94.44%
Epoka 20/50 - Skutecznosc treningowa: 95.94%
Epoka 30/50 - Skutecznosc treningowa: 96.56%
Epoka 40/50 - Skutecznosc treningowa: 96.89%
Epoka 50/50 - Skutecznosc treningowa: 97.25%
In [37]:
test_image = load_mnist_images('t10k-images.idx3-ubyte')
test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')

pred = 0
test_output = np.zeros((16, 676))

for i in range(nsamples):
    x = test_image[i].reshape(bok, bok)

    for k in range(16):
        new_row = convulsion(x, kernel[k], 1, 0)
        test_output[k, :] = new_row.flatten()

    test_output_relu = ReLu(test_output)
    raw = np.dot(test_output_relu.flatten(), W)

    przewidziana_cyfra = np.argmax(raw)
    prawdziwa_cyfra = test_image_labels[i]

    if przewidziana_cyfra == prawdziwa_cyfra:
        pred += 1

proc = (pred / nsamples) * 100
print(f"Skutecznosc: {proc:.2f}%")
Skutecznosc: 95.85%

60000 obrazow, a= 0.01, 50 iteracji

In [ ]:
# 1 Warstwa konwulcyjna, z 16 filtrami 3x3  10 neuronow w wartswie wyjsciowej, ReLu

kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]

train_image = load_mnist_images('train-images.idx3-ubyte')
train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')

# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy

output = np.zeros((16, 676))
W = np.random.uniform(-0.1, 0.1, (10816, 10))

bok = int(np.sqrt(train_image[0].size))
alpha = 0.01
nsamples = 60000
epochs = 50

one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]

for b in range(epochs):
    correct = 0
    for j in range(nsamples):
        x = train_image[j].reshape(bok, bok)
        y = one_hot_label[j]
        for i in range(16):
            new_row = convulsion(x, kernel[i], 1, 0)
            new_row_flat = new_row.flatten()
            output[i, :] = new_row_flat

        output = ReLu(output)
        output_flat = output.flatten()

        # teraz trzeba pomnozyc wektor przez dense layer.
        raw = np.dot(output_flat, W)

        if np.argmax(raw) == train_image_labels[j]:
            correct += 1

        # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.
        delta = (2 * 1 / 10) * (raw - y)
        weight_delta = np.outer(output_flat, delta)

        conv_raw = np.dot(delta, W.T).reshape((16, 26, 26))
        delta_relu = conv_raw * ReLu_deriv(output.reshape((16, 26, 26)))
        W = W - alpha * weight_delta

        for i in range(16):
            kernel_delta = convulsion(x, delta_relu[i], 1, 0)
            kernel[i] = kernel[i] - alpha * kernel_delta

    if (b + 1) % 10 == 0 or b == 0:
        print(f"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%")
Epoka 1/50 - Skutecznosc treningowa: 86.16%
Epoka 10/50 - Skutecznosc treningowa: 96.37%
Epoka 20/50 - Skutecznosc treningowa: 96.97%
Epoka 30/50 - Skutecznosc treningowa: 97.26%
In [7]:
test_image = load_mnist_images('t10k-images.idx3-ubyte')
test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')

pred = 0
test_output = np.zeros((16, 676))

for i in range(nsamples):
    x = test_image[i].reshape(bok, bok)

    for k in range(16):
        new_row = convulsion(x, kernel[k], 1, 0)
        test_output[k, :] = new_row.flatten()

    test_output_relu = ReLu(test_output)
    raw = np.dot(test_output_relu.flatten(), W)

    przewidziana_cyfra = np.argmax(raw)
    prawdziwa_cyfra = test_image_labels[i]

    if przewidziana_cyfra == prawdziwa_cyfra:
        pred += 1

proc = (pred / nsamples) * 100
print(f"Skutecznosc: {proc:.2f}%")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 7
      3 
      4 pred = 0
      5 test_output = np.zeros((16, 676))
      6 
----> 7 for i in range(nsamples):
      8     x = test_image[i].reshape(bok, bok)
      9 
     10     for k in range(16):

NameError: name 'nsamples' is not defined

Zadanie 3

1000 obrazow, a= 0.001, 300 iteracji

In [8]:
def max_pooling(image, step=2):
    windows = sliding_window_view(image, (2, 2), axis=(-2, -1))[:, ::step, ::step]  # 16 x 26 x 26 x 2 x 2 // step
    mask = (windows == np.max(windows, axis=(-2, -1),
                              keepdims=True))  # Maska jest o wymirach 16 x 13 x 13 x 2 x 2 a musi byc 16 x 26 x 26
    mask = (mask.transpose(0, 1, 3, 2, 4)).reshape(16, 26, 26)
    return np.max(windows, axis=(-2, -1)), mask
In [71]:
# 1 Warstwa konwulcyjna, z 16 filtrami 3x3  10 neuronow w wartswie wyjsciowej, ReLu

kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]

train_image = load_mnist_images('train-images.idx3-ubyte')
train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')

# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy

output = np.zeros((16, 676))
W = np.random.uniform(-0.1, 0.1, (2704, 10))

bok = int(np.sqrt(train_image[0].size))
alpha = 0.001
nsamples = 1000
epochs = 300

one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]

for b in range(epochs):
    correct = 0
    for j in range(nsamples):
        x = train_image[j].reshape(bok, bok)
        y = one_hot_label[j]
        for i in range(16):
            new_row = convulsion(x, kernel[i], 1, 0)
            new_row_flat = new_row.flatten()
            output[i, :] = new_row_flat

        output = ReLu(output)
        output_2d = output.reshape(16, 26, 26)

        # Teraz trzeba zrobic pool, a w wstecznej wziasc pod uwage maske
        pool, mask = max_pooling(output_2d)

        pool_flat = pool.flatten()

        # teraz trzeba pomnozyc wektor przez dense layer.
        raw = np.dot(pool_flat, W)

        if np.argmax(raw) == train_image_labels[j]:
            correct += 1

        # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.
        delta = (2 * 1 / 10) * (raw - y)
        weight_delta = np.outer(pool_flat, delta)

        conv_raw = np.dot(delta, W.T).reshape((16, 13, 13))

        # Max pool backprop
        back_pool = np.repeat(np.repeat(conv_raw, 2, axis=1), 2, axis=2)

        delta_relu = back_pool * mask * ReLu_deriv(output.reshape((16, 26, 26)))
        W = W - alpha * weight_delta

        for i in range(16):
            kernel_delta = convulsion(x, delta_relu[i], 1, 0)
            kernel[i] = kernel[i] - alpha * kernel_delta

    if (b + 1) % 10 == 0 or b == 0:
        print(f"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%")
Epoka 1/300 - Skutecznosc treningowa: 13.20%
Epoka 10/300 - Skutecznosc treningowa: 54.50%
Epoka 20/300 - Skutecznosc treningowa: 73.80%
Epoka 30/300 - Skutecznosc treningowa: 80.00%
Epoka 40/300 - Skutecznosc treningowa: 82.60%
Epoka 50/300 - Skutecznosc treningowa: 85.10%
Epoka 60/300 - Skutecznosc treningowa: 86.70%
Epoka 70/300 - Skutecznosc treningowa: 87.50%
Epoka 80/300 - Skutecznosc treningowa: 88.00%
Epoka 90/300 - Skutecznosc treningowa: 88.70%
Epoka 100/300 - Skutecznosc treningowa: 89.00%
Epoka 110/300 - Skutecznosc treningowa: 89.20%
Epoka 120/300 - Skutecznosc treningowa: 89.90%
Epoka 130/300 - Skutecznosc treningowa: 90.70%
Epoka 140/300 - Skutecznosc treningowa: 91.30%
Epoka 150/300 - Skutecznosc treningowa: 91.80%
Epoka 160/300 - Skutecznosc treningowa: 91.80%
Epoka 170/300 - Skutecznosc treningowa: 92.10%
Epoka 180/300 - Skutecznosc treningowa: 92.40%
Epoka 190/300 - Skutecznosc treningowa: 92.90%
Epoka 200/300 - Skutecznosc treningowa: 93.00%
Epoka 210/300 - Skutecznosc treningowa: 93.30%
Epoka 220/300 - Skutecznosc treningowa: 93.50%
Epoka 230/300 - Skutecznosc treningowa: 93.50%
Epoka 240/300 - Skutecznosc treningowa: 93.60%
Epoka 250/300 - Skutecznosc treningowa: 93.90%
Epoka 260/300 - Skutecznosc treningowa: 94.20%
Epoka 270/300 - Skutecznosc treningowa: 94.40%
Epoka 280/300 - Skutecznosc treningowa: 94.60%
Epoka 290/300 - Skutecznosc treningowa: 94.60%
Epoka 300/300 - Skutecznosc treningowa: 94.80%
In [74]:
test_image = load_mnist_images('t10k-images.idx3-ubyte')
test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')

pred = 0
test_output = np.zeros((16, 676))

for i in range(10000):
    x = test_image[i].reshape(bok, bok)

    for k in range(16):
        new_row = convulsion(x, kernel[k], 1, 0)
        test_output[k, :] = new_row.flatten()

    test_output_relu = ReLu(test_output)

    output_2d = test_output_relu.reshape(16, 26, 26)

    pool, mask = max_pooling(output_2d)

    pool_flat = pool.flatten()

    raw = np.dot(pool_flat, W)

    przewidziana_cyfra = np.argmax(raw)
    prawdziwa_cyfra = test_image_labels[i]

    if przewidziana_cyfra == prawdziwa_cyfra:
        pred += 1

proc = (pred / 10000) * 100
print(f"Skutecznosc: {proc:.2f}%")
Skutecznosc: 89.64%

10000 obrazow, a= 0.001, 300 iteracji

In [11]:
# 1 Warstwa konwulcyjna, z 16 filtrami 3x3  10 neuronow w wartswie wyjsciowej, ReLu

kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]

train_image = load_mnist_images('train-images.idx3-ubyte')
train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')

# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy

output = np.zeros((16, 676))
W = np.random.uniform(-0.1, 0.1, (2704, 10))

bok = int(np.sqrt(train_image[0].size))
alpha = 0.001
nsamples = 10000
epochs = 300

one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]

for b in range(epochs):
    correct = 0
    for j in range(nsamples):
        x = train_image[j].reshape(bok, bok)
        y = one_hot_label[j]
        for i in range(16):
            new_row = convulsion(x, kernel[i], 1, 0)
            new_row_flat = new_row.flatten()
            output[i, :] = new_row_flat

        output = ReLu(output)
        output_2d = output.reshape(16, 26, 26)

        # Teraz trzeba zrobic pool, a w wstecznej wziasc pod uwage maske
        pool, mask = max_pooling(output_2d)

        pool_flat = pool.flatten()

        # teraz trzeba pomnozyc wektor przez dense layer.
        raw = np.dot(pool_flat, W)

        if np.argmax(raw) == train_image_labels[j]:
            correct += 1

        # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.
        delta = (2 * 1 / 10) * (raw - y)
        weight_delta = np.outer(pool_flat, delta)

        conv_raw = np.dot(delta, W.T).reshape((16, 13, 13))

        # Max pool backprop
        back_pool = np.repeat(np.repeat(conv_raw, 2, axis=1), 2, axis=2)

        delta_relu = back_pool * mask * ReLu_deriv(output.reshape((16, 26, 26)))
        W = W - alpha * weight_delta

        for i in range(16):
            kernel_delta = convulsion(x, delta_relu[i], 1, 0)
            kernel[i] = kernel[i] - alpha * kernel_delta

    if (b + 1) % 10 == 0 or b == 0:
        print(f"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%")
Epoka 1/300 - Skutecznosc treningowa: 34.59%
Epoka 10/300 - Skutecznosc treningowa: 86.54%
Epoka 20/300 - Skutecznosc treningowa: 89.63%
Epoka 30/300 - Skutecznosc treningowa: 91.55%
Epoka 40/300 - Skutecznosc treningowa: 92.70%
Epoka 50/300 - Skutecznosc treningowa: 93.43%
Epoka 60/300 - Skutecznosc treningowa: 93.91%
Epoka 70/300 - Skutecznosc treningowa: 94.35%
Epoka 80/300 - Skutecznosc treningowa: 94.75%
Epoka 90/300 - Skutecznosc treningowa: 95.07%
Epoka 100/300 - Skutecznosc treningowa: 95.25%
Epoka 110/300 - Skutecznosc treningowa: 95.43%
Epoka 120/300 - Skutecznosc treningowa: 95.56%
Epoka 130/300 - Skutecznosc treningowa: 95.69%
Epoka 140/300 - Skutecznosc treningowa: 95.80%
Epoka 150/300 - Skutecznosc treningowa: 95.99%
Epoka 160/300 - Skutecznosc treningowa: 96.04%
Epoka 170/300 - Skutecznosc treningowa: 96.15%
Epoka 180/300 - Skutecznosc treningowa: 96.24%
Epoka 190/300 - Skutecznosc treningowa: 96.37%
Epoka 200/300 - Skutecznosc treningowa: 96.49%
Epoka 210/300 - Skutecznosc treningowa: 96.52%
Epoka 220/300 - Skutecznosc treningowa: 96.60%
Epoka 230/300 - Skutecznosc treningowa: 96.66%
Epoka 240/300 - Skutecznosc treningowa: 96.71%
Epoka 250/300 - Skutecznosc treningowa: 96.76%
Epoka 260/300 - Skutecznosc treningowa: 96.81%
Epoka 270/300 - Skutecznosc treningowa: 96.85%
Epoka 280/300 - Skutecznosc treningowa: 96.92%
Epoka 290/300 - Skutecznosc treningowa: 96.97%
Epoka 300/300 - Skutecznosc treningowa: 97.00%
In [13]:
test_image = load_mnist_images('t10k-images.idx3-ubyte')
test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')

pred = 0
test_output = np.zeros((16, 676))

for i in range(10000):
    x = test_image[i].reshape(bok, bok)

    for k in range(16):
        new_row = convulsion(x, kernel[k], 1, 0)
        test_output[k, :] = new_row.flatten()

    test_output_relu = ReLu(test_output)

    output_2d = test_output_relu.reshape(16, 26, 26)

    pool, mask = max_pooling(output_2d)

    pool_flat = pool.flatten()

    raw = np.dot(pool_flat, W)

    przewidziana_cyfra = np.argmax(raw)
    prawdziwa_cyfra = test_image_labels[i]

    if przewidziana_cyfra == prawdziwa_cyfra:
        pred += 1

proc = (pred / 10000) * 100
print(f"Skutecznosc: {proc:.2f}%")
Skutecznosc: 95.96%

60000 obrazow, a= 0.01, 50 iteracji

In [9]:
# 1 Warstwa konwulcyjna, z 16 filtrami 3x3  10 neuronow w wartswie wyjsciowej, ReLu

kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]

train_image = load_mnist_images('train-images.idx3-ubyte')
train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')

# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy

output = np.zeros((16, 676))
W = np.random.uniform(-0.1, 0.1, (2704, 10))

bok = int(np.sqrt(train_image[0].size))
alpha = 0.01
nsamples = 60000
epochs = 50

one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]

for b in range(epochs):
    correct = 0
    for j in range(nsamples):
        x = train_image[j].reshape(bok, bok)
        y = one_hot_label[j]
        for i in range(16):
            new_row = convulsion(x, kernel[i], 1, 0)
            new_row_flat = new_row.flatten()
            output[i, :] = new_row_flat

        output = ReLu(output)
        output_2d = output.reshape(16, 26, 26)

        # Teraz trzeba zrobic pool, a w wstecznej wziasc pod uwage maske
        pool, mask = max_pooling(output_2d)

        pool_flat = pool.flatten()

        # teraz trzeba pomnozyc wektor przez dense layer.
        raw = np.dot(pool_flat, W)

        if np.argmax(raw) == train_image_labels[j]:
            correct += 1

        # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.
        delta = (2 * 1 / 10) * (raw - y)
        weight_delta = np.outer(pool_flat, delta)

        conv_raw = np.dot(delta, W.T).reshape((16, 13, 13))

        # Max pool backprop
        back_pool = np.repeat(np.repeat(conv_raw, 2, axis=1), 2, axis=2)

        delta_relu = back_pool * mask * ReLu_deriv(output.reshape((16, 26, 26)))
        W = W - alpha * weight_delta

        for i in range(16):
            kernel_delta = convulsion(x, delta_relu[i], 1, 0)
            kernel[i] = kernel[i] - alpha * kernel_delta

    if (b + 1) % 10 == 0 or b == 0:
        print(f"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%")
Epoka 1/50 - Skutecznosc treningowa: 88.65%
Epoka 10/50 - Skutecznosc treningowa: 96.88%
Epoka 20/50 - Skutecznosc treningowa: 97.37%
Epoka 30/50 - Skutecznosc treningowa: 97.56%
Epoka 40/50 - Skutecznosc treningowa: 97.66%
Epoka 50/50 - Skutecznosc treningowa: 97.74%
In [10]:
test_image = load_mnist_images('t10k-images.idx3-ubyte')
test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')

pred = 0
test_output = np.zeros((16, 676))

for i in range(10000):
    x = test_image[i].reshape(bok, bok)

    for k in range(16):
        new_row = convulsion(x, kernel[k], 1, 0)
        test_output[k, :] = new_row.flatten()

    test_output_relu = ReLu(test_output)

    output_2d = test_output_relu.reshape(16, 26, 26)

    pool, mask = max_pooling(output_2d)

    pool_flat = pool.flatten()

    raw = np.dot(pool_flat, W)

    przewidziana_cyfra = np.argmax(raw)
    prawdziwa_cyfra = test_image_labels[i]

    if przewidziana_cyfra == prawdziwa_cyfra:
        pred += 1

proc = (pred / 10000) * 100
print(f"Skutecznosc: {proc:.2f}%")
Skutecznosc: 97.49%