{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# SkopeRules example\n\n\nAn example using SkopeRules for imbalanced classification.\n\nSkopeRules find logical rules with high precision and fuse them. Finding good\nrules is done by fitting classification and regression trees to sub-samples.\nA fitted tree defines a set of rules (each tree node defines a rule); rules\nare then tested out of the bag, and the ones with higher precision are selected\nand merged. This produces a real-valued decision function, reflecting for\neach new sample how many rules (each weighted by respective precision) have\nfound it abnormal.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom skrules import SkopeRules\nprint(__doc__)\n\nrng = np.random.RandomState(42)\n\nn_inliers = 1000\nn_outliers = 50\n\n# Generate train data\nI = 0.5 * rng.randn(int(n_inliers / 2), 2)\nX_inliers = np.r_[I + 2, I - 2]\nO = 0.5 * rng.randn(n_outliers, 2)\nX_outliers = O  # np.r_[O, O + [2, -2]]\nX_train = np.r_[X_inliers, X_outliers]\ny_train = [0] * n_inliers + [1] * n_outliers"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Training the SkopeRules classifier\n..................................\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# fit the model\nclf = SkopeRules(random_state=rng, n_estimators=10)\nclf.fit(X_train, y_train)\n\n# plot the line, the samples, and the nearest vectors to the plane\nxx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))\nZ = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\n\nplt.title(\"Skope Rules, value of the decision_function method\")\nplt.contourf(xx, yy, Z, cmap=plt.cm.Blues)\n\na = plt.scatter(X_inliers[:, 0], X_inliers[:, 1], c='white',\n                s=20, edgecolor='k')\nb = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red',\n                s=20, edgecolor='k')\nplt.axis('tight')\nplt.xlim((-5, 5))\nplt.ylim((-5, 5))\nplt.legend([a, b],\n           [\"inliers\", \"outliers\"],\n           loc=\"upper left\")\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Extracting top rules\n....................\n\nOn the 4 following figures, the predict_top_rules method is used with\nseveral values of n_rules. n_rules = 2 means that the prediction is\ndone using only the 2 best rules.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print('The 4 most precise rules are the following:')\nfor rule in clf.rules_[:4]:\n    print(rule[0])\n\nfig, axes = plt.subplots(2, 2, figsize=(12, 5),\n                         sharex=True, sharey=True)\nfor i_ax, ax in enumerate(np.ravel(axes)):\n    Z = clf.predict_top_rules(np.c_[xx.ravel(), yy.ravel()], i_ax+1)\n    Z = Z.reshape(xx.shape)\n    ax.set_title(\"Prediction with predict_top_rules, n_rules=\"+str(i_ax+1))\n    ax.contourf(xx, yy, Z, cmap=plt.cm.Blues)\n\n    a = ax.scatter(X_inliers[:, 0], X_inliers[:, 1], c='white',\n                   s=20, edgecolor='k')\n    b = ax.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red',\n                   s=20, edgecolor='k')\n    ax.axis('tight')\nplt.xlim((-5, 5))\nplt.ylim((-5, 5))\nplt.legend([a, b],\n           [\"inliers\", \"outliers\"],\n           loc=\"upper left\")\nplt.show()"
      ]
    }
  ],
  "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.6.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}