{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.cm as cm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from kerasy.utils import generateWholeCakes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "seed = 1\n",
    "N = 200\n",
    "K = 3\n",
    "r_low, r_high = 2,5\n",
    "rmin,rmax = -r_high, r_high"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "X,Y = np.meshgrid(np.linspace(rmin,rmax,100), np.linspace(rmin,rmax,100))\n",
    "XY = np.c_[X.ravel(),Y.ravel()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 22844 characters]\n",
      "text/plain": [
       "<Figure size 288x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "train_x, train_y = generateWholeCakes(K*2, N*2, r_low=r_low, r_high=r_high, seed=seed, same=False, plot=True, figsize=(4,4), noise_scale=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "mask = (train_y%2)==0\n",
    "train_x = train_x[mask]\n",
    "train_y = train_y[mask]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 11804 characters]\n",
      "text/plain": [
       "<Figure size 288x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.figure(figsize=(4,4))\n",
    "for i,(x,y) in enumerate(train_x):\n",
    "    plt.scatter(x, y, color=cm.jet(train_y[i]/K))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## KMeans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from kerasy.ML.EM import KMeans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/20 [####----------------]  20.00% - 0.021s  distortion measure: 1585.073\n",
      "05/20 [#####---------------]  25.00% - 0.052s  distortion measure: 521.5821\n",
      "09/20 [#########-----------]  45.00% - 0.124s  distortion measure: 446.9584\n",
      "13/20 [#############-------]  65.00% - 0.231s  distortion measure: 342.2100\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 225516 characters]\n",
      "text/plain": [
       "<Figure size 720x720 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize=(10,10))\n",
    "for i, K in enumerate([2,3,4,5]):\n",
    "    ax = fig.add_subplot(2,2,i+1)\n",
    "    # Change the depth to fit the data.\n",
    "    model = KMeans(K=K, random_state=seed)\n",
    "    model.fit(train_x, memorize=True, max_iter=20)\n",
    "    Z = model.predict(XY).reshape(X.shape)\n",
    "    ax.scatter(train_x[:,0], train_x[:,1], c=train_y, s=50)\n",
    "    ax.pcolor(X,Y,Z,alpha=0.2)\n",
    "    # Initial µs.\n",
    "    for i,(x,y) in enumerate(model.history[0][0]):  ax.scatter(x,y,s=200, edgecolors=cm.jet(i/K), facecolor=\"white\", marker=\"o\")\n",
    "    # Final µs.olor\n",
    "    for i,(x,y) in enumerate(model.history[-1][0]): ax.scatter(x,y,s=200, edgecolors=cm.jet(i/K), facecolor=\"white\", marker=\"d\")\n",
    "    ax.set_title(f\"KMeans K={K}\\nO:initial, D:Final\"), ax.set_xlim(rmin,rmax), ax.set_ylim(rmin,rmax)\n",
    "    ax.set_xticks([]), ax.set_yticks([])\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Gaussian Mixture model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from kerasy.ML.EM import MixedGaussian"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "021/250 [#-------------------]   8.40% - 0.032s  Log Likelihood: -903.973\n",
      "022/250 [#-------------------]   8.80% - 0.042s  Log Likelihood: -832.961\n",
      "204/250 [################----]  81.60% - 0.692s  Log Likelihood: -824.379\n",
      "191/250 [###############-----]  76.40% - 0.792s  Log Likelihood: -818.752\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 433308 characters]\n",
      "text/plain": [
       "<Figure size 720x720 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize=(10,10))\n",
    "for i, K in enumerate([2,3,4,5]):\n",
    "    ax = fig.add_subplot(2,2,i+1)\n",
    "    # Change the depth to fit the data.\n",
    "    model = MixedGaussian(K=K, random_state=seed)\n",
    "    model.fit(train_x, max_iter=250)\n",
    "    Z = np.sum(model.predict(XY), axis=1).reshape(X.shape)\n",
    "    ax.scatter(train_x[:,0], train_x[:,1], c=train_y, s=50)\n",
    "    ax.pcolor(X,Y,Z,alpha=0.2,cmap=\"jet\")\n",
    "    ax.set_title(f\"Gaussian Mixture Model K={K}\\nLog Likelihood: {model.loglikelihood(train_x):.3f}\"), ax.set_xlim(rmin,rmax), ax.set_ylim(rmin,rmax)\n",
    "    ax.set_xticks([]), ax.set_yticks([])\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "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.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
