{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Įsidiekite programinę įrangą\n",
    "import imageio.v3 as imageio\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas\n",
    "import sklearn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2.1. Veiksmai su matricomis\n",
    "# Pamėginkite įsivesti naujas matricas ir atlikti veiksmus su jomis.\n",
    "\n",
    "A = np.array([[1, 2], [3, 4]])\n",
    "B = np.array([[1, 2], [3, 4]])\n",
    "\n",
    "C = A + B\n",
    "D = A * B\n",
    "E = np.matmul(A,B)\n",
    "\n",
    "print(\"C=\", C)\n",
    "print(\"D=\", D)\n",
    "print(\"E=\", E)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2.2. MSE skaičiavimas\n",
    "# Išanalizuokite žemiau pateikta MSE skaičiavimo pavyzdį.\n",
    "\n",
    "x = np.arange(0, 5.0, 0.1)\n",
    "y = np.sin(x)\n",
    "y2 = y + np.random.normal(0,0.1,len(y))\n",
    "\n",
    "plt.plot(x, y)\n",
    "plt.plot(x, y2)\n",
    "plt.show()\n",
    "\n",
    "MSE = (1/len(y))*np.sum(np.power((y-y2),2))\n",
    "\n",
    "print(\"MSE=\", MSE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2.3. Atlikite veiksmus su paveikslėliais\n",
    "# Pamėginkite pritaikyti įvarias numpy, ndimage ir matplotlib funkcijas paveikslėliams.\n",
    "\n",
    "ktu = imageio.imread('assets/ktu.png')\n",
    "new_ktu = np.full(ktu.shape, [0, 0, 0, 255])\n",
    "\n",
    "kernel_variant = 0\n",
    "if kernel_variant == 0:\n",
    "    # Edge detection\n",
    "    kernel_coef = 1\n",
    "    kernel = np.array([\n",
    "        [ 0, -1,  0],\n",
    "        [-1,  4, -1],\n",
    "        [ 0, -1,  0]\n",
    "    ])\n",
    "elif kernel_variant == 1:\n",
    "    # 3x3 Gaussian blur\n",
    "    kernel_coef = 1/16\n",
    "    kernel = np.array([\n",
    "        [1, 2, 1],\n",
    "        [2, 4, 2],\n",
    "        [1, 2, 1]\n",
    "    ])\n",
    "\n",
    "for y, row in enumerate(ktu):\n",
    "    for x, pixel in enumerate(row):\n",
    "        neighbour_sum = [0, 0, 0]\n",
    "        for dy, kernel_row in enumerate(kernel):\n",
    "            neighbour_y = y + dy - kernel.shape[0]//2\n",
    "            for dx, kernel_pixel_coeff in enumerate(kernel_row):\n",
    "                neighbour_x = x + dx - kernel.shape[1]//2\n",
    "\n",
    "                if 0 <= neighbour_x < ktu.shape[0] and 0 <= neighbour_y < ktu.shape[1]:\n",
    "                    neighbour_sum[0] += ktu[neighbour_y][neighbour_x][0] * kernel_pixel_coeff\n",
    "                    neighbour_sum[1] += ktu[neighbour_y][neighbour_x][1] * kernel_pixel_coeff\n",
    "                    neighbour_sum[2] += ktu[neighbour_y][neighbour_x][2] * kernel_pixel_coeff\n",
    "\n",
    "        new_ktu[y][x] = [\n",
    "            neighbour_sum[0] * kernel_coef,\n",
    "            neighbour_sum[1] * kernel_coef,\n",
    "            neighbour_sum[2] * kernel_coef,\n",
    "            255\n",
    "        ]\n",
    "\n",
    "plt.imshow(new_ktu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 46320 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 2.4. Išvestinių skaičiavimas\n",
    "# Pakeiskite žingsnio ir kitus parametrus.\n",
    "\n",
    "delta_x = 0.01\n",
    "\n",
    "x = np.arange(0, 5.0, delta_x)\n",
    "y = np.cos(x)+np.cos(6*x)\n",
    "\n",
    "dydx = np.diff(y)/delta_x\n",
    "\n",
    "plt.plot(x, y)\n",
    "plt.plot(x[1:]-delta_x/2, dydx)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 55728 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 2.5. Išvestinės skaičiavimas su np.gradient\n",
    "# * Kodėl dydx_numerical ir dydx_analytical reikšmės nesutampa?\n",
    "#   Ats.: Nes 'dydx_numerical' tiktais aproksimuoja, sources: https://numpy.org/doc/stable/reference/generated/numpy.gradient.html\n",
    "#         O 'dydx_analytical' yra tiksli formulė išvesta ranka\n",
    "#\n",
    "# * Pakeiskite y=f(x) funkciją ir braižomus parametrus.\n",
    "\n",
    "x = np.linspace(-5, 5, 30)\n",
    "dx = x[1]-x[0]\n",
    "\n",
    "y = np.sin(x)+np.cos(2*x)\n",
    "#y = np.tan(x)+1/(2*x)\n",
    "\n",
    "dydx_numerical = np.gradient(y, dx)\n",
    "dydx_analytical = np.cos(x)-2*np.sin(2*x)\n",
    "\n",
    "plt.plot(x, y)\n",
    "plt.plot(x, dydx_numerical)\n",
    "plt.plot(x, dydx_analytical)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.contour.QuadContourSet at 0x1ea68b5d410>"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 253892 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 2.6. Gradientinio lauko radimas\n",
    "# Išanalizuokite žemiau pateiktą kodą. Pamėginkite atvaizduoti kitas $z(x,y)$ funkcijas.\n",
    "\n",
    "feature_x = np.arange(-2, 2, 0.1)\n",
    "feature_y = np.arange(-2, 2, 0.1)\n",
    "\n",
    "x, y = np.meshgrid(feature_x, feature_y)\n",
    "\n",
    "#z = x * np.exp(-(x**2 + y**2))\n",
    "z = x * np.sin((x + y**2))\n",
    "\n",
    "u = 1*np.exp(-(x**2 + y**2))+x*np.exp(-(x**2 + y**2))*(-2*x)\n",
    "v = x*np.exp(-(x**2 + y**2))*(-2*y)\n",
    "\n",
    "norm = np.linalg.norm(np.array((u, v)), axis=0)\n",
    "u = u / norm\n",
    "v = v / norm\n",
    "\n",
    "fig, ax = plt.subplots(1, 1)\n",
    "ax.set_aspect(1)\n",
    "ax.quiver(x, y, u, v, units='xy', scale=10, color='gray')\n",
    "ax.contour(x, y, z, 10, cmap='jet')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "TensorFlow version: 2.15.0\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<matplotlib.image.AxesImage at 0x1ea78389b10>"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 9992 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 2.7. MNIST duomenų bazė\n",
    "# Pamėginkite išsiaiškinti duomenų tipą ir juos atvaizduoti.\n",
    "\n",
    "import tensorflow as tf\n",
    "print(\"TensorFlow version:\", tf.__version__)\n",
    "\n",
    "mnist = tf.keras.datasets.mnist\n",
    "\n",
    "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
    "x_train, x_test = x_train / 255.0, x_test / 255.0\n",
    "\n",
    "plt.imshow(x_train[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     A          B    C  D      E    F\n",
      "0  1.0 2013-01-02  1.0  3   test  foo\n",
      "1  1.0 2013-01-02  1.0  3  train  foo\n",
      "2  1.0 2013-01-02  1.0  3   test  foo\n",
      "3  1.0 2013-01-02  1.0  3  train  foo\n",
      "21                 Lower De Boom (21st Amendment Brewery)\n",
      "32                    Hop Crisis (21st Amendment Brewery)\n",
      "70             London Balling (Against the Grain Brewery)\n",
      "134                Quakertown Stout (Armadillo Ale Works)\n",
      "171     Devils Tramping Ground Tripel (Aviator Brewing...\n",
      "                              ...                        \n",
      "2279    Lee Hill Series Vol. 4 - Manhattan Style Rye A...\n",
      "2281    Lee Hill Series Vol. 3 - Barrel Aged Imperial ...\n",
      "2286    Upslope Imperial India Pale Ale (Upslope Brewi...\n",
      "2312                   Voodoo Love Child (Voodoo Brewery)\n",
      "2315                            Gran Met (Voodoo Brewery)\n",
      "Name: label, Length: 84, dtype: object\n"
     ]
    }
   ],
   "source": [
    "# 2.8. Pandas biblioteka\n",
    "# Išanalizuokite žemiau pateiktą kodą, pamėginkite rasti įvairių duomenų\n",
    "# rinkinių internete ir jiems pritaikyti žemiau esantį kodą. Atlikite duomenų filtravimą,\n",
    "# atvaizdavimą ir pritaikykite įvairiais Pandas bibliotekos funkcijas.\n",
    "#\n",
    "# https://pandas.pydata.org/docs/user_guide/10min.html\n",
    "\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "df1 = pd.DataFrame({\n",
    "    \"A\": 1.0,\n",
    "    \"B\": pd.Timestamp(\"20130102\"),\n",
    "    \"C\": pd.Series(1, index=list(range(4)), dtype=\"float32\"),\n",
    "    \"D\": np.array([3] * 4, dtype=\"int32\"),\n",
    "    \"E\": pd.Categorical([\"test\", \"train\", \"test\", \"train\"]),\n",
    "    \"F\": \"foo\",\n",
    "})\n",
    "\n",
    "print(df1)\n",
    "\n",
    "df2 = pd.read_csv('assets/beers.csv')\n",
    "\n",
    "print(df2[df2.abv>0.09].label)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Ice Cream Profits')"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 35364 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "df = pd.read_csv('assets/Ice Cream Sales - temperatures.csv')\n",
    "\n",
    "df.sort_values('Ice Cream Profits', ascending=False, inplace=True)\n",
    "\n",
    "plt.plot(df['Temperature'], df['Ice Cream Profits'])\n",
    "plt.xlabel('Temperature')\n",
    "plt.ylabel('Ice Cream Profits')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
