{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Multiclass classification with under-sampling\n\nSome balancing methods allow for balancing dataset with multiples classes.\nWe provide an example to illustrate the use of those methods which do\nnot differ from the binary case.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>\n# License: MIT\n\nfrom collections import Counter\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nfrom imblearn.datasets import make_imbalance\nfrom imblearn.under_sampling import NearMiss\nfrom imblearn.pipeline import make_pipeline\nfrom imblearn.metrics import classification_report_imbalanced\n\nprint(__doc__)\n\nRANDOM_STATE = 42\n\n# Create a folder to fetch the dataset\niris = load_iris()\nX, y = make_imbalance(\n    iris.data,\n    iris.target,\n    sampling_strategy={0: 25, 1: 50, 2: 50},\n    random_state=RANDOM_STATE,\n)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=RANDOM_STATE)\n\nprint(f\"Training target statistics: {Counter(y_train)}\")\nprint(f\"Testing target statistics: {Counter(y_test)}\")\n\n# Create a pipeline\npipeline = make_pipeline(\n    NearMiss(version=2), StandardScaler(), LogisticRegression(random_state=RANDOM_STATE)\n)\npipeline.fit(X_train, y_train)\n\n# Classify and report the results\nprint(classification_report_imbalanced(y_test, pipeline.predict(X_test)))"
      ]
    }
  ],
  "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.8.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}