commit 905610642fb4b91878afc2a95a74cbf1e17f497a Author: basiek Date: Fri Dec 4 14:57:35 2026 +0100 chore: import existing project files diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/.idea/JupyterProject.iml b/.idea/JupyterProject.iml new file mode 100644 index 0000000..258c9e6 --- /dev/null +++ b/.idea/JupyterProject.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/PSI.iml b/.idea/PSI.iml new file mode 100644 index 0000000..1856f08 --- /dev/null +++ b/.idea/PSI.iml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..bead604 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..714462f --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..91d85a5 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { + "associatedIndex": 7, + "fromUser": false +} + + + + + + + + + + + + + + 1793619322586 + + + + + + \ No newline at end of file diff --git a/.ipynb_checkpoints/sample-checkpoint.ipynb b/.ipynb_checkpoints/sample-checkpoint.ipynb new file mode 100644 index 0000000..e69de29 diff --git a/LAB2.ipynb b/LAB2.ipynb new file mode 100644 index 0000000..74d46f8 --- /dev/null +++ b/LAB2.ipynb @@ -0,0 +1,366 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "e240313e75a92965", + "metadata": {}, + "source": [ + "# Laboratorium 2" + ] + }, + { + "cell_type": "markdown", + "id": "bd24186044d05b5c", + "metadata": { + "ExecuteTime": { + "end_time": "2026-10-14T09:25:08.681806831Z", + "start_time": "2026-10-14T09:25:08.610679950Z" + } + }, + "source": [ + "## Zadanie 1" + ] + }, + { + "cell_type": "code", + "id": "24c6b783334b0556", + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:32.519912534Z", + "start_time": "2026-11-04T13:37:32.466261885Z" + } + }, + "source": [ + "import numpy as np\n", + "\n", + "weight_value = np.array(0.5)\n", + "expected_value = np.array(0.8)\n", + "input = np.array(2)\n", + "alpha = 0.1\n", + "n = 1\n", + "\n", + "def error_prediction_n_epoch(weight_value, expected_value, input, alpha, n, x):\n", + " for i in range(x):\n", + " prediction = weight_value * input\n", + " delta = (np.outer(((2 / n) * (prediction - expected_value)),\n", + " input))\n", + " weight_value = weight_value - (alpha * delta)\n", + " return prediction, delta" + ], + "outputs": [], + "execution_count": 1 + }, + { + "cell_type": "code", + "id": "fbbac2e949ca045d", + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:32.584393763Z", + "start_time": "2026-11-04T13:37:32.523292517Z" + } + }, + "source": [ + "pred_5, err_5 = error_prediction_n_epoch(weight_value, expected_value, input, alpha, n, 5)\n", + "print(f\"Wynik dla 5 epok: {pred_5.item():.5f}, Błąd: {err_5.item():.10f}\\n\", )" + ], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Wynik dla 5 epok: 0.80032, Błąd: 0.0012800000\n", + "\n" + ] + } + ], + "execution_count": 2 + }, + { + "cell_type": "code", + "id": "9d6d0aec86b777ae", + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:32.634140435Z", + "start_time": "2026-11-04T13:37:32.591494653Z" + } + }, + "source": [ + "pred_20, err_20 = error_prediction_n_epoch(weight_value, expected_value, input, alpha, n, 20)\n", + "print(f\"Wynik dla 20 epok: {pred_20.item():.5f}, Błąd: {err_20.item():.10f}\\n\", )" + ], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Wynik dla 20 epok: 0.80000, Błąd: 0.0000000000\n", + "\n" + ] + } + ], + "execution_count": 3 + }, + { + "cell_type": "code", + "id": "62a29a8fa0d41975", + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:32.687186787Z", + "start_time": "2026-11-04T13:37:32.636238862Z" + } + }, + "source": [ + "new_alpha = 1\n", + "pred_alp_1, err_alp_1 = error_prediction_n_epoch(weight_value, expected_value, input, alpha, n, 5)\n", + "print(f\"Wynik alpha = 1: {pred_alp_1.item():.5f}, Błąd: {err_alp_1.item():.10f}\\n\", )\n", + "# Nigdy nei osiagnie celu przez zbyt wysoka alphe przez co przeskakujemy wartosc najblizsza." + ], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Wynik alpha = 1: 0.80032, Błąd: 0.0012800000\n", + "\n" + ] + } + ], + "execution_count": 4 + }, + { + "cell_type": "code", + "id": "5f47e48f0964e2d3", + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:32.781481476Z", + "start_time": "2026-11-04T13:37:32.689353042Z" + } + }, + "source": [ + "new_input = np.array(0.1)\n", + "pred_alp_1, err_alp_1 = error_prediction_n_epoch(weight_value, expected_value, new_input, alpha, n, 20000)\n", + "print(f\"Wynik input = 0.1: {pred_alp_1.item():.5f}, Błąd: {err_alp_1.item():.10f}\\n\", )\n", + "# Osiagnie cel dopiero po 20k epok." + ], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Wynik input = 0.1: 0.80000, Błąd: -0.0000000000\n", + "\n" + ] + } + ], + "execution_count": 5 + }, + { + "cell_type": "markdown", + "id": "73b83e4e6fc78d91", + "metadata": {}, + "source": [ + "## Zadanie 2" + ] + }, + { + "cell_type": "code", + "id": "ed6809cca4d96211", + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:32.839400273Z", + "start_time": "2026-11-04T13:37:32.786766917Z" + } + }, + "source": [ + "input_data = np.array([\n", + " [0.5, 0.1, 0.2, 0.8],\n", + " [0.75, 0.3, 0.1, 0.9],\n", + " [0.1, 0.7, 0.6, 0.2]\n", + "])\n", + "expected_results = np.array([\n", + " [0.1, 0.5, 0.1, 0.7],\n", + " [1.0, 0.2, 0.3, 0.6],\n", + " [0.1, -0.5, 0.2, 0.2],\n", + " [0.0, 0.3, 0.9, -0.1],\n", + " [-0.1, 0.7, 0.1, 0.8]\n", + "])\n", + "weights = np.array([\n", + " [0.1, 0.1, -0.3],\n", + " [0.1, 0.2, 0.0],\n", + " [0.0, 0.7, 0.1],\n", + " [0.2, 0.4, 0.0],\n", + " [-0.3, 0.5, 0.1]\n", + "])\n", + "epochs = 1000\n", + "alpha = 0.01\n", + "\n", + "\n", + "def neuron_network_learning_per_series(weights, input_data, expected_results, alpha, epochs):\n", + " w = weights.copy()\n", + " num_series = input_data.shape[1]\n", + " num_neurons = expected_results.shape[0]\n", + "\n", + " for epoch in range(epochs):\n", + " epoch_error = 0\n", + " for i in range(num_series):\n", + " x_i = input_data[:, i:i + 1]\n", + " y_i = expected_results[:, i:i + 1]\n", + " pred_i = np.dot(w, x_i)\n", + " error_i = (1 / num_neurons) * np.sum((pred_i - y_i) ** 2)\n", + " epoch_error += error_i\n", + " delta_i = (2 / num_neurons) * np.dot((pred_i - y_i), x_i.T)\n", + " w = w - alpha * delta_i\n", + " # print(f\"\\nEpoch {epoch + 1}:\")\n", + " # print(f\"Serie: {i + 1}:\\n\")\n", + " # print(\"\\nOutput: \\n\", pred_i)\n", + " # print(\"\\nWeights: \\n\", w)\n", + " # print(f\"\\nError: {error_i:.6f}\\n\")\n", + " return epoch_error" + ], + "outputs": [], + "execution_count": 6 + }, + { + "cell_type": "code", + "id": "298d88832156e7e3", + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:32.930222326Z", + "start_time": "2026-11-04T13:37:32.841342726Z" + } + }, + "source": "epoch_err = neuron_network_learning_per_series(weights, input_data, expected_results, alpha, epochs)", + "outputs": [], + "execution_count": 7 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:32.982286508Z", + "start_time": "2026-11-04T13:37:32.932885017Z" + } + }, + "cell_type": "code", + "source": "print(f\"Blad ostatniej epoki: {epoch_err:.6f}\\n\")", + "id": "b031dd3370566a75", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Blad ostatniej epoki: 0.258218\n", + "\n" + ] + } + ], + "execution_count": 8 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 3", + "id": "b010bf3ee2e61ff0" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-04T13:37:33.122170592Z", + "start_time": "2026-11-04T13:37:32.985840238Z" + } + }, + "cell_type": "code", + "source": [ + "w = np.random.uniform(-1, 1, (4, 3))\n", + "data = np.loadtxt('training_colors.txt')\n", + "\n", + "input = data[:, :3]\n", + "input_info = data[:, 3]\n", + "\n", + "goal = np.zeros((1, 4))\n", + "\n", + "color_map = {\n", + " 1: [1.0, 0.0, 0.0, 0.0], # Czerwony\n", + " 2: [0.0, 1.0, 0.0, 0.0], # Zielony\n", + " 3: [0.0, 0.0, 1.0, 0.0], # Niebieski\n", + " 4: [0.0, 0.0, 0.0, 1.0], # Żółty\n", + "}\n", + "\n", + "goal_list = [color_map[int(label)] for label in input_info]\n", + "goal = np.array(goal_list)\n", + "\n", + "goal = goal.T\n", + "input = input.T\n", + "alpha = 0.01\n", + "epochs = 100\n", + "\n", + "\n", + "def neuron_network_learning_per_series(weights, input_data, expected_results, alpha, epochs):\n", + " w = weights.copy()\n", + " num_series = input_data.shape[1]\n", + " num_neurons = expected_results.shape[0]\n", + "\n", + " for epoch in range(epochs):\n", + " epoch_error = 0\n", + " for i in range(num_series):\n", + " x_i = input_data[:, i:i + 1]\n", + " y_i = expected_results[:, i:i + 1]\n", + " pred_i = np.dot(w, x_i)\n", + " error_i = (1 / num_neurons) * np.sum((pred_i - y_i) ** 2)\n", + " epoch_error += error_i\n", + " delta_i = (2 / num_neurons) * np.dot((pred_i - y_i), x_i.T)\n", + " w = w - alpha * delta_i\n", + " return w\n", + "\n", + "w = neuron_network_learning_per_series(w, input, goal, alpha, epochs)\n", + "\n", + "test_data = np.loadtxt('test_colors.txt')\n", + "X_test = test_data[:, :3].T\n", + "y_test_info = test_data[:, 3]\n", + "\n", + "predictions_test = np.dot(w, X_test)\n", + "\n", + "y_pred_test = np.argmax(predictions_test, axis=0) + 1\n", + "\n", + "correct_predictions = np.sum(y_pred_test == y_test_info)\n", + "total_samples = len(y_test_info)\n", + "accuracy = (correct_predictions / total_samples) * 100.0\n", + "\n", + "print(f\"Poprawnie rozpoznane na zbiorze testowym: {correct_predictions} / {total_samples}\")\n", + "print(f\"Skuteczność sieci: {accuracy:.2f}%\")\n" + ], + "id": "123e2ae3e3e2ebed", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Poprawnie rozpoznane na zbiorze testowym: 130 / 130\n", + "Skuteczność sieci: 100.00%\n" + ] + } + ], + "execution_count": 9 + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.13.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/LAB3.ipynb b/LAB3.ipynb new file mode 100644 index 0000000..2cbcb2d --- /dev/null +++ b/LAB3.ipynb @@ -0,0 +1,632 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "e240313e75a92965", + "metadata": {}, + "source": "# Laboratorium 3" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:05.431744233Z", + "start_time": "2026-11-02T15:48:05.207672302Z" + } + }, + "cell_type": "code", + "source": [ + "from tensorflow import keras\n", + "from keras.models import Sequential\n", + "from keras.layers import Dense\n", + "from keras.optimizers import SGD\n", + "import numpy as np\n", + "import struct" + ], + "id": "4d18fbc40747d5a3", + "outputs": [], + "execution_count": 159 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 1", + "id": "b70f4ee5d79e60" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:05.526470433Z", + "start_time": "2026-11-02T15:48:05.438979772Z" + } + }, + "cell_type": "code", + "source": [ + "x = np.array([[0.5, 0.1, 0.2, 0.8], [0.75, 0.3, 0.1, 0.9], [0.1, 0.7, 0.6, 0.2]])\n", + "\n", + "Wh = np.array([\n", + " [0.1, 0.1, -0.3],\n", + " [0.1, 0.2, 0.0],\n", + " [0.0, 0.7, 0.1],\n", + " [0.2, 0.4, 0.0],\n", + " [-0.3, 0.5, 0.1]\n", + "])\n", + "\n", + "Wy = np.array([\n", + " [0.7, 0.9, -0.4, 0.8, 0.1],\n", + " [0.8, 0.5, 0.3, 0.1, 0.0],\n", + " [-0.3, 0.9, 0.3, 0.1, -0.2]\n", + "])\n", + "\n", + "\n", + "def ReLu(x):\n", + " return np.maximum(x, 0)\n", + "\n", + "\n", + "def deep_neural_network(input, weights_h, weights_y):\n", + " layer_hidden_1 = np.dot(weights_h, input)\n", + " layer_hidden_1_r = ReLu(layer_hidden_1)\n", + " layer_output = np.dot(weights_y, layer_hidden_1_r)\n", + " return layer_hidden_1, layer_hidden_1_r, layer_output\n", + "\n", + "\n", + "layer_hidden_1, layer_hidden_1_r, layer_output = deep_neural_network(x, Wh, Wy)\n", + "\n", + "print(layer_output)\n" + ], + "id": "1fe1f57f2e5d30a8", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0.376 0.082 0.053 0.49 ]\n", + " [0.3765 0.133 0.067 0.465 ]\n", + " [0.305 0.123 0.073 0.402 ]]\n" + ] + } + ], + "execution_count": 160 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 2", + "id": "c04a058b137dfe88" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:05.564390548Z", + "start_time": "2026-11-02T15:48:05.533869120Z" + } + }, + "cell_type": "code", + "source": [ + "goal = np.array([\n", + " [0.1, 0.5, 0.1, 0.7],\n", + " [1.0, 0.2, 0.3, 0.6],\n", + " [0.1, -0.5, 0.2, 0.2],\n", + "])\n", + "\n", + "alpha = 0.01\n", + "epochs = 50\n", + "\n", + "\n", + "def ReLu_deriv(x):\n", + " return np.where(x > 0, 1, 0)\n", + "\n", + "\n", + "def supervised_learning(input, weights_h, weights_y, goal, alpha, epochs):\n", + " num_neurons = goal.shape[0]\n", + " num_series = input.shape[1]\n", + " for i in range(epochs):\n", + " for j in range(num_series):\n", + " series_input = input[:, j:j + 1]\n", + " series_goal = goal[:, j:j + 1]\n", + " layer_hidden_1, layer_hidden_1_r, layer_output = deep_neural_network(series_input, weights_h, weights_y)\n", + "\n", + " layer_output_delta = (2 / num_neurons) * (layer_output - series_goal)\n", + "\n", + " layer_hidden_delta = np.dot(weights_y.T, layer_output_delta)\n", + " layer_hidden_delta = layer_hidden_delta * ReLu_deriv(layer_hidden_1)\n", + "\n", + " layer_output_weight_delta = np.dot(layer_output_delta, layer_hidden_1_r.T)\n", + " layer_hidden_weight_delta = np.dot(layer_hidden_delta, series_input.T)\n", + "\n", + " weights_h = weights_h - alpha * layer_hidden_weight_delta\n", + " weights_y = weights_y - alpha * layer_output_weight_delta\n", + " if (i == epochs - 1):\n", + " print(f\"\\nSeria {j + 1}:\")\n", + " print(np.round(layer_output, 6))\n", + "\n", + " return layer_output\n", + "\n", + "\n", + "output = supervised_learning(x, Wh, Wy, goal, alpha, epochs)\n" + ], + "id": "d13e053086fe80f6", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Seria 1:\n", + "[[0.442756]\n", + " [0.565494]\n", + " [0.157309]]\n", + "\n", + "Seria 2:\n", + "[[0.140418]\n", + " [0.186105]\n", + " [0.063895]]\n", + "\n", + "Seria 3:\n", + "[[0.105594]\n", + " [0.093659]\n", + " [0.045049]]\n", + "\n", + "Seria 4:\n", + "[[0.584537]\n", + " [0.711427]\n", + " [0.216373]]\n" + ] + } + ], + "execution_count": 161 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 3", + "id": "111fd4dd04394153" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:05.644432142Z", + "start_time": "2026-11-02T15:48:05.586047916Z" + } + }, + "cell_type": "code", + "source": [ + "def sigmoid(x):\n", + " x = np.clip(x, -500, 500)\n", + " return 1 / (1 + np.exp(-x))\n", + "\n", + "\n", + "def sigmoid_deriv(x):\n", + " return x * (1 - x)\n", + "\n", + "\n", + "class NeuralNewtork:\n", + " def __init__(self, n, a=0.01):\n", + " self.num_neurons = n\n", + " self.alpha = a\n", + " self.layers = {\n", + " 'weights': [],\n", + " 'activation_function': [],\n", + " 'derivative_function': [],\n", + " }\n", + "\n", + " def add_layer(self, n, activation_func):\n", + " weights = np.random.uniform(-1, 1, (n, self.num_neurons))\n", + " self.layers['weights'].append(weights)\n", + " self.num_neurons = n\n", + " if activation_func is not None:\n", + " self.layers['activation_function'].append(activation_func)\n", + " if activation_func == 'sigmoid':\n", + " self.layers['derivative_function'].append(sigmoid_deriv)\n", + " else:\n", + " self.layers['derivative_function'].append(ReLu_deriv)\n", + " else:\n", + " self.layers['activation_function'].append(None)\n", + " self.layers['derivative_function'].append(None)\n", + "\n", + " def forward_propagation(self, input):\n", + " activation = []\n", + " raw_output = []\n", + "\n", + " current_input = input\n", + " for i in range(len(self.layers['weights'])):\n", + " z = np.dot(self.layers['weights'][i], current_input)\n", + " raw_output.append(z)\n", + "\n", + " a = self.layers['activation_function'][i](z)\n", + " activation.append(a)\n", + " current_input = a\n", + "\n", + " return activation, raw_output\n", + "\n", + " def back_propagation(self, activation, input, raw_output, expected_output):\n", + " N = expected_output.shape[0]\n", + " layer_output_delta = (2 * 1 / N) * (activation[-1] - expected_output)\n", + "\n", + " layer_hidden_delta = np.dot(self.layers['weights'][-1].T, layer_output_delta)\n", + "\n", + " layer_output_weight_delta = np.dot(layer_output_delta, activation[-2].T)\n", + " self.layers['weights'][-1] = self.layers['weights'][-1] - self.alpha * layer_output_weight_delta\n", + "\n", + " for i in reversed(range(len(self.layers['weights']) - 1)):\n", + " layer_hidden_delta = layer_hidden_delta * self.layers['derivative_function'][i](raw_output[i])\n", + "\n", + " wejscie_lub_aktywacja = activation[i - 1] if i > 0 else input\n", + " layer_hidden_weight_delta = np.dot(layer_hidden_delta, wejscie_lub_aktywacja.T)\n", + "\n", + " self.layers['weights'][i] = self.layers['weights'][i] - self.alpha * layer_hidden_weight_delta\n", + "\n", + " def fit(self, input, expected_output):\n", + " input_data = (input.copy()).reshape(1, -1).T\n", + " activation, raw_output = self.forward_propagation(input_data)\n", + " self.back_propagation(activation, input_data, raw_output, expected_output)\n", + "\n", + " def predict(self, input):\n", + " input_data = (input.copy()).reshape(-1, 1)\n", + " activation, _ = self.forward_propagation(input_data)\n", + " return activation[-1]\n", + "\n", + "def load_mnist_images(filename):\n", + " with open(filename, 'rb') as f:\n", + " magic, num_images, rows, cols = struct.unpack('>IIII', f.read(16))\n", + " image_data = np.frombuffer(f.read(), dtype=np.uint8)\n", + " images = image_data.reshape(num_images, rows * cols).astype(np.float32) / 255.0\n", + " return images\n", + "\n", + "\n", + "def load_mnist_labels(filename):\n", + " with open(filename, 'rb') as f:\n", + " magic, num_labels = struct.unpack('>II', f.read(8))\n", + " labels = np.frombuffer(f.read(), dtype=np.uint8)\n", + " return labels\n", + "\n", + "\n", + "def to_one_hot(label, num_classes=10):\n", + " one_hot = np.zeros((num_classes, 1))\n", + " one_hot[label] = 1.0\n", + " return one_hot" + ], + "id": "49b96a3eca9ceae9", + "outputs": [], + "execution_count": 162 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:28.235953110Z", + "start_time": "2026-11-02T15:48:05.646551099Z" + } + }, + "cell_type": "code", + "source": [ + "nn = NeuralNewtork(784)\n", + "nn.add_layer(40, ReLu)\n", + "nn.add_layer(10, ReLu)\n", + "\n", + "train_image = load_mnist_images('train-images.idx3-ubyte')\n", + "train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')\n", + "\n", + "test_image = load_mnist_images('t10k-images.idx3-ubyte')\n", + "test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')\n", + "\n", + "epochs = 6\n", + "\n", + "print(\"Rozpoczynam proces uczenia sieci...\")\n", + "for epoch in range(epochs):\n", + " correct_train = 0\n", + "\n", + " for i in range(len(train_image)):\n", + " x = train_image[i].reshape(-1, 1)\n", + " label = train_image_labels[i]\n", + " expected = to_one_hot(label)\n", + "\n", + " nn.fit(x, expected)\n", + "\n", + " activation = nn.predict(x)\n", + " predicted_label = np.argmax(activation)\n", + " if predicted_label == label:\n", + " correct_train += 1\n", + "\n", + " train_accuracy = correct_train / len(train_image) * 100\n", + " print(f\"Epoka {epoch + 1}/{epochs} zakończona. Skuteczność treningowa: {train_accuracy:.2f}%\")\n" + ], + "id": "b2ee263a039e016e", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Rozpoczynam proces uczenia sieci...\n", + "Epoka 1/6 zakończona. Skuteczność treningowa: 61.03%\n", + "Epoka 2/6 zakończona. Skuteczność treningowa: 77.58%\n", + "Epoka 3/6 zakończona. Skuteczność treningowa: 83.84%\n", + "Epoka 4/6 zakończona. Skuteczność treningowa: 86.83%\n", + "Epoka 5/6 zakończona. Skuteczność treningowa: 88.48%\n", + "Epoka 6/6 zakończona. Skuteczność treningowa: 89.54%\n" + ] + } + ], + "execution_count": 163 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:28.366459094Z", + "start_time": "2026-11-02T15:48:28.238764489Z" + } + }, + "cell_type": "code", + "source": [ + "print(\"\\n--- TESTOWANIE SIECI (Zbiór testowy t10k) ---\")\n", + "correct_test = 0\n", + "\n", + "for i in range(len(test_image)):\n", + " x = test_image[i].reshape(-1, 1)\n", + " label = test_image_labels[i]\n", + "\n", + " activation = nn.predict(x)\n", + " predicted_label = np.argmax(activation)\n", + "\n", + " if predicted_label == label:\n", + " correct_test += 1\n", + "\n", + "test_accuracy = correct_test / len(test_image) * 100\n", + "print(f\"Skuteczność testowa modelu: {test_accuracy:.2f}%\")" + ], + "id": "7b709ff408ad9843", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- TESTOWANIE SIECI (Zbiór testowy t10k) ---\n", + "Skuteczność testowa modelu: 82.61%\n" + ] + } + ], + "execution_count": 164 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 4", + "id": "a5a0fbb71d562dba" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:28.456012551Z", + "start_time": "2026-11-02T15:48:28.374327966Z" + } + }, + "cell_type": "code", + "source": [ + "data = np.loadtxt('training_colors.txt')\n", + "\n", + "input = data[:, :3]\n", + "input_info = data[:, 3]\n", + "\n", + "goal = np.zeros((1, 4))\n", + "\n", + "color_map = {\n", + " 1: [1.0, 0.0, 0.0, 0.0], # Czerwony\n", + " 2: [0.0, 1.0, 0.0, 0.0], # Zielony\n", + " 3: [0.0, 0.0, 1.0, 0.0], # Niebieski\n", + " 4: [0.0, 0.0, 0.0, 1.0], # Żółty\n", + "}\n", + "\n", + "goal_list = [color_map[int(label)] for label in input_info]\n", + "goal = np.array(goal_list)\n", + "\n", + "nn = NeuralNewtork(3)\n", + "nn.add_layer(16, ReLu)\n", + "nn.add_layer(4, ReLu)\n", + "\n", + "epochs = 10\n", + "\n", + "print(\"Rozpoczynam proces uczenia sieci...\")\n", + "for epoch in range(epochs):\n", + " correct_train = 0\n", + "\n", + " for i in range(len(data)):\n", + " x = input[i].reshape(-1, 1)\n", + "\n", + " expected = goal[i].reshape(-1, 1)\n", + "\n", + " nn.fit(x, expected)\n", + "\n", + " activation = nn.predict(x)\n", + " predicted_label = np.argmax(activation)\n", + "\n", + " if predicted_label == int(input_info[i]) - 1:\n", + " correct_train += 1\n", + " train_accuracy = correct_train / len(data) * 100\n", + " print(f\"Epoka {epoch + 1}/{epochs} zakończona. Skuteczność treningowa: {train_accuracy:.2f}%\")\n" + ], + "id": "1b869f3b7546661b", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Rozpoczynam proces uczenia sieci...\n", + "Epoka 1/10 zakończona. Skuteczność treningowa: 50.46%\n", + "Epoka 2/10 zakończona. Skuteczność treningowa: 90.83%\n", + "Epoka 3/10 zakończona. Skuteczność treningowa: 100.00%\n", + "Epoka 4/10 zakończona. Skuteczność treningowa: 100.00%\n", + "Epoka 5/10 zakończona. Skuteczność treningowa: 100.00%\n", + "Epoka 6/10 zakończona. Skuteczność treningowa: 100.00%\n", + "Epoka 7/10 zakończona. Skuteczność treningowa: 100.00%\n", + "Epoka 8/10 zakończona. Skuteczność treningowa: 100.00%\n", + "Epoka 9/10 zakończona. Skuteczność treningowa: 100.00%\n", + "Epoka 10/10 zakończona. Skuteczność treningowa: 100.00%\n" + ] + } + ], + "execution_count": 165 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:28.512064093Z", + "start_time": "2026-11-02T15:48:28.457851611Z" + } + }, + "cell_type": "code", + "source": [ + "test_data = np.loadtxt('test_colors.txt')\n", + "\n", + "input_test = test_data[:, :3]\n", + "input_test_info = (test_data[:, 3] - 1)\n", + "\n", + "print(\"\\n--- TESTOWANIE SIECI (Zbiór testowy t10k) ---\")\n", + "correct_test = 0\n", + "\n", + "for i in range(len(test_data)):\n", + " x = input_test[i].reshape(-1, 1)\n", + "\n", + " activation = nn.predict(x)\n", + " predicted_label = np.argmax(activation)\n", + "\n", + " if predicted_label == int(input_test_info[i]):\n", + " correct_test += 1\n", + "\n", + "test_accuracy = correct_test / len(test_data) * 100\n", + "print(f\"Skuteczność testowa modelu: {test_accuracy:.2f}%\")" + ], + "id": "6074d03eb64c3496", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- TESTOWANIE SIECI (Zbiór testowy t10k) ---\n", + "Skuteczność testowa modelu: 100.00%\n" + ] + } + ], + "execution_count": 166 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 5\n", + "id": "133f30d616b9b9c2" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-02T15:48:31.171962142Z", + "start_time": "2026-11-02T15:48:28.515088448Z" + } + }, + "cell_type": "code", + "source": [ + "y_test = keras.utils.to_categorical(input_test_info, num_classes=4)\n", + "\n", + "model = Sequential()\n", + "\n", + "model.add(keras.Input(shape=(3,)))\n", + "model.add(Dense(16, use_bias=False, activation='relu'))\n", + "model.add(Dense(4, use_bias=False))\n", + "opt = SGD(learning_rate=0.01)\n", + "model.compile(opt, loss='mse', metrics=['accuracy'])\n", + "\n", + "model.fit(\n", + " input,\n", + " goal,\n", + " epochs=25,\n", + " batch_size=5,\n", + " validation_data=(input_test, y_test),\n", + " verbose=1\n", + ")\n", + "test_loss, test_accuracy = model.evaluate(input_test, y_test, verbose=0)\n", + "print(f\"\\nSkuteczność modelu na zbiorze testowym: {test_accuracy * 100:.2f}%\")" + ], + "id": "73ab306f4a4cdba6", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Epoch 1/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 7ms/step - accuracy: 0.2294 - loss: 0.2698 - val_accuracy: 0.2231 - val_loss: 0.2566\n", + "Epoch 2/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.2294 - loss: 0.2477 - val_accuracy: 0.2615 - val_loss: 0.2374\n", + "Epoch 3/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.2294 - loss: 0.2316 - val_accuracy: 0.2923 - val_loss: 0.2229\n", + "Epoch 4/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.2661 - loss: 0.2192 - val_accuracy: 0.3308 - val_loss: 0.2115\n", + "Epoch 5/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.2661 - loss: 0.2092 - val_accuracy: 0.3385 - val_loss: 0.2021\n", + "Epoch 6/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.3028 - loss: 0.2011 - val_accuracy: 0.3308 - val_loss: 0.1944\n", + "Epoch 7/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.3028 - loss: 0.1943 - val_accuracy: 0.3231 - val_loss: 0.1877\n", + "Epoch 8/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.2936 - loss: 0.1883 - val_accuracy: 0.3154 - val_loss: 0.1820\n", + "Epoch 9/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.3394 - loss: 0.1829 - val_accuracy: 0.3615 - val_loss: 0.1768\n", + "Epoch 10/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.3670 - loss: 0.1782 - val_accuracy: 0.4154 - val_loss: 0.1720\n", + "Epoch 11/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.4037 - loss: 0.1738 - val_accuracy: 0.4538 - val_loss: 0.1678\n", + "Epoch 12/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.4312 - loss: 0.1698 - val_accuracy: 0.4923 - val_loss: 0.1638\n", + "Epoch 13/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.4679 - loss: 0.1661 - val_accuracy: 0.5154 - val_loss: 0.1601\n", + "Epoch 14/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.4679 - loss: 0.1627 - val_accuracy: 0.5538 - val_loss: 0.1567\n", + "Epoch 15/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.5046 - loss: 0.1594 - val_accuracy: 0.5615 - val_loss: 0.1533\n", + "Epoch 16/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.5046 - loss: 0.1562 - val_accuracy: 0.5538 - val_loss: 0.1501\n", + "Epoch 17/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.5229 - loss: 0.1531 - val_accuracy: 0.5846 - val_loss: 0.1470\n", + "Epoch 18/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.5505 - loss: 0.1499 - val_accuracy: 0.6231 - val_loss: 0.1439\n", + "Epoch 19/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.5780 - loss: 0.1469 - val_accuracy: 0.6615 - val_loss: 0.1410\n", + "Epoch 20/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 4ms/step - accuracy: 0.6147 - loss: 0.1438 - val_accuracy: 0.6615 - val_loss: 0.1381\n", + "Epoch 21/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.6422 - loss: 0.1410 - val_accuracy: 0.6769 - val_loss: 0.1353\n", + "Epoch 22/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.6697 - loss: 0.1382 - val_accuracy: 0.7000 - val_loss: 0.1326\n", + "Epoch 23/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.6972 - loss: 0.1354 - val_accuracy: 0.7077 - val_loss: 0.1299\n", + "Epoch 24/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.7248 - loss: 0.1327 - val_accuracy: 0.7308 - val_loss: 0.1273\n", + "Epoch 25/25\n", + "\u001B[1m22/22\u001B[0m \u001B[32m━━━━━━━━━━━━━━━━━━━━\u001B[0m\u001B[37m\u001B[0m \u001B[1m0s\u001B[0m 3ms/step - accuracy: 0.7523 - loss: 0.1303 - val_accuracy: 0.7615 - val_loss: 0.1248\n", + "\n", + "Skuteczność modelu na zbiorze testowym: 76.15%\n" + ] + } + ], + "execution_count": 167 + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.13.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/LAB4.ipynb b/LAB4.ipynb new file mode 100644 index 0000000..235fb6b --- /dev/null +++ b/LAB4.ipynb @@ -0,0 +1,925 @@ +{ + "cells": [ + { + "metadata": {}, + "cell_type": "markdown", + "source": "# Laboratorium 4", + "id": "a5fdda4037524d27" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:04:49.400753329Z", + "start_time": "2026-11-09T22:04:49.357109712Z" + } + }, + "cell_type": "code", + "source": [ + "import numpy as np\n", + "import struct\n", + "import scipy as sc" + ], + "id": "4ddc40d457336ec4", + "outputs": [], + "execution_count": 107 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Kod laboratorium 3:", + "id": "69234b3906bf94a3" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:04:49.487814246Z", + "start_time": "2026-11-09T22:04:49.426247352Z" + } + }, + "cell_type": "code", + "source": [ + "def sigmoid(x):\n", + " x = np.clip(x, -500, 500)\n", + " return 1 / (1 + np.exp(-x))\n", + "\n", + "\n", + "def sigmoid_deriv(x):\n", + " s = sigmoid(x)\n", + " return s * (1 - s)\n", + "\n", + "\n", + "def tangens_hip(x):\n", + " return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))\n", + "\n", + "\n", + "def tangens_hip_deriv(x):\n", + " return 1 - x ** 2\n", + "\n", + "\n", + "def softmax(x):\n", + " return sc.special.softmax(x)\n", + "\n", + "\n", + "def softmax_deriv(x):\n", + " return np.ones_like(x)\n", + "\n", + "\n", + "def ReLu_deriv(x):\n", + " return np.where(x > 0, 1, 0)\n", + "\n", + "\n", + "def ReLu(x):\n", + " return np.maximum(x, 0)\n", + "\n", + "\n", + "def load_mnist_images(filename):\n", + " with open(filename, 'rb') as f:\n", + " magic, num_images, rows, cols = struct.unpack('>IIII', f.read(16))\n", + " image_data = np.frombuffer(f.read(), dtype=np.uint8)\n", + " images = image_data.reshape(num_images, rows * cols).astype(np.float32) / 255.0\n", + " return images\n", + "\n", + "\n", + "def load_mnist_labels(filename):\n", + " with open(filename, 'rb') as f:\n", + " magic, num_labels = struct.unpack('>II', f.read(8))\n", + " labels = np.frombuffer(f.read(), dtype=np.uint8)\n", + " return labels\n", + "\n", + "\n", + "def to_one_hot(label, num_classes=10):\n", + " one_hot = np.zeros((num_classes, 1))\n", + " one_hot[label] = 1.0\n", + " return one_hot\n", + "\n", + "\n", + "class NeuralNewtork:\n", + " def __init__(self, n, a=0.01):\n", + " self.num_neurons = n\n", + " self.alpha = a\n", + " self.layers = {\n", + " 'weights': [],\n", + " 'activation_function': [],\n", + " 'derivative_function': [],\n", + " }\n", + "\n", + " def add_layer(self, n, activation_func, w_min=-1.0, w_max=1.0):\n", + " weights = np.random.uniform(w_min, w_max, (n, self.num_neurons))\n", + " self.layers['weights'].append(weights)\n", + " self.num_neurons = n\n", + " if activation_func is not None:\n", + " self.layers['activation_function'].append(activation_func)\n", + " if activation_func == sigmoid:\n", + " self.layers['derivative_function'].append(sigmoid_deriv)\n", + " elif activation_func == ReLu:\n", + " self.layers['derivative_function'].append(ReLu_deriv)\n", + " elif activation_func == tangens_hip:\n", + " self.layers['derivative_function'].append(tangens_hip_deriv)\n", + " elif activation_func == softmax:\n", + " self.layers['derivative_function'].append(softmax_deriv)\n", + " else:\n", + " self.layers['activation_function'].append(None)\n", + " self.layers['derivative_function'].append(None)\n", + "\n", + " def forward_propagation(self, input):\n", + " activation = []\n", + " raw_output = []\n", + "\n", + " current_input = input\n", + " for i in range(len(self.layers['weights'])):\n", + " z = np.dot(self.layers['weights'][i], current_input)\n", + " raw_output.append(z)\n", + "\n", + " if self.layers['activation_function'][i] is not None:\n", + " a = self.layers['activation_function'][i](z)\n", + " else:\n", + " a = z\n", + " activation.append(a)\n", + " current_input = a\n", + "\n", + " return activation, raw_output\n", + "\n", + " def back_propagation(self, activation, input, raw_output, expected_output):\n", + " N = expected_output.shape[0]\n", + " layer_output_delta = (2 * 1 / N) * (activation[-1] - expected_output)\n", + "\n", + " layer_hidden_delta = np.dot(self.layers['weights'][-1].T, layer_output_delta)\n", + "\n", + " layer_output_weight_delta = np.dot(layer_output_delta, activation[-2].T)\n", + " self.layers['weights'][-1] = self.layers['weights'][-1] - self.alpha * layer_output_weight_delta\n", + "\n", + " for i in reversed(range(len(self.layers['weights']) - 1)):\n", + " layer_hidden_delta = layer_hidden_delta * self.layers['derivative_function'][i](\n", + " raw_output[i])\n", + "\n", + " wejscie_lub_aktywacja = activation[i - 1] if i > 0 else input\n", + " layer_hidden_weight_delta = np.dot(layer_hidden_delta, wejscie_lub_aktywacja.T)\n", + "\n", + " self.layers['weights'][i] = self.layers['weights'][i] - self.alpha * layer_hidden_weight_delta\n", + "\n", + " def dropout(self, input, expected_output, proc=0.5):\n", + " activation = []\n", + " raw_output = []\n", + " dropout_vectors = []\n", + "\n", + " current_input = input\n", + " num_layers = len(self.layers['weights'])\n", + " for i in range(num_layers):\n", + " z = np.dot(self.layers['weights'][i], current_input)\n", + " raw_output.append(z)\n", + "\n", + " if self.layers['activation_function'][i] is not None:\n", + " a = self.layers['activation_function'][i](z)\n", + " else:\n", + " a = z\n", + "\n", + " if i < num_layers - 1:\n", + " vector = np.random.default_rng().integers(0, 2, size=a.shape)\n", + " dropout_vectors.append(vector)\n", + " a = a * vector * (1 / proc)\n", + " else:\n", + " dropout_vectors.append(None)\n", + "\n", + " activation.append(a)\n", + " current_input = a\n", + "\n", + " N = expected_output.shape[0]\n", + " layer_output_delta = (2 * 1 / N) * (activation[-1] - expected_output)\n", + "\n", + " layer_hidden_delta = np.dot(self.layers['weights'][-1].T, layer_output_delta)\n", + "\n", + " layer_output_weight_delta = np.dot(layer_output_delta, activation[-2].T)\n", + " self.layers['weights'][-1] = self.layers['weights'][-1] - self.alpha * layer_output_weight_delta\n", + "\n", + " for i in reversed(range(num_layers - 1)):\n", + " layer_hidden_delta = dropout_vectors[i] * layer_hidden_delta * self.layers['derivative_function'][i](\n", + " raw_output[i])\n", + "\n", + " wejscie_lub_aktywacja = activation[i - 1] if i > 0 else input\n", + " layer_hidden_weight_delta = np.dot(layer_hidden_delta, wejscie_lub_aktywacja.T)\n", + "\n", + " self.layers['weights'][i] = self.layers['weights'][i] - self.alpha * layer_hidden_weight_delta\n", + " if i > 0:\n", + " layer_hidden_delta = np.dot(self.layers['weights'][i].T, layer_hidden_delta)\n", + "\n", + " def miniBatchGradientDescent(self, input, expected_output, n, proc=0.5):\n", + " num_samples, h = input.shape\n", + " for i in range(0, num_samples, n):\n", + " batch_input = input[i: i + n, :].T\n", + " batch_expected = expected_output[i: i + n, :].T\n", + " dropout_mask = []\n", + " activation = []\n", + " raw_output = []\n", + " Nr = batch_input.shape[1]\n", + "\n", + " current_input = batch_input\n", + " for l in range(len(self.layers['weights'])):\n", + " z = np.dot(self.layers['weights'][l], current_input)\n", + "\n", + " raw_output.append(z)\n", + "\n", + " if self.layers['activation_function'][l] is not None:\n", + " a = self.layers['activation_function'][l](z)\n", + " else:\n", + " a = z\n", + "\n", + " if l < len(self.layers['weights']) - 1:\n", + " mask = np.random.default_rng().integers(0, 2, size=a.shape)\n", + " a = a * mask * (1 / proc)\n", + " dropout_mask.append(mask)\n", + " else:\n", + " dropout_mask.append(None)\n", + "\n", + " activation.append(a)\n", + " current_input = a\n", + "\n", + " if self.layers['activation_function'][-1] == softmax:\n", + " layer_output_delta = ((activation[-1] - batch_expected)) / n\n", + " else:\n", + " layer_output_delta = (2 * 1 / Nr) * (activation[-1] - batch_expected)\n", + "\n", + " layer_hidden_delta = np.dot(self.layers['weights'][-1].T, layer_output_delta)\n", + "\n", + " layer_output_weight_delta = np.dot(layer_output_delta, activation[-2].T)\n", + " self.layers['weights'][-1] = self.layers['weights'][-1] - self.alpha * layer_output_weight_delta\n", + "\n", + " for l in reversed(range(len(self.layers['weights']) - 1)):\n", + " layer_hidden_delta = dropout_mask[l] * layer_hidden_delta * self.layers['derivative_function'][l](\n", + " raw_output[l])\n", + "\n", + " wejscie_lub_aktywacja = activation[l - 1] if l > 0 else batch_input\n", + " layer_hidden_weight_delta = np.dot(layer_hidden_delta, wejscie_lub_aktywacja.T)\n", + "\n", + " self.layers['weights'][l] = self.layers['weights'][l] - self.alpha * layer_hidden_weight_delta\n", + " if l > 0:\n", + " layer_hidden_delta = np.dot(self.layers['weights'][l].T, layer_hidden_delta)\n", + "\n", + " def fit(self, input, expected_output):\n", + " input_data = (input.copy()).reshape(1, -1).T\n", + " activation, raw_output = self.forward_propagation(input_data)\n", + " self.back_propagation(activation, input_data, raw_output, expected_output)\n", + "\n", + " def predict(self, input):\n", + " input_data = (input.copy()).reshape(-1, 1)\n", + " activation, _ = self.forward_propagation(input_data)\n", + " return activation[-1]\n" + ], + "id": "394f2d37d10b500e", + "outputs": [], + "execution_count": 108 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 1\n", + "id": "8338a244e10e008b" + }, + { + "cell_type": "code", + "id": "initial_id", + "metadata": { + "collapsed": true, + "ExecuteTime": { + "end_time": "2026-11-09T22:05:45.641840062Z", + "start_time": "2026-11-09T22:04:49.513578355Z" + } + }, + "source": [ + "nn = NeuralNewtork(784, a=0.005)\n", + "nn.add_layer(40, ReLu, -0.1, 0.1)\n", + "nn.add_layer(10, None, -0.1, 0.1)\n", + "\n", + "train_image = load_mnist_images('train-images.idx3-ubyte')\n", + "train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')\n", + "\n", + "test_image = load_mnist_images('t10k-images.idx3-ubyte')\n", + "test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')\n", + "\n", + "epochs = 350\n", + "n_train_samples = 1000\n", + "\n", + "print(\"Nauka z Dropout:\")\n", + "for epoch in range(epochs):\n", + " correct_train = 0\n", + "\n", + " for i in range(n_train_samples):\n", + " x = train_image[i].reshape(-1, 1)\n", + " label = train_image_labels[i]\n", + " expected = to_one_hot(label)\n", + "\n", + " nn.dropout(x, expected)\n", + "\n", + " prediction = nn.predict(x)\n", + " if np.argmax(prediction) == label:\n", + " correct_train += 1\n", + "\n", + " train_acc = (correct_train / n_train_samples) * 100\n", + " if (epoch + 1) % 10 == 0 or epoch == 0:\n", + " print(f\"Epoka {epoch + 1}/{epochs} | Skutecznosc: {train_acc:.2f}%\")" + ], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Nauka z Dropout:\n", + "Epoka 1/350 | Skutecznosc: 20.80%\n", + "Epoka 10/350 | Skutecznosc: 72.10%\n", + "Epoka 20/350 | Skutecznosc: 77.30%\n", + "Epoka 30/350 | Skutecznosc: 83.00%\n", + "Epoka 40/350 | Skutecznosc: 85.10%\n", + "Epoka 50/350 | Skutecznosc: 87.60%\n", + "Epoka 60/350 | Skutecznosc: 89.70%\n", + "Epoka 70/350 | Skutecznosc: 90.60%\n", + "Epoka 80/350 | Skutecznosc: 91.70%\n", + "Epoka 90/350 | Skutecznosc: 92.40%\n", + "Epoka 100/350 | Skutecznosc: 93.20%\n", + "Epoka 110/350 | Skutecznosc: 93.80%\n", + "Epoka 120/350 | Skutecznosc: 93.70%\n", + "Epoka 130/350 | Skutecznosc: 95.00%\n", + "Epoka 140/350 | Skutecznosc: 95.40%\n", + "Epoka 150/350 | Skutecznosc: 95.60%\n", + "Epoka 160/350 | Skutecznosc: 95.80%\n", + "Epoka 170/350 | Skutecznosc: 95.80%\n", + "Epoka 180/350 | Skutecznosc: 96.20%\n", + "Epoka 190/350 | Skutecznosc: 96.40%\n", + "Epoka 200/350 | Skutecznosc: 96.60%\n", + "Epoka 210/350 | Skutecznosc: 96.90%\n", + "Epoka 220/350 | Skutecznosc: 96.90%\n", + "Epoka 230/350 | Skutecznosc: 97.30%\n", + "Epoka 240/350 | Skutecznosc: 97.20%\n", + "Epoka 250/350 | Skutecznosc: 97.40%\n", + "Epoka 260/350 | Skutecznosc: 97.60%\n", + "Epoka 270/350 | Skutecznosc: 97.80%\n", + "Epoka 280/350 | Skutecznosc: 97.70%\n", + "Epoka 290/350 | Skutecznosc: 98.00%\n", + "Epoka 300/350 | Skutecznosc: 97.90%\n", + "Epoka 310/350 | Skutecznosc: 98.10%\n", + "Epoka 320/350 | Skutecznosc: 97.90%\n", + "Epoka 330/350 | Skutecznosc: 98.10%\n", + "Epoka 340/350 | Skutecznosc: 97.90%\n", + "Epoka 350/350 | Skutecznosc: 98.20%\n" + ] + } + ], + "execution_count": 109 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:05:45.801683169Z", + "start_time": "2026-11-09T22:05:45.644344961Z" + } + }, + "cell_type": "code", + "source": [ + "print(\"Sprawdzamy skutecznosc\")\n", + "correct_train = 0\n", + "\n", + "for i in range(n_train_samples):\n", + " x = test_image[i].reshape(-1, 1)\n", + " label = test_image_labels[i]\n", + " expected = to_one_hot(label)\n", + "\n", + " prediction = nn.predict(x)\n", + "\n", + " if np.argmax(prediction) == label:\n", + " correct_train += 1\n", + "\n", + "train_acc = (correct_train / n_train_samples) * 100\n", + "print(f\"Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "97ae5a0126c2ef3f", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Sprawdzamy skutecznosc\n", + "Skutecznosc: 84.00%\n" + ] + } + ], + "execution_count": 110 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 2\n", + "id": "5dedb9abf3e6fb73" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:05:53.643833057Z", + "start_time": "2026-11-09T22:05:45.804478234Z" + } + }, + "cell_type": "code", + "source": [ + "nn = NeuralNewtork(784, a=0.1)\n", + "nn.add_layer(40, ReLu, -0.1, 0.1)\n", + "nn.add_layer(10, None, -0.1, 0.1)\n", + "\n", + "epochs = 350\n", + "n_train_samples = 1000\n", + "\n", + "X_train = train_image[:n_train_samples]\n", + "Y_train = np.zeros((n_train_samples, 10))\n", + "for i in range(n_train_samples):\n", + " Y_train[i, train_image_labels[i]] = 1.0\n", + "\n", + "print(\"Nauka z miniBatchGradientDescent:\")\n", + "for epoch in range(epochs):\n", + " nn.miniBatchGradientDescent(X_train, Y_train, n=100)\n", + "\n", + " correct_train = 0\n", + " for i in range(n_train_samples):\n", + " prediction = nn.predict(train_image[i])\n", + " if np.argmax(prediction) == train_image_labels[i]:\n", + " correct_train += 1\n", + "\n", + " train_acc = (correct_train / n_train_samples) * 100\n", + " if (epoch + 1) % 10 == 0 or epoch == 0:\n", + " print(f\"Epoka {epoch + 1}/{epochs} | Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "6a52cd7422f24dea", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Nauka z miniBatchGradientDescent:\n", + "Epoka 1/350 | Skutecznosc: 43.00%\n", + "Epoka 10/350 | Skutecznosc: 78.30%\n", + "Epoka 20/350 | Skutecznosc: 85.60%\n", + "Epoka 30/350 | Skutecznosc: 89.00%\n", + "Epoka 40/350 | Skutecznosc: 91.60%\n", + "Epoka 50/350 | Skutecznosc: 93.10%\n", + "Epoka 60/350 | Skutecznosc: 93.80%\n", + "Epoka 70/350 | Skutecznosc: 94.40%\n", + "Epoka 80/350 | Skutecznosc: 95.10%\n", + "Epoka 90/350 | Skutecznosc: 95.40%\n", + "Epoka 100/350 | Skutecznosc: 95.90%\n", + "Epoka 110/350 | Skutecznosc: 96.60%\n", + "Epoka 120/350 | Skutecznosc: 96.60%\n", + "Epoka 130/350 | Skutecznosc: 96.70%\n", + "Epoka 140/350 | Skutecznosc: 97.10%\n", + "Epoka 150/350 | Skutecznosc: 97.10%\n", + "Epoka 160/350 | Skutecznosc: 97.20%\n", + "Epoka 170/350 | Skutecznosc: 97.60%\n", + "Epoka 180/350 | Skutecznosc: 97.80%\n", + "Epoka 190/350 | Skutecznosc: 98.10%\n", + "Epoka 200/350 | Skutecznosc: 98.00%\n", + "Epoka 210/350 | Skutecznosc: 98.50%\n", + "Epoka 220/350 | Skutecznosc: 98.70%\n", + "Epoka 230/350 | Skutecznosc: 98.60%\n", + "Epoka 240/350 | Skutecznosc: 98.80%\n", + "Epoka 250/350 | Skutecznosc: 98.50%\n", + "Epoka 260/350 | Skutecznosc: 99.20%\n", + "Epoka 270/350 | Skutecznosc: 99.10%\n", + "Epoka 280/350 | Skutecznosc: 99.20%\n", + "Epoka 290/350 | Skutecznosc: 99.20%\n", + "Epoka 300/350 | Skutecznosc: 99.30%\n", + "Epoka 310/350 | Skutecznosc: 99.30%\n", + "Epoka 320/350 | Skutecznosc: 99.30%\n", + "Epoka 330/350 | Skutecznosc: 99.30%\n", + "Epoka 340/350 | Skutecznosc: 99.40%\n", + "Epoka 350/350 | Skutecznosc: 99.40%\n" + ] + } + ], + "execution_count": 111 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:08:43.069226299Z", + "start_time": "2026-11-09T22:08:43.001351653Z" + } + }, + "cell_type": "code", + "source": [ + "print(\"Sprawdzamy skutecznosc\")\n", + "correct_train = 0\n", + "\n", + "for i in range(n_train_samples):\n", + " x = test_image[i].reshape(-1, 1)\n", + " label = test_image_labels[i]\n", + " expected = to_one_hot(label)\n", + "\n", + " prediction = nn.predict(x)\n", + "\n", + " if np.argmax(prediction) == label:\n", + " correct_train += 1\n", + "\n", + "train_acc = (correct_train / n_train_samples) * 100\n", + "print(f\"Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "c895ea161a612627", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Sprawdzamy skutecznosc\n", + "Skutecznosc: 9.90%\n" + ] + } + ], + "execution_count": 128 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 3\n", + "id": "406348aaf794ae" + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### a) Tangens Hipreboliczny:", + "id": "dc984f165eaa6ed" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:06:07.914731874Z", + "start_time": "2026-11-09T22:05:53.769525789Z" + } + }, + "cell_type": "code", + "source": [ + "nn = NeuralNewtork(784, a=0.02)\n", + "nn.add_layer(100, tangens_hip, -0.01, 0.01)\n", + "nn.add_layer(10, None, -0.1, 0.1)\n", + "\n", + "epochs = 350\n", + "n_train_samples = 1000\n", + "\n", + "X_train = train_image[:n_train_samples]\n", + "Y_train = np.zeros((n_train_samples, 10))\n", + "for i in range(n_train_samples):\n", + " Y_train[i, train_image_labels[i]] = 1.0\n", + "\n", + "print(\"Nauka z miniBatchGradientDescent: (Tangens hiperboliczny)\")\n", + "for epoch in range(epochs):\n", + " nn.miniBatchGradientDescent(X_train, Y_train, n=100)\n", + "\n", + " correct_train = 0\n", + " for i in range(n_train_samples):\n", + " prediction = nn.predict(train_image[i])\n", + " if np.argmax(prediction) == train_image_labels[i]:\n", + " correct_train += 1\n", + "\n", + " train_acc = (correct_train / n_train_samples) * 100\n", + " if (epoch + 1) % 10 == 0 or epoch == 0:\n", + " print(f\"Epoka {epoch + 1}/{epochs} | Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "b326f81a8fa25dad", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Nauka z miniBatchGradientDescent: (Tangens hiperboliczny)\n", + "Epoka 1/350 | Skutecznosc: 59.80%\n", + "Epoka 10/350 | Skutecznosc: 81.20%\n", + "Epoka 20/350 | Skutecznosc: 84.50%\n", + "Epoka 30/350 | Skutecznosc: 86.20%\n", + "Epoka 40/350 | Skutecznosc: 87.30%\n", + "Epoka 50/350 | Skutecznosc: 88.00%\n", + "Epoka 60/350 | Skutecznosc: 89.10%\n", + "Epoka 70/350 | Skutecznosc: 89.50%\n", + "Epoka 80/350 | Skutecznosc: 90.10%\n", + "Epoka 90/350 | Skutecznosc: 90.60%\n", + "Epoka 100/350 | Skutecznosc: 90.90%\n", + "Epoka 110/350 | Skutecznosc: 90.50%\n", + "Epoka 120/350 | Skutecznosc: 91.00%\n", + "Epoka 130/350 | Skutecznosc: 91.80%\n", + "Epoka 140/350 | Skutecznosc: 92.10%\n", + "Epoka 150/350 | Skutecznosc: 92.10%\n", + "Epoka 160/350 | Skutecznosc: 92.50%\n", + "Epoka 170/350 | Skutecznosc: 92.70%\n", + "Epoka 180/350 | Skutecznosc: 92.90%\n", + "Epoka 190/350 | Skutecznosc: 93.20%\n", + "Epoka 200/350 | Skutecznosc: 93.50%\n", + "Epoka 210/350 | Skutecznosc: 93.30%\n", + "Epoka 220/350 | Skutecznosc: 93.70%\n", + "Epoka 230/350 | Skutecznosc: 93.60%\n", + "Epoka 240/350 | Skutecznosc: 93.70%\n", + "Epoka 250/350 | Skutecznosc: 93.80%\n", + "Epoka 260/350 | Skutecznosc: 94.00%\n", + "Epoka 270/350 | Skutecznosc: 94.40%\n", + "Epoka 280/350 | Skutecznosc: 94.50%\n", + "Epoka 290/350 | Skutecznosc: 94.50%\n", + "Epoka 300/350 | Skutecznosc: 94.40%\n", + "Epoka 310/350 | Skutecznosc: 94.90%\n", + "Epoka 320/350 | Skutecznosc: 94.90%\n", + "Epoka 330/350 | Skutecznosc: 95.30%\n", + "Epoka 340/350 | Skutecznosc: 95.30%\n", + "Epoka 350/350 | Skutecznosc: 95.20%\n" + ] + } + ], + "execution_count": 113 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:06:08.030264881Z", + "start_time": "2026-11-09T22:06:07.917035085Z" + } + }, + "cell_type": "code", + "source": [ + "print(\"Sprawdzamy skutecznosc (Hipreboliczny)\")\n", + "correct_train = 0\n", + "\n", + "for i in range(n_train_samples):\n", + " x = test_image[i].reshape(-1, 1)\n", + " label = test_image_labels[i]\n", + " expected = to_one_hot(label)\n", + "\n", + " prediction = nn.predict(x)\n", + "\n", + " if np.argmax(prediction) == label:\n", + " correct_train += 1\n", + "\n", + "train_acc = (correct_train / n_train_samples) * 100\n", + "print(f\"Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "802956bbd42c04f5", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Sprawdzamy skutecznosc (Hipreboliczny)\n", + "Skutecznosc: 76.00%\n" + ] + } + ], + "execution_count": 114 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### b) Sigmoidalna:", + "id": "a9e73283f38189" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:06:23.079766733Z", + "start_time": "2026-11-09T22:06:08.056998719Z" + } + }, + "cell_type": "code", + "source": [ + "nn = NeuralNewtork(784, a=0.01)\n", + "nn.add_layer(100, sigmoid, -0.1, 0.1)\n", + "nn.add_layer(10, None, -0.1, 0.1)\n", + "\n", + "epochs = 350\n", + "n_train_samples = 1000\n", + "\n", + "X_train = train_image[:n_train_samples]\n", + "Y_train = np.zeros((n_train_samples, 10))\n", + "for i in range(n_train_samples):\n", + " Y_train[i, train_image_labels[i]] = 1.0\n", + "\n", + "print(\"Nauka z miniBatchGradientDescent: (Tangens Sigmoidalna)\")\n", + "for epoch in range(epochs):\n", + " nn.miniBatchGradientDescent(X_train, Y_train, n=100)\n", + "\n", + " correct_train = 0\n", + " for i in range(n_train_samples):\n", + " prediction = nn.predict(train_image[i])\n", + " if np.argmax(prediction) == train_image_labels[i]:\n", + " correct_train += 1\n", + "\n", + " train_acc = (correct_train / n_train_samples) * 100\n", + " if (epoch + 1) % 10 == 0 or epoch == 0:\n", + " print(f\"Epoka {epoch + 1}/{epochs} | Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "d02b5688f2c296cb", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Nauka z miniBatchGradientDescent: (Tangens Sigmoidalna)\n", + "Epoka 1/350 | Skutecznosc: 12.30%\n", + "Epoka 10/350 | Skutecznosc: 38.10%\n", + "Epoka 20/350 | Skutecznosc: 52.40%\n", + "Epoka 30/350 | Skutecznosc: 56.50%\n", + "Epoka 40/350 | Skutecznosc: 61.20%\n", + "Epoka 50/350 | Skutecznosc: 65.50%\n", + "Epoka 60/350 | Skutecznosc: 62.00%\n", + "Epoka 70/350 | Skutecznosc: 64.50%\n", + "Epoka 80/350 | Skutecznosc: 63.60%\n", + "Epoka 90/350 | Skutecznosc: 65.60%\n", + "Epoka 100/350 | Skutecznosc: 63.00%\n", + "Epoka 110/350 | Skutecznosc: 66.90%\n", + "Epoka 120/350 | Skutecznosc: 67.20%\n", + "Epoka 130/350 | Skutecznosc: 68.50%\n", + "Epoka 140/350 | Skutecznosc: 70.40%\n", + "Epoka 150/350 | Skutecznosc: 66.30%\n", + "Epoka 160/350 | Skutecznosc: 68.60%\n", + "Epoka 170/350 | Skutecznosc: 69.50%\n", + "Epoka 180/350 | Skutecznosc: 70.30%\n", + "Epoka 190/350 | Skutecznosc: 67.90%\n", + "Epoka 200/350 | Skutecznosc: 69.40%\n", + "Epoka 210/350 | Skutecznosc: 69.50%\n", + "Epoka 220/350 | Skutecznosc: 68.30%\n", + "Epoka 230/350 | Skutecznosc: 68.50%\n", + "Epoka 240/350 | Skutecznosc: 69.60%\n", + "Epoka 250/350 | Skutecznosc: 70.00%\n", + "Epoka 260/350 | Skutecznosc: 69.00%\n", + "Epoka 270/350 | Skutecznosc: 69.20%\n", + "Epoka 280/350 | Skutecznosc: 70.90%\n", + "Epoka 290/350 | Skutecznosc: 71.20%\n", + "Epoka 300/350 | Skutecznosc: 70.50%\n", + "Epoka 310/350 | Skutecznosc: 69.90%\n", + "Epoka 320/350 | Skutecznosc: 69.90%\n", + "Epoka 330/350 | Skutecznosc: 71.40%\n", + "Epoka 340/350 | Skutecznosc: 72.00%\n", + "Epoka 350/350 | Skutecznosc: 71.90%\n" + ] + } + ], + "execution_count": 115 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:06:23.176585148Z", + "start_time": "2026-11-09T22:06:23.082613887Z" + } + }, + "cell_type": "code", + "source": [ + "print(\"Sprawdzamy skutecznosc (Sigmoidalna)\")\n", + "correct_train = 0\n", + "\n", + "for i in range(n_train_samples):\n", + " x = test_image[i].reshape(-1, 1)\n", + " label = test_image_labels[i]\n", + " expected = to_one_hot(label)\n", + "\n", + " prediction = nn.predict(x)\n", + "\n", + " if np.argmax(prediction) == label:\n", + " correct_train += 1\n", + "\n", + "train_acc = (correct_train / n_train_samples) * 100\n", + "print(f\"Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "97bdfb311beef8b", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Sprawdzamy skutecznosc (Sigmoidalna)\n", + "Skutecznosc: 65.30%\n" + ] + } + ], + "execution_count": 116 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### c) Softmax:", + "id": "3a651d88e1268c45" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:41:09.173072614Z", + "start_time": "2026-11-09T22:41:04.716200045Z" + } + }, + "cell_type": "code", + "source": [ + "nn = NeuralNewtork(784, a=0.02)\n", + "nn.add_layer(100, ReLu, -0.1, 0.1)\n", + "nn.add_layer(10, softmax, -0.1, 0.1)\n", + "\n", + "epochs = 350\n", + "n_train_samples = 1000\n", + "\n", + "X_train = train_image[:n_train_samples]\n", + "Y_train = np.zeros((n_train_samples, 10))\n", + "for i in range(n_train_samples):\n", + " Y_train[i, train_image_labels[i]] = 1.0\n", + "\n", + "print(\"Nauka z miniBatchGradientDescent: (Softmax:)\")\n", + "for epoch in range(epochs):\n", + " nn.miniBatchGradientDescent(X_train, Y_train, n=100)\n", + "\n", + " correct_train = 0\n", + " for i in range(n_train_samples):\n", + " prediction = nn.predict(train_image[i])\n", + " if np.argmax(prediction) == train_image_labels[i]:\n", + " correct_train += 1\n", + "\n", + " train_acc = (correct_train / n_train_samples) * 100\n", + " if (epoch + 1) % 10 == 0 or epoch == 0:\n", + " print(f\"Epoka {epoch + 1}/{epochs} | Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "f286afb719a046b0", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Nauka z miniBatchGradientDescent: (Softmax:)\n", + "Epoka 1/350 | Skutecznosc: 13.90%\n", + "Epoka 10/350 | Skutecznosc: 14.40%\n", + "Epoka 20/350 | Skutecznosc: 11.70%\n", + "Epoka 30/350 | Skutecznosc: 11.70%\n", + "Epoka 40/350 | Skutecznosc: 11.70%\n", + "Epoka 50/350 | Skutecznosc: 11.70%\n", + "Epoka 60/350 | Skutecznosc: 11.70%\n", + "Epoka 70/350 | Skutecznosc: 11.70%\n", + "Epoka 80/350 | Skutecznosc: 11.70%\n" + ] + }, + { + "ename": "KeyboardInterrupt", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001B[31m---------------------------------------------------------------------------\u001B[39m", + "\u001B[31mKeyboardInterrupt\u001B[39m Traceback (most recent call last)", + "\u001B[36mCell\u001B[39m\u001B[36m \u001B[39m\u001B[32mIn[129]\u001B[39m\u001B[32m, line 19\u001B[39m\n\u001B[32m 15\u001B[39m nn.miniBatchGradientDescent(X_train, Y_train, n=\u001B[32m100\u001B[39m)\n\u001B[32m 16\u001B[39m \n\u001B[32m 17\u001B[39m correct_train = \u001B[32m0\u001B[39m\n\u001B[32m 18\u001B[39m \u001B[38;5;28;01mfor\u001B[39;00m i \u001B[38;5;28;01min\u001B[39;00m range(n_train_samples):\n\u001B[32m---> \u001B[39m\u001B[32m19\u001B[39m prediction = nn.predict(train_image[i])\n\u001B[32m 20\u001B[39m \u001B[38;5;28;01mif\u001B[39;00m np.argmax(prediction) == train_image_labels[i]:\n\u001B[32m 21\u001B[39m correct_train += \u001B[32m1\u001B[39m\n\u001B[32m 22\u001B[39m \n", + "\u001B[36mCell\u001B[39m\u001B[36m \u001B[39m\u001B[32mIn[108]\u001B[39m\u001B[32m, line 224\u001B[39m, in \u001B[36mNeuralNewtork.predict\u001B[39m\u001B[34m(self, input)\u001B[39m\n\u001B[32m 222\u001B[39m \u001B[38;5;28;01mdef\u001B[39;00m predict(self, input):\n\u001B[32m 223\u001B[39m input_data = (input.copy()).reshape(-\u001B[32m1\u001B[39m, \u001B[32m1\u001B[39m)\n\u001B[32m--> \u001B[39m\u001B[32m224\u001B[39m activation, _ = self.forward_propagation(input_data)\n\u001B[32m 225\u001B[39m \u001B[38;5;28;01mreturn\u001B[39;00m activation[-\u001B[32m1\u001B[39m]\n", + "\u001B[36mCell\u001B[39m\u001B[36m \u001B[39m\u001B[32mIn[108]\u001B[39m\u001B[32m, line 90\u001B[39m, in \u001B[36mNeuralNewtork.forward_propagation\u001B[39m\u001B[34m(self, input)\u001B[39m\n\u001B[32m 86\u001B[39m raw_output = []\n\u001B[32m 87\u001B[39m \n\u001B[32m 88\u001B[39m current_input = input\n\u001B[32m 89\u001B[39m \u001B[38;5;28;01mfor\u001B[39;00m i \u001B[38;5;28;01min\u001B[39;00m range(len(self.layers[\u001B[33m'weights'\u001B[39m])):\n\u001B[32m---> \u001B[39m\u001B[32m90\u001B[39m z = np.dot(self.layers[\u001B[33m'weights'\u001B[39m][i], current_input)\n\u001B[32m 91\u001B[39m raw_output.append(z)\n\u001B[32m 92\u001B[39m \n\u001B[32m 93\u001B[39m \u001B[38;5;28;01mif\u001B[39;00m self.layers[\u001B[33m'activation_function'\u001B[39m][i] \u001B[38;5;28;01mis\u001B[39;00m \u001B[38;5;28;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n", + "\u001B[31mKeyboardInterrupt\u001B[39m: " + ] + } + ], + "execution_count": 129 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-09T22:06:40.771702833Z", + "start_time": "2026-11-09T22:06:40.613076766Z" + } + }, + "cell_type": "code", + "source": [ + "correct_train = 0\n", + "\n", + "for i in range(n_train_samples):\n", + " x = test_image[i].reshape(-1, 1)\n", + " label = test_image_labels[i]\n", + " expected = to_one_hot(label)\n", + "\n", + " prediction = nn.predict(x)\n", + "\n", + " if np.argmax(prediction) == label:\n", + " correct_train += 1\n", + "\n", + "train_acc = (correct_train / n_train_samples) * 100\n", + "print(f\"Skutecznosc: {train_acc:.2f}%\")" + ], + "id": "dbe2b39d2226ed3a", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Skutecznosc: 9.90%\n" + ] + } + ], + "execution_count": 118 + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/LAB5.ipynb b/LAB5.ipynb new file mode 100644 index 0000000..3caf398 --- /dev/null +++ b/LAB5.ipynb @@ -0,0 +1,1123 @@ +{ + "cells": [ + { + "metadata": {}, + "cell_type": "markdown", + "source": "# Laboratorium 5", + "id": "d2a91852c332946c" + }, + { + "cell_type": "code", + "id": "initial_id", + "metadata": { + "collapsed": true, + "ExecuteTime": { + "end_time": "2026-11-24T16:55:29.184700631Z", + "start_time": "2026-11-24T16:55:29.091785500Z" + } + }, + "source": [ + "import numpy as np\n", + "import struct\n", + "import scipy as sc\n", + "from numpy.lib.stride_tricks import sliding_window_view" + ], + "outputs": [], + "execution_count": 2 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 1", + "id": "20f7ff979715d0b7" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T16:55:29.948474692Z", + "start_time": "2026-11-24T16:55:29.914553229Z" + } + }, + "cell_type": "code", + "source": [ + "input_image = np.array([\n", + " [1, 1, 1, 0, 0],\n", + " [0, 1, 1, 1, 0],\n", + " [0, 0, 1, 1, 1],\n", + " [0, 0, 1, 1, 0],\n", + " [0, 1, 1, 0, 0]\n", + "])\n", + "\n", + "filter = np.array([\n", + " [1, 0, 1],\n", + " [0, 1, 0],\n", + " [1, 0, 1]\n", + "])\n", + "\n", + "output_image = np.array([\n", + " [4, 3, 4],\n", + " [2, 4, 3],\n", + " [2, 3, 4]\n", + "])" + ], + "id": "85144c8764288375", + "outputs": [], + "execution_count": 3 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T16:55:31.578189006Z", + "start_time": "2026-11-24T16:55:31.546948872Z" + } + }, + "cell_type": "code", + "source": [ + "def convulsion(image, filtr, step, padding):\n", + " if padding != 0:\n", + " image = np.pad(image, padding)\n", + " h_img, w_img = image.shape\n", + " h_filter, w_filter = filtr.shape\n", + " h_out = (h_img - h_filter) // step + 1\n", + " w_out = (w_img - w_filter) // step + 1\n", + "\n", + " output = np.zeros((h_out, w_out))\n", + "\n", + " for i in range(h_out):\n", + " for j in range(w_out):\n", + " h_idx = i * step\n", + " w_idx = j * step\n", + "\n", + " window = image[h_idx:h_idx + h_filter, w_idx:w_idx + w_filter]\n", + " output[i, j] = np.sum(window * filtr)\n", + " return output\n", + "\n", + "\n", + "def convulsion(image, filtr, step=1, padding=0):\n", + " if padding != 0:\n", + " image = np.pad(image, padding)\n", + " h_filter, w_filter = filtr.shape\n", + "\n", + " windows = sliding_window_view(image, (h_filter, w_filter))[::step, ::step]\n", + "\n", + " return np.sum(windows * filtr, axis=(2, 3))" + ], + "id": "8e50c10e150b6e2e", + "outputs": [], + "execution_count": 4 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-23T20:26:25.167399170Z", + "start_time": "2026-11-23T20:26:25.107225412Z" + } + }, + "cell_type": "code", + "source": "convulsion(input_image, filter, 1, 0)", + "id": "a74fe25f30a15b5f", + "outputs": [ + { + "data": { + "text/plain": [ + "array([[4, 3, 4],\n", + " [2, 4, 3],\n", + " [2, 3, 4]])" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "execution_count": 32 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 2", + "id": "ff1f08ecb1c6a812" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T16:56:41.382930340Z", + "start_time": "2026-11-24T16:56:41.347487785Z" + } + }, + "cell_type": "code", + "source": [ + "def ReLu(x):\n", + " return np.maximum(x, 0)\n", + "\n", + "\n", + "def ReLu_deriv(x):\n", + " return np.where(x > 0, 1, 0)\n", + "\n", + "\n", + "def softmax(x):\n", + " return sc.special.softmax(x)\n", + "\n", + "\n", + "def softmax_deriv(x):\n", + " return np.ones_like(x)\n", + "\n", + "\n", + "def load_mnist_images(filename):\n", + " with open(filename, 'rb') as f:\n", + " magic, num_images, rows, cols = struct.unpack('>IIII', f.read(16))\n", + " image_data = np.frombuffer(f.read(), dtype=np.uint8)\n", + " images = image_data.reshape(num_images, rows * cols).astype(np.float32) / 255.0\n", + " return images\n", + "\n", + "\n", + "def load_mnist_labels(filename):\n", + " with open(filename, 'rb') as f:\n", + " magic, num_labels = struct.unpack('>II', f.read(8))\n", + " labels = np.frombuffer(f.read(), dtype=np.uint8)\n", + " return labels\n", + "\n", + "\n", + "def to_one_hot(label, num_classes=10):\n", + " one_hot = np.zeros((num_classes, 1))\n", + " one_hot[label] = 1.0\n", + " return one_hot" + ], + "id": "643c9eb1593b3ac6", + "outputs": [], + "execution_count": 6 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### 1000 obrazow, a= 0.01, 50 iteracji", + "id": "d0aedf40dba2d464" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-23T20:28:17.357453290Z", + "start_time": "2026-11-23T20:26:25.242960784Z" + } + }, + "cell_type": "code", + "source": [ + "# 1 Warstwa konwulcyjna, z 16 filtrami 3x3 10 neuronow w wartswie wyjsciowej, ReLu\n", + "\n", + "kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]\n", + "\n", + "train_image = load_mnist_images('train-images.idx3-ubyte')\n", + "train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')\n", + "\n", + "# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy\n", + "\n", + "output = np.zeros((16, 676))\n", + "W = np.random.uniform(-0.1, 0.1, (10816, 10))\n", + "\n", + "bok = int(np.sqrt(train_image[0].size))\n", + "alpha = 0.01\n", + "nsamples = 1000\n", + "epochs = 50\n", + "\n", + "one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]\n", + "\n", + "for b in range(epochs):\n", + " correct = 0\n", + " for j in range(nsamples):\n", + " x = train_image[j].reshape(bok, bok)\n", + " y = one_hot_label[j]\n", + " for i in range(16):\n", + " new_row = convulsion(x, kernel[i], 1, 0)\n", + " new_row_flat = new_row.flatten()\n", + " output[i, :] = new_row_flat\n", + "\n", + " output = ReLu(output)\n", + " output_flat = output.flatten()\n", + "\n", + " # teraz trzeba pomnozyc wektor przez dense layer.\n", + " raw = np.dot(output_flat, W)\n", + "\n", + " if np.argmax(raw) == train_image_labels[j]:\n", + " correct += 1\n", + "\n", + " # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.\n", + " delta = (2 * 1 / 10) * (raw - y)\n", + " weight_delta = np.outer(output_flat, delta)\n", + "\n", + " conv_raw = np.dot(delta, W.T).reshape((16, 26, 26))\n", + " delta_relu = conv_raw * ReLu_deriv(output.reshape((16, 26, 26)))\n", + " W = W - alpha * weight_delta\n", + "\n", + " for i in range(16):\n", + " kernel_delta = convulsion(x, delta_relu[i], 1, 0)\n", + " kernel[i] = kernel[i] - alpha * kernel_delta\n", + "\n", + " if (b + 1) % 10 == 0 or b == 0:\n", + " print(f\"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%\")" + ], + "id": "449d9a4f62d57df", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Epoka 1/50 - Skutecznosc treningowa: 27.50%\n", + "Epoka 10/50 - Skutecznosc treningowa: 86.30%\n", + "Epoka 20/50 - Skutecznosc treningowa: 90.30%\n", + "Epoka 30/50 - Skutecznosc treningowa: 92.80%\n", + "Epoka 40/50 - Skutecznosc treningowa: 95.10%\n", + "Epoka 50/50 - Skutecznosc treningowa: 97.10%\n" + ] + } + ], + "execution_count": 34 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-23T20:28:18.629294791Z", + "start_time": "2026-11-23T20:28:17.360207459Z" + } + }, + "cell_type": "code", + "source": [ + "test_image = load_mnist_images('t10k-images.idx3-ubyte')\n", + "test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')\n", + "\n", + "pred = 0\n", + "test_output = np.zeros((16, 676))\n", + "\n", + "for i in range(nsamples):\n", + " x = test_image[i].reshape(bok, bok)\n", + "\n", + " for k in range(16):\n", + " new_row = convulsion(x, kernel[k], 1, 0)\n", + " test_output[k, :] = new_row.flatten()\n", + "\n", + " test_output_relu = ReLu(test_output)\n", + " raw = np.dot(test_output_relu.flatten(), W)\n", + "\n", + " przewidziana_cyfra = np.argmax(raw)\n", + " prawdziwa_cyfra = test_image_labels[i]\n", + "\n", + " if przewidziana_cyfra == prawdziwa_cyfra:\n", + " pred += 1\n", + "\n", + "proc = (pred / nsamples) * 100\n", + "print(f\"Skutecznosc: {proc:.2f}%\")\n" + ], + "id": "5406d570240f1819", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Skutecznosc: 84.50%\n" + ] + } + ], + "execution_count": 35 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### 10000 obrazow, a= 0.01, 50 iteracji", + "id": "2f1b63486bc4006" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-23T20:44:20.855932437Z", + "start_time": "2026-11-23T20:28:18.632652402Z" + } + }, + "cell_type": "code", + "source": [ + "# 1 Warstwa konwulcyjna, z 16 filtrami 3x3 10 neuronow w wartswie wyjsciowej, ReLu\n", + "\n", + "kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]\n", + "\n", + "train_image = load_mnist_images('train-images.idx3-ubyte')\n", + "train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')\n", + "\n", + "# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy\n", + "\n", + "output = np.zeros((16, 676))\n", + "W = np.random.uniform(-0.1, 0.1, (10816, 10))\n", + "\n", + "bok = int(np.sqrt(train_image[0].size))\n", + "alpha = 0.01\n", + "nsamples = 10000\n", + "epochs = 50\n", + "\n", + "one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]\n", + "\n", + "for b in range(epochs):\n", + " correct = 0\n", + " for j in range(nsamples):\n", + " x = train_image[j].reshape(bok, bok)\n", + " y = one_hot_label[j]\n", + " for i in range(16):\n", + " new_row = convulsion(x, kernel[i], 1, 0)\n", + " new_row_flat = new_row.flatten()\n", + " output[i, :] = new_row_flat\n", + "\n", + " output = ReLu(output)\n", + " output_flat = output.flatten()\n", + "\n", + " # teraz trzeba pomnozyc wektor przez dense layer.\n", + " raw = np.dot(output_flat, W)\n", + "\n", + " if np.argmax(raw) == train_image_labels[j]:\n", + " correct += 1\n", + "\n", + " # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.\n", + " delta = (2 * 1 / 10) * (raw - y)\n", + " weight_delta = np.outer(output_flat, delta)\n", + "\n", + " conv_raw = np.dot(delta, W.T).reshape((16, 26, 26))\n", + " delta_relu = conv_raw * ReLu_deriv(output.reshape((16, 26, 26)))\n", + " W = W - alpha * weight_delta\n", + "\n", + " for i in range(16):\n", + " kernel_delta = convulsion(x, delta_relu[i], 1, 0)\n", + " kernel[i] = kernel[i] - alpha * kernel_delta\n", + "\n", + " if (b + 1) % 10 == 0 or b == 0:\n", + " print(f\"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%\")" + ], + "id": "520f7f91381cfe00", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Epoka 1/50 - Skutecznosc treningowa: 73.07%\n", + "Epoka 10/50 - Skutecznosc treningowa: 94.44%\n", + "Epoka 20/50 - Skutecznosc treningowa: 95.94%\n", + "Epoka 30/50 - Skutecznosc treningowa: 96.56%\n", + "Epoka 40/50 - Skutecznosc treningowa: 96.89%\n", + "Epoka 50/50 - Skutecznosc treningowa: 97.25%\n" + ] + } + ], + "execution_count": 36 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-23T20:44:40.362030155Z", + "start_time": "2026-11-23T20:44:20.872674386Z" + } + }, + "cell_type": "code", + "source": [ + "test_image = load_mnist_images('t10k-images.idx3-ubyte')\n", + "test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')\n", + "\n", + "pred = 0\n", + "test_output = np.zeros((16, 676))\n", + "\n", + "for i in range(nsamples):\n", + " x = test_image[i].reshape(bok, bok)\n", + "\n", + " for k in range(16):\n", + " new_row = convulsion(x, kernel[k], 1, 0)\n", + " test_output[k, :] = new_row.flatten()\n", + "\n", + " test_output_relu = ReLu(test_output)\n", + " raw = np.dot(test_output_relu.flatten(), W)\n", + "\n", + " przewidziana_cyfra = np.argmax(raw)\n", + " prawdziwa_cyfra = test_image_labels[i]\n", + "\n", + " if przewidziana_cyfra == prawdziwa_cyfra:\n", + " pred += 1\n", + "\n", + "proc = (pred / nsamples) * 100\n", + "print(f\"Skutecznosc: {proc:.2f}%\")\n" + ], + "id": "981a56b3d6aeffdb", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Skutecznosc: 95.85%\n" + ] + } + ], + "execution_count": 37 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### 60000 obrazow, a= 0.01, 50 iteracji", + "id": "ab169a9340984ce4" + }, + { + "metadata": { + "ExecuteTime": { + "start_time": "2026-11-23T20:44:40.366187038Z" + } + }, + "cell_type": "code", + "source": [ + "# 1 Warstwa konwulcyjna, z 16 filtrami 3x3 10 neuronow w wartswie wyjsciowej, ReLu\n", + "\n", + "kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]\n", + "\n", + "train_image = load_mnist_images('train-images.idx3-ubyte')\n", + "train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')\n", + "\n", + "# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy\n", + "\n", + "output = np.zeros((16, 676))\n", + "W = np.random.uniform(-0.1, 0.1, (10816, 10))\n", + "\n", + "bok = int(np.sqrt(train_image[0].size))\n", + "alpha = 0.01\n", + "nsamples = 60000\n", + "epochs = 50\n", + "\n", + "one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]\n", + "\n", + "for b in range(epochs):\n", + " correct = 0\n", + " for j in range(nsamples):\n", + " x = train_image[j].reshape(bok, bok)\n", + " y = one_hot_label[j]\n", + " for i in range(16):\n", + " new_row = convulsion(x, kernel[i], 1, 0)\n", + " new_row_flat = new_row.flatten()\n", + " output[i, :] = new_row_flat\n", + "\n", + " output = ReLu(output)\n", + " output_flat = output.flatten()\n", + "\n", + " # teraz trzeba pomnozyc wektor przez dense layer.\n", + " raw = np.dot(output_flat, W)\n", + "\n", + " if np.argmax(raw) == train_image_labels[j]:\n", + " correct += 1\n", + "\n", + " # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.\n", + " delta = (2 * 1 / 10) * (raw - y)\n", + " weight_delta = np.outer(output_flat, delta)\n", + "\n", + " conv_raw = np.dot(delta, W.T).reshape((16, 26, 26))\n", + " delta_relu = conv_raw * ReLu_deriv(output.reshape((16, 26, 26)))\n", + " W = W - alpha * weight_delta\n", + "\n", + " for i in range(16):\n", + " kernel_delta = convulsion(x, delta_relu[i], 1, 0)\n", + " kernel[i] = kernel[i] - alpha * kernel_delta\n", + "\n", + " if (b + 1) % 10 == 0 or b == 0:\n", + " print(f\"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%\")" + ], + "id": "306fd239dcdbad1b", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Epoka 1/50 - Skutecznosc treningowa: 86.16%\n", + "Epoka 10/50 - Skutecznosc treningowa: 96.37%\n", + "Epoka 20/50 - Skutecznosc treningowa: 96.97%\n", + "Epoka 30/50 - Skutecznosc treningowa: 97.26%\n" + ] + } + ], + "execution_count": null + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T13:10:39.992577156Z", + "start_time": "2026-11-24T13:10:39.827599985Z" + } + }, + "cell_type": "code", + "source": [ + "test_image = load_mnist_images('t10k-images.idx3-ubyte')\n", + "test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')\n", + "\n", + "pred = 0\n", + "test_output = np.zeros((16, 676))\n", + "\n", + "for i in range(nsamples):\n", + " x = test_image[i].reshape(bok, bok)\n", + "\n", + " for k in range(16):\n", + " new_row = convulsion(x, kernel[k], 1, 0)\n", + " test_output[k, :] = new_row.flatten()\n", + "\n", + " test_output_relu = ReLu(test_output)\n", + " raw = np.dot(test_output_relu.flatten(), W)\n", + "\n", + " przewidziana_cyfra = np.argmax(raw)\n", + " prawdziwa_cyfra = test_image_labels[i]\n", + "\n", + " if przewidziana_cyfra == prawdziwa_cyfra:\n", + " pred += 1\n", + "\n", + "proc = (pred / nsamples) * 100\n", + "print(f\"Skutecznosc: {proc:.2f}%\")\n" + ], + "id": "7129ad6cf3a6eacc", + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'nsamples' is not defined", + "output_type": "error", + "traceback": [ + "\u001B[31m---------------------------------------------------------------------------\u001B[39m", + "\u001B[31mNameError\u001B[39m Traceback (most recent call last)", + "\u001B[36mCell\u001B[39m\u001B[36m \u001B[39m\u001B[32mIn[7]\u001B[39m\u001B[32m, line 7\u001B[39m\n\u001B[32m 3\u001B[39m \n\u001B[32m 4\u001B[39m pred = \u001B[32m0\u001B[39m\n\u001B[32m 5\u001B[39m test_output = np.zeros((\u001B[32m16\u001B[39m, \u001B[32m676\u001B[39m))\n\u001B[32m 6\u001B[39m \n\u001B[32m----> \u001B[39m\u001B[32m7\u001B[39m \u001B[38;5;28;01mfor\u001B[39;00m i \u001B[38;5;28;01min\u001B[39;00m range(nsamples):\n\u001B[32m 8\u001B[39m x = test_image[i].reshape(bok, bok)\n\u001B[32m 9\u001B[39m \n\u001B[32m 10\u001B[39m \u001B[38;5;28;01mfor\u001B[39;00m k \u001B[38;5;28;01min\u001B[39;00m range(\u001B[32m16\u001B[39m):\n", + "\u001B[31mNameError\u001B[39m: name 'nsamples' is not defined" + ] + } + ], + "execution_count": 7 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "## Zadanie 3", + "id": "e2becffbaa79b2a5" + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### 1000 obrazow, a= 0.001, 300 iteracji", + "id": "1e3bcf9e8c036c7c" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T16:57:02.602251717Z", + "start_time": "2026-11-24T16:57:02.566849987Z" + } + }, + "cell_type": "code", + "source": [ + "def max_pooling(image, step=2):\n", + " windows = sliding_window_view(image, (2, 2), axis=(-2, -1))[:, ::step, ::step] # 16 x 26 x 26 x 2 x 2 // step\n", + " mask = (windows == np.max(windows, axis=(-2, -1),\n", + " keepdims=True)) # Maska jest o wymirach 16 x 13 x 13 x 2 x 2 a musi byc 16 x 26 x 26\n", + " mask = (mask.transpose(0, 1, 3, 2, 4)).reshape(16, 26, 26)\n", + " return np.max(windows, axis=(-2, -1)), mask" + ], + "id": "2a830e9b9fafa608", + "outputs": [], + "execution_count": 8 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T15:35:57.057858477Z", + "start_time": "2026-11-24T15:23:30.342135069Z" + } + }, + "cell_type": "code", + "source": [ + "# 1 Warstwa konwulcyjna, z 16 filtrami 3x3 10 neuronow w wartswie wyjsciowej, ReLu\n", + "\n", + "kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]\n", + "\n", + "train_image = load_mnist_images('train-images.idx3-ubyte')\n", + "train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')\n", + "\n", + "# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy\n", + "\n", + "output = np.zeros((16, 676))\n", + "W = np.random.uniform(-0.1, 0.1, (2704, 10))\n", + "\n", + "bok = int(np.sqrt(train_image[0].size))\n", + "alpha = 0.001\n", + "nsamples = 1000\n", + "epochs = 300\n", + "\n", + "one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]\n", + "\n", + "for b in range(epochs):\n", + " correct = 0\n", + " for j in range(nsamples):\n", + " x = train_image[j].reshape(bok, bok)\n", + " y = one_hot_label[j]\n", + " for i in range(16):\n", + " new_row = convulsion(x, kernel[i], 1, 0)\n", + " new_row_flat = new_row.flatten()\n", + " output[i, :] = new_row_flat\n", + "\n", + " output = ReLu(output)\n", + " output_2d = output.reshape(16, 26, 26)\n", + "\n", + " # Teraz trzeba zrobic pool, a w wstecznej wziasc pod uwage maske\n", + " pool, mask = max_pooling(output_2d)\n", + "\n", + " pool_flat = pool.flatten()\n", + "\n", + " # teraz trzeba pomnozyc wektor przez dense layer.\n", + " raw = np.dot(pool_flat, W)\n", + "\n", + " if np.argmax(raw) == train_image_labels[j]:\n", + " correct += 1\n", + "\n", + " # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.\n", + " delta = (2 * 1 / 10) * (raw - y)\n", + " weight_delta = np.outer(pool_flat, delta)\n", + "\n", + " conv_raw = np.dot(delta, W.T).reshape((16, 13, 13))\n", + "\n", + " # Max pool backprop\n", + " back_pool = np.repeat(np.repeat(conv_raw, 2, axis=1), 2, axis=2)\n", + "\n", + " delta_relu = back_pool * mask * ReLu_deriv(output.reshape((16, 26, 26)))\n", + " W = W - alpha * weight_delta\n", + "\n", + " for i in range(16):\n", + " kernel_delta = convulsion(x, delta_relu[i], 1, 0)\n", + " kernel[i] = kernel[i] - alpha * kernel_delta\n", + "\n", + " if (b + 1) % 10 == 0 or b == 0:\n", + " print(f\"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%\")" + ], + "id": "b392b2ce13d4e498", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Epoka 1/300 - Skutecznosc treningowa: 13.20%\n", + "Epoka 10/300 - Skutecznosc treningowa: 54.50%\n", + "Epoka 20/300 - Skutecznosc treningowa: 73.80%\n", + "Epoka 30/300 - Skutecznosc treningowa: 80.00%\n", + "Epoka 40/300 - Skutecznosc treningowa: 82.60%\n", + "Epoka 50/300 - Skutecznosc treningowa: 85.10%\n", + "Epoka 60/300 - Skutecznosc treningowa: 86.70%\n", + "Epoka 70/300 - Skutecznosc treningowa: 87.50%\n", + "Epoka 80/300 - Skutecznosc treningowa: 88.00%\n", + "Epoka 90/300 - Skutecznosc treningowa: 88.70%\n", + "Epoka 100/300 - Skutecznosc treningowa: 89.00%\n", + "Epoka 110/300 - Skutecznosc treningowa: 89.20%\n", + "Epoka 120/300 - Skutecznosc treningowa: 89.90%\n", + "Epoka 130/300 - Skutecznosc treningowa: 90.70%\n", + "Epoka 140/300 - Skutecznosc treningowa: 91.30%\n", + "Epoka 150/300 - Skutecznosc treningowa: 91.80%\n", + "Epoka 160/300 - Skutecznosc treningowa: 91.80%\n", + "Epoka 170/300 - Skutecznosc treningowa: 92.10%\n", + "Epoka 180/300 - Skutecznosc treningowa: 92.40%\n", + "Epoka 190/300 - Skutecznosc treningowa: 92.90%\n", + "Epoka 200/300 - Skutecznosc treningowa: 93.00%\n", + "Epoka 210/300 - Skutecznosc treningowa: 93.30%\n", + "Epoka 220/300 - Skutecznosc treningowa: 93.50%\n", + "Epoka 230/300 - Skutecznosc treningowa: 93.50%\n", + "Epoka 240/300 - Skutecznosc treningowa: 93.60%\n", + "Epoka 250/300 - Skutecznosc treningowa: 93.90%\n", + "Epoka 260/300 - Skutecznosc treningowa: 94.20%\n", + "Epoka 270/300 - Skutecznosc treningowa: 94.40%\n", + "Epoka 280/300 - Skutecznosc treningowa: 94.60%\n", + "Epoka 290/300 - Skutecznosc treningowa: 94.60%\n", + "Epoka 300/300 - Skutecznosc treningowa: 94.80%\n" + ] + } + ], + "execution_count": 71 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T15:37:19.743760825Z", + "start_time": "2026-11-24T15:36:56.677036524Z" + } + }, + "cell_type": "code", + "source": [ + "test_image = load_mnist_images('t10k-images.idx3-ubyte')\n", + "test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')\n", + "\n", + "pred = 0\n", + "test_output = np.zeros((16, 676))\n", + "\n", + "for i in range(10000):\n", + " x = test_image[i].reshape(bok, bok)\n", + "\n", + " for k in range(16):\n", + " new_row = convulsion(x, kernel[k], 1, 0)\n", + " test_output[k, :] = new_row.flatten()\n", + "\n", + " test_output_relu = ReLu(test_output)\n", + "\n", + " output_2d = test_output_relu.reshape(16, 26, 26)\n", + "\n", + " pool, mask = max_pooling(output_2d)\n", + "\n", + " pool_flat = pool.flatten()\n", + "\n", + " raw = np.dot(pool_flat, W)\n", + "\n", + " przewidziana_cyfra = np.argmax(raw)\n", + " prawdziwa_cyfra = test_image_labels[i]\n", + "\n", + " if przewidziana_cyfra == prawdziwa_cyfra:\n", + " pred += 1\n", + "\n", + "proc = (pred / 10000) * 100\n", + "print(f\"Skutecznosc: {proc:.2f}%\")" + ], + "id": "f57c90de0b4901ea", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Skutecznosc: 89.64%\n" + ] + } + ], + "execution_count": 74 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### 10000 obrazow, a= 0.001, 300 iteracji", + "id": "a3f021bb3884cdc" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T21:43:01.460616351Z", + "start_time": "2026-11-24T19:37:50.523207801Z" + } + }, + "cell_type": "code", + "source": [ + "# 1 Warstwa konwulcyjna, z 16 filtrami 3x3 10 neuronow w wartswie wyjsciowej, ReLu\n", + "\n", + "kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]\n", + "\n", + "train_image = load_mnist_images('train-images.idx3-ubyte')\n", + "train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')\n", + "\n", + "# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy\n", + "\n", + "output = np.zeros((16, 676))\n", + "W = np.random.uniform(-0.1, 0.1, (2704, 10))\n", + "\n", + "bok = int(np.sqrt(train_image[0].size))\n", + "alpha = 0.001\n", + "nsamples = 10000\n", + "epochs = 300\n", + "\n", + "one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]\n", + "\n", + "for b in range(epochs):\n", + " correct = 0\n", + " for j in range(nsamples):\n", + " x = train_image[j].reshape(bok, bok)\n", + " y = one_hot_label[j]\n", + " for i in range(16):\n", + " new_row = convulsion(x, kernel[i], 1, 0)\n", + " new_row_flat = new_row.flatten()\n", + " output[i, :] = new_row_flat\n", + "\n", + " output = ReLu(output)\n", + " output_2d = output.reshape(16, 26, 26)\n", + "\n", + " # Teraz trzeba zrobic pool, a w wstecznej wziasc pod uwage maske\n", + " pool, mask = max_pooling(output_2d)\n", + "\n", + " pool_flat = pool.flatten()\n", + "\n", + " # teraz trzeba pomnozyc wektor przez dense layer.\n", + " raw = np.dot(pool_flat, W)\n", + "\n", + " if np.argmax(raw) == train_image_labels[j]:\n", + " correct += 1\n", + "\n", + " # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.\n", + " delta = (2 * 1 / 10) * (raw - y)\n", + " weight_delta = np.outer(pool_flat, delta)\n", + "\n", + " conv_raw = np.dot(delta, W.T).reshape((16, 13, 13))\n", + "\n", + " # Max pool backprop\n", + " back_pool = np.repeat(np.repeat(conv_raw, 2, axis=1), 2, axis=2)\n", + "\n", + " delta_relu = back_pool * mask * ReLu_deriv(output.reshape((16, 26, 26)))\n", + " W = W - alpha * weight_delta\n", + "\n", + " for i in range(16):\n", + " kernel_delta = convulsion(x, delta_relu[i], 1, 0)\n", + " kernel[i] = kernel[i] - alpha * kernel_delta\n", + "\n", + " if (b + 1) % 10 == 0 or b == 0:\n", + " print(f\"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%\")" + ], + "id": "a9ff04d82be93728", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Epoka 1/300 - Skutecznosc treningowa: 34.59%\n", + "Epoka 10/300 - Skutecznosc treningowa: 86.54%\n", + "Epoka 20/300 - Skutecznosc treningowa: 89.63%\n", + "Epoka 30/300 - Skutecznosc treningowa: 91.55%\n", + "Epoka 40/300 - Skutecznosc treningowa: 92.70%\n", + "Epoka 50/300 - Skutecznosc treningowa: 93.43%\n", + "Epoka 60/300 - Skutecznosc treningowa: 93.91%\n", + "Epoka 70/300 - Skutecznosc treningowa: 94.35%\n", + "Epoka 80/300 - Skutecznosc treningowa: 94.75%\n", + "Epoka 90/300 - Skutecznosc treningowa: 95.07%\n", + "Epoka 100/300 - Skutecznosc treningowa: 95.25%\n", + "Epoka 110/300 - Skutecznosc treningowa: 95.43%\n", + "Epoka 120/300 - Skutecznosc treningowa: 95.56%\n", + "Epoka 130/300 - Skutecznosc treningowa: 95.69%\n", + "Epoka 140/300 - Skutecznosc treningowa: 95.80%\n", + "Epoka 150/300 - Skutecznosc treningowa: 95.99%\n", + "Epoka 160/300 - Skutecznosc treningowa: 96.04%\n", + "Epoka 170/300 - Skutecznosc treningowa: 96.15%\n", + "Epoka 180/300 - Skutecznosc treningowa: 96.24%\n", + "Epoka 190/300 - Skutecznosc treningowa: 96.37%\n", + "Epoka 200/300 - Skutecznosc treningowa: 96.49%\n", + "Epoka 210/300 - Skutecznosc treningowa: 96.52%\n", + "Epoka 220/300 - Skutecznosc treningowa: 96.60%\n", + "Epoka 230/300 - Skutecznosc treningowa: 96.66%\n", + "Epoka 240/300 - Skutecznosc treningowa: 96.71%\n", + "Epoka 250/300 - Skutecznosc treningowa: 96.76%\n", + "Epoka 260/300 - Skutecznosc treningowa: 96.81%\n", + "Epoka 270/300 - Skutecznosc treningowa: 96.85%\n", + "Epoka 280/300 - Skutecznosc treningowa: 96.92%\n", + "Epoka 290/300 - Skutecznosc treningowa: 96.97%\n", + "Epoka 300/300 - Skutecznosc treningowa: 97.00%\n" + ] + } + ], + "execution_count": 11 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T22:31:04.765769205Z", + "start_time": "2026-11-24T22:30:49.293707571Z" + } + }, + "cell_type": "code", + "source": [ + "test_image = load_mnist_images('t10k-images.idx3-ubyte')\n", + "test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')\n", + "\n", + "pred = 0\n", + "test_output = np.zeros((16, 676))\n", + "\n", + "for i in range(10000):\n", + " x = test_image[i].reshape(bok, bok)\n", + "\n", + " for k in range(16):\n", + " new_row = convulsion(x, kernel[k], 1, 0)\n", + " test_output[k, :] = new_row.flatten()\n", + "\n", + " test_output_relu = ReLu(test_output)\n", + "\n", + " output_2d = test_output_relu.reshape(16, 26, 26)\n", + "\n", + " pool, mask = max_pooling(output_2d)\n", + "\n", + " pool_flat = pool.flatten()\n", + "\n", + " raw = np.dot(pool_flat, W)\n", + "\n", + " przewidziana_cyfra = np.argmax(raw)\n", + " prawdziwa_cyfra = test_image_labels[i]\n", + "\n", + " if przewidziana_cyfra == prawdziwa_cyfra:\n", + " pred += 1\n", + "\n", + "proc = (pred / 10000) * 100\n", + "print(f\"Skutecznosc: {proc:.2f}%\")" + ], + "id": "e3757e578533f176", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Skutecznosc: 95.96%\n" + ] + } + ], + "execution_count": 13 + }, + { + "metadata": {}, + "cell_type": "markdown", + "source": "### 60000 obrazow, a= 0.01, 50 iteracji\n", + "id": "b4f9b5c94ac0aa30" + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T19:00:01.751889159Z", + "start_time": "2026-11-24T16:57:09.012273819Z" + } + }, + "cell_type": "code", + "source": [ + "# 1 Warstwa konwulcyjna, z 16 filtrami 3x3 10 neuronow w wartswie wyjsciowej, ReLu\n", + "\n", + "kernel = [np.random.uniform(-0.01, 0.01, (3, 3)) for x in range(16)]\n", + "\n", + "train_image = load_mnist_images('train-images.idx3-ubyte')\n", + "train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')\n", + "\n", + "# Biore obraz, robie na nim convulsion na kazdym z filtrow, kazdy z nich splaszczam do postaci wektora i zmienam w wiersz w nowej macierzy\n", + "\n", + "output = np.zeros((16, 676))\n", + "W = np.random.uniform(-0.1, 0.1, (2704, 10))\n", + "\n", + "bok = int(np.sqrt(train_image[0].size))\n", + "alpha = 0.01\n", + "nsamples = 60000\n", + "epochs = 50\n", + "\n", + "one_hot_label = [to_one_hot(train_image_labels[x]).flatten() for x in range(nsamples)]\n", + "\n", + "for b in range(epochs):\n", + " correct = 0\n", + " for j in range(nsamples):\n", + " x = train_image[j].reshape(bok, bok)\n", + " y = one_hot_label[j]\n", + " for i in range(16):\n", + " new_row = convulsion(x, kernel[i], 1, 0)\n", + " new_row_flat = new_row.flatten()\n", + " output[i, :] = new_row_flat\n", + "\n", + " output = ReLu(output)\n", + " output_2d = output.reshape(16, 26, 26)\n", + "\n", + " # Teraz trzeba zrobic pool, a w wstecznej wziasc pod uwage maske\n", + " pool, mask = max_pooling(output_2d)\n", + "\n", + " pool_flat = pool.flatten()\n", + "\n", + " # teraz trzeba pomnozyc wektor przez dense layer.\n", + " raw = np.dot(pool_flat, W)\n", + "\n", + " if np.argmax(raw) == train_image_labels[j]:\n", + " correct += 1\n", + "\n", + " # Teraz trzeba policzcy gradient i na jego pdstawie zrobic propagacje.\n", + " delta = (2 * 1 / 10) * (raw - y)\n", + " weight_delta = np.outer(pool_flat, delta)\n", + "\n", + " conv_raw = np.dot(delta, W.T).reshape((16, 13, 13))\n", + "\n", + " # Max pool backprop\n", + " back_pool = np.repeat(np.repeat(conv_raw, 2, axis=1), 2, axis=2)\n", + "\n", + " delta_relu = back_pool * mask * ReLu_deriv(output.reshape((16, 26, 26)))\n", + " W = W - alpha * weight_delta\n", + "\n", + " for i in range(16):\n", + " kernel_delta = convulsion(x, delta_relu[i], 1, 0)\n", + " kernel[i] = kernel[i] - alpha * kernel_delta\n", + "\n", + " if (b + 1) % 10 == 0 or b == 0:\n", + " print(f\"Epoka {b + 1}/{epochs} - Skutecznosc treningowa: {(correct / nsamples) * 100:.2f}%\")" + ], + "id": "6055a656fa8399ba", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Epoka 1/50 - Skutecznosc treningowa: 88.65%\n", + "Epoka 10/50 - Skutecznosc treningowa: 96.88%\n", + "Epoka 20/50 - Skutecznosc treningowa: 97.37%\n", + "Epoka 30/50 - Skutecznosc treningowa: 97.56%\n", + "Epoka 40/50 - Skutecznosc treningowa: 97.66%\n", + "Epoka 50/50 - Skutecznosc treningowa: 97.74%\n" + ] + } + ], + "execution_count": 9 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-11-24T19:37:39.980237166Z", + "start_time": "2026-11-24T19:37:24.212619007Z" + } + }, + "cell_type": "code", + "source": [ + "test_image = load_mnist_images('t10k-images.idx3-ubyte')\n", + "test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')\n", + "\n", + "pred = 0\n", + "test_output = np.zeros((16, 676))\n", + "\n", + "for i in range(10000):\n", + " x = test_image[i].reshape(bok, bok)\n", + "\n", + " for k in range(16):\n", + " new_row = convulsion(x, kernel[k], 1, 0)\n", + " test_output[k, :] = new_row.flatten()\n", + "\n", + " test_output_relu = ReLu(test_output)\n", + "\n", + " output_2d = test_output_relu.reshape(16, 26, 26)\n", + "\n", + " pool, mask = max_pooling(output_2d)\n", + "\n", + " pool_flat = pool.flatten()\n", + "\n", + " raw = np.dot(pool_flat, W)\n", + "\n", + " przewidziana_cyfra = np.argmax(raw)\n", + " prawdziwa_cyfra = test_image_labels[i]\n", + "\n", + " if przewidziana_cyfra == prawdziwa_cyfra:\n", + " pred += 1\n", + "\n", + "proc = (pred / 10000) * 100\n", + "print(f\"Skutecznosc: {proc:.2f}%\")" + ], + "id": "f64a32c7b8d70a54", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Skutecznosc: 97.49%\n" + ] + } + ], + "execution_count": 10 + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/t10k-images.idx3-ubyte b/t10k-images.idx3-ubyte new file mode 100644 index 0000000..1170b2c Binary files /dev/null and b/t10k-images.idx3-ubyte differ diff --git a/t10k-labels.idx1-ubyte b/t10k-labels.idx1-ubyte new file mode 100644 index 0000000..d1c3a97 Binary files /dev/null and b/t10k-labels.idx1-ubyte differ diff --git a/test_colors.txt b/test_colors.txt new file mode 100644 index 0000000..46f12e1 --- /dev/null +++ b/test_colors.txt @@ -0,0 +1,130 @@ +0.84 0.93 0.28 4 +0.14 0.88 0.12 2 +0.16 0.03 0.88 3 +0.08 0.89 0.30 2 +0.85 0.39 0.09 1 +0.26 0.19 0.88 3 +0.91 0.18 0.05 1 +0.14 0.07 0.94 3 +0.93 0.88 0.06 4 +0.19 0.14 0.92 3 +0.13 0.05 0.90 3 +0.17 0.15 0.80 3 +0.87 0.84 0.09 4 +0.01 0.05 0.86 3 +0.81 0.13 0.27 1 +0.87 0.92 0.28 4 +0.04 0.31 0.83 3 +0.42 0.21 0.88 3 +0.86 0.20 0.46 1 +0.84 0.88 0.37 4 +0.00 0.95 0.32 2 +0.12 0.00 0.93 3 +0.85 0.86 0.25 4 +0.87 0.14 0.05 1 +0.83 0.21 0.26 1 +0.87 0.85 0.19 4 +0.08 0.00 0.86 3 +0.11 0.06 0.89 3 +1.01 0.97 0.15 4 +0.89 0.20 0.02 1 +0.90 0.97 0.24 4 +0.18 0.07 0.82 3 +0.87 0.25 0.03 1 +0.22 0.95 0.20 2 +0.90 0.90 0.08 4 +0.94 0.20 0.23 1 +0.88 0.99 0.07 4 +0.09 0.19 0.95 3 +0.97 0.04 0.04 1 +0.84 0.91 0.26 4 +0.83 0.87 0.12 4 +0.97 0.95 0.04 4 +0.09 0.03 0.92 3 +0.12 0.85 0.18 2 +0.97 0.08 0.16 1 +0.91 0.91 0.14 4 +0.84 0.95 0.05 4 +0.90 0.22 0.27 1 +0.00 0.99 0.25 2 +0.21 0.96 0.19 2 +0.95 0.89 0.16 4 +0.19 0.92 0.17 2 +0.19 0.88 0.04 2 +0.10 0.93 0.00 2 +0.27 0.11 0.94 3 +0.85 0.14 0.24 1 +0.92 0.09 0.24 1 +0.90 0.09 0.35 1 +0.11 0.96 0.13 2 +0.27 0.76 0.12 2 +0.15 0.81 0.26 2 +0.89 0.94 0.18 4 +0.96 0.88 0.11 4 +0.25 0.90 0.03 2 +0.95 0.82 0.27 4 +0.88 0.96 0.12 4 +0.88 0.22 0.17 1 +1.02 0.08 0.24 1 +0.09 0.92 0.07 2 +0.95 0.19 0.37 1 +0.94 0.28 0.15 1 +1.03 0.96 0.23 4 +0.01 0.90 0.14 2 +0.00 0.00 0.91 3 +0.88 0.94 0.27 4 +0.90 0.86 0.17 4 +0.28 0.18 0.86 3 +0.00 0.27 0.89 3 +0.91 0.90 0.04 4 +0.18 0.11 0.95 3 +0.24 0.88 0.18 2 +0.96 0.90 0.00 4 +0.03 0.00 0.90 3 +0.92 0.15 0.33 1 +0.90 0.92 0.29 4 +0.94 0.04 0.16 1 +0.18 0.88 0.16 2 +0.88 0.90 0.11 4 +0.12 0.17 0.86 3 +0.17 0.19 1.04 3 +0.87 0.19 0.40 1 +0.16 0.90 0.26 2 +0.31 0.20 0.95 3 +0.90 0.22 0.19 1 +0.18 1.01 0.18 2 +0.00 0.93 0.15 2 +0.26 0.88 0.26 2 +0.95 0.88 0.19 4 +0.29 0.91 0.17 2 +0.32 0.23 0.91 3 +0.92 0.17 0.07 1 +0.11 0.00 0.91 3 +0.26 0.83 0.11 2 +0.87 0.02 0.19 1 +0.31 0.24 0.90 3 +0.03 0.92 0.26 2 +0.96 0.04 0.25 1 +0.87 0.01 0.00 1 +0.20 0.02 0.93 3 +0.10 0.16 0.95 3 +0.91 0.89 0.11 4 +0.12 0.27 0.92 3 +0.15 0.88 0.20 2 +0.88 0.32 0.15 1 +0.07 0.81 0.00 2 +0.10 0.17 0.92 3 +0.88 0.93 0.19 4 +0.07 0.24 0.88 3 +0.24 0.10 0.82 3 +0.90 0.14 0.35 1 +0.97 0.89 0.26 4 +0.29 0.93 0.14 2 +0.89 0.05 0.00 1 +0.84 0.30 0.14 1 +0.02 0.12 0.92 3 +0.96 0.23 0.23 1 +0.23 0.36 0.87 3 +0.98 0.49 0.18 1 +0.94 0.00 0.08 1 +0.90 0.78 0.37 4 \ No newline at end of file diff --git a/train-images.idx3-ubyte b/train-images.idx3-ubyte new file mode 100644 index 0000000..bbce276 Binary files /dev/null and b/train-images.idx3-ubyte differ diff --git a/train-labels.idx1-ubyte b/train-labels.idx1-ubyte new file mode 100644 index 0000000..d6b4c5d Binary files /dev/null and b/train-labels.idx1-ubyte differ diff --git a/training_colors.txt b/training_colors.txt new file mode 100644 index 0000000..74e7930 --- /dev/null +++ b/training_colors.txt @@ -0,0 +1,109 @@ +0.91 0.82 0.05 4 +0.91 0.09 0.26 1 +0.89 0.90 0.18 4 +0.82 0.04 0.08 1 +0.19 0.91 0.00 2 +0.20 0.17 0.90 3 +0.10 0.97 0.00 2 +0.22 0.97 0.03 2 +0.20 0.20 0.89 3 +0.03 0.97 0.21 2 +0.92 0.28 0.26 1 +0.00 0.10 0.86 3 +0.12 0.17 0.91 3 +0.94 0.15 0.06 1 +0.81 0.25 0.09 1 +0.00 0.04 0.88 3 +0.83 0.95 0.08 4 +0.84 0.93 0.06 4 +0.19 0.17 0.88 3 +0.03 0.21 0.93 3 +0.42 0.89 0.24 2 +0.15 0.25 0.90 3 +0.86 0.99 0.19 4 +0.29 0.86 0.10 2 +0.89 0.84 0.28 4 +0.82 0.08 0.13 1 +0.87 0.16 0.17 1 +0.25 0.37 0.85 3 +0.90 0.10 0.01 1 +0.08 0.03 0.87 3 +0.99 0.92 0.00 4 +0.88 0.89 0.28 4 +0.91 0.00 0.08 1 +0.01 0.24 0.95 3 +0.86 0.00 0.18 1 +0.89 0.12 0.21 1 +0.90 0.88 0.36 4 +0.22 0.25 0.90 3 +0.30 0.95 0.16 2 +0.19 0.00 0.85 3 +0.09 0.02 0.95 3 +0.88 0.82 0.08 4 +0.91 0.15 0.04 1 +0.95 0.85 0.07 4 +0.34 0.88 0.22 2 +0.88 0.89 0.28 4 +0.87 0.18 0.22 1 +0.83 0.92 0.11 4 +0.86 0.34 0.00 1 +0.00 0.25 0.92 3 +0.81 0.24 0.20 1 +0.27 0.89 0.07 2 +0.98 0.16 0.27 1 +0.90 0.28 0.05 1 +0.23 0.28 0.90 3 +0.17 0.08 0.93 3 +0.88 0.90 0.18 4 +0.95 0.93 0.00 4 +0.12 0.10 0.82 3 +0.03 0.86 0.19 2 +0.93 0.26 0.29 1 +0.99 0.91 0.01 4 +0.16 0.14 0.89 3 +0.93 0.24 0.24 1 +0.92 0.91 0.00 4 +0.91 0.22 0.26 1 +0.11 0.79 0.12 2 +0.91 0.14 0.02 1 +0.37 0.98 0.25 2 +0.14 0.86 0.16 2 +0.91 0.18 0.30 1 +0.93 0.20 0.08 1 +0.99 0.87 0.09 4 +0.13 0.90 0.20 2 +0.90 0.29 0.03 1 +0.77 0.00 0.25 1 +0.15 0.17 0.89 3 +0.85 0.18 0.10 1 +0.14 0.85 0.17 2 +0.21 0.21 0.90 3 +0.11 0.90 0.00 2 +0.89 0.84 0.18 4 +0.01 0.30 0.85 3 +0.21 0.94 0.13 2 +0.14 0.94 0.08 2 +0.86 0.89 0.21 4 +0.06 0.20 0.95 3 +0.86 0.78 0.26 4 +0.19 1.00 0.21 2 +0.21 0.09 0.89 3 +0.86 0.93 0.22 4 +0.08 0.83 0.21 2 +0.26 0.87 0.12 2 +0.84 0.13 0.17 1 +0.90 0.28 0.16 1 +0.82 0.97 0.12 4 +0.11 0.95 0.13 2 +0.94 0.94 0.16 4 +0.17 0.86 0.11 2 +0.91 0.89 0.01 4 +0.94 0.90 0.18 4 +0.00 0.83 0.21 2 +0.18 0.87 0.27 2 +0.90 0.26 0.09 1 +0.14 0.90 0.04 2 +0.86 0.20 0.00 1 +0.09 0.12 0.87 3 +0.97 0.02 0.13 1 +0.91 0.19 0.14 1 \ No newline at end of file