{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simple classification example: the iris dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "from sklearn import datasets\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import classification_report\n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.metrics import confusion_matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import some data to play with\n",
    "# columns: Sepal Length, Sepal Width, Petal Length and Petal Width\n",
    "iris = datasets.load_iris()\n",
    "X = iris.data\n",
    "y = iris.target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# just to create a nice table\n",
    "df = pd.DataFrame({\"Sepal Length (cm)\": X[:,0], \"Sepal Width (cm)\": X[:,1], \n",
    "                   'Petal Length (cm)': X[:,2], 'Petal Width (cm)': X[:,3], \n",
    "                   'category': y})\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "list(iris.target_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# split data into training and test data sets\n",
    "x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)\n",
    "# random_state with a number creates a reproduceable random number series  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# plot with color code\n",
    "plt.subplots(1, 2, figsize=(10, 5))\n",
    "\n",
    "plt.subplot(1, 2, 1)\n",
    "plt.scatter(X[:, 0], X[:, 1], c=y, edgecolor='k')\n",
    "plt.xlabel('Sepal length')\n",
    "plt.ylabel('Sepal width')\n",
    "\n",
    "plt.subplot(1, 2, 2)\n",
    "plt.scatter(X[:, 2], X[:, 3], c=y, edgecolor='k')\n",
    "plt.xlabel('Petal length')\n",
    "plt.ylabel('Petal width')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Softmax regression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "# multiclass regression is done automatically depending on the input\n",
    "# L-BFGS Limited-memory Broyden–Fletcher–Goldfarb–Shanno\n",
    "log_reg = LogisticRegression(solver='lbfgs')\n",
    "log_reg.fit(x_train, y_train);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## k-nearest neighbor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "kn_neigh = KNeighborsClassifier(n_neighbors=5)\n",
    "kn_neigh.fit(x_train, y_train);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fisher linear discriminant"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n",
    "fisher_ld = LinearDiscriminantAnalysis()\n",
    "fisher_ld.fit(x_train, y_train);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Classification accuracy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for clf in [log_reg, kn_neigh, fisher_ld]:\n",
    "    y_pred = clf.predict(x_test)\n",
    "    acc = accuracy_score(y_test, y_pred)\n",
    "    print(type(clf).__name__)\n",
    "    print(f\"accuracy: {acc:0.2f}\")\n",
    "    \n",
    "    # confusion matrix: columns: true class, row: predicted class\n",
    "    print(confusion_matrix(y_test, y_pred),\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = log_reg.predict(x_test)\n",
    "print(classification_report(y_test, y_pred))\n",
    "# The \"support\" column in the classification_report provides \n",
    "# information about the distribution of classes in the test set,\n",
    "# showing how many instances of each class were present in the test data.\n",
    "\n",
    "# F1-score provides a single value that balances both precision and recall,\n",
    "# making it a useful metric for evaluating the overall performance \n",
    "# of a classification model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
