{
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3",
      "language": "python"
    },
    "language_info": {
      "mimetype": "text/x-python",
      "file_extension": ".py",
      "name": "python",
      "nbconvert_exporter": "python",
      "codemirror_mode": {
        "version": 3,
        "name": "ipython"
      },
      "version": "3.5.2",
      "pygments_lexer": "ipython3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0,
  "cells": [
    {
      "source": [
        "%matplotlib inline"
      ],
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false
      }
    },
    {
      "source": [
        "\n# How to fit a basic Monotone RF model\n\n\nThis example shows how to fit a model using `MonoRandomForestClassifier`.\nIn short, it is identical to `sci-kit learn's` RandomForestClassifier, with\nthe addition of `incr_feats`, `decr_feats` and `coef_calc_type` constructor\nparameters, which describe the monotone features and the coefficient\ncalculation method. It fits a forest ensemble, converts the leaves into\nmonotone compliant 'rules', an then recalculates the rule coefficients\nas described in the Theory section of this documentation.\n\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    },
    {
      "source": [
        "import numpy as np\nfrom monoensemble import MonoRandomForestClassifier\nfrom sklearn.datasets import load_boston"
      ],
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false
      }
    },
    {
      "source": [
        "Load the data\n----------------\n\nFirst we load the standard data source on \n`Boston Housing \n<https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html>`_, and \nconvert the output from real valued (regression) to binary classification \nwith roughly 50-50 class distribution:\n\n\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    },
    {
      "source": [
        "data = load_boston()\ny = data['target']\nX = data['data']\nfeatures = data['feature_names']"
      ],
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false
      }
    },
    {
      "source": [
        "Specify the monotone features\n-------------------------\nThere are 13 predictors for house price in the Boston dataset:\n\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    },
    {
      "source": [
        "#. CRIM - per capita crime rate by town\n#. ZN - proportion of residential land zoned for lots over 25,000 sq.ft.\n#. INDUS - proportion of non-retail business acres per town.\n#. CHAS - Charles River dummy variable (1 if tract bounds river; 0 otherwise)\n#. NOX - nitric oxides concentration (parts per 10 million)\n#. RM - average number of rooms per dwelling\n#. AGE - proportion of owner-occupied units built prior to 1940\n#. DIS - weighted distances to five Boston employment centres\n#. RAD - index of accessibility to radial highways\n#. TAX - full-value property-tax rate per $10,000\n#. PTRATIO - pupil-teacher ratio by town\n#. B - 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town\n#. LSTAT - % lower status of the population\n\n The output is MEDV - Median value of owner-occupied homes in $1000's, but we \n convert it to a binary y in +/-1 indicating whether MEDV is less than \n $21(,000):\n\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    },
    {
      "source": [
        "y[y< 21]=-1 # convert real output to 50-50 binary classification\ny[y>=21]=+1"
      ],
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false
      }
    },
    {
      "source": [
        "We suspect that the number of rooms (6. RM) and the highway \naccessibility (9. RAD) would, if anything, increase the price of a house\n(all other things being equal). Likewise we suspect that crime rate (1.\nCRIM), distance from employment (8. DIS) and percentage of lower status\nresidents (13. LSTAT) would be likely to, if anything, decrease house prices.\nSo we have:\n\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    },
    {
      "source": [
        "incr_feats=[6,9]\ndecr_feats=[1,8,13]"
      ],
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false
      }
    },
    {
      "source": [
        "Fit a MonoRandomForestClassifier model\n-------------------------\nWe now fit our classifier. To understand the model and hyperparameters, \nplease refer to the original paper available \n`here <http://staffhome.ecm.uwa.edu.au/~19514733/>`_:\n\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    },
    {
      "source": [
        "# Specify hyperparams for model solution (normally optimised via oob_score or \n# CV)\nn_estimators = 100\nmtry = 3\ncoef_calc_type='boost' # or 'bayes','logistic'\n# Solve model\nclf = MonoRandomForestClassifier(n_estimators=n_estimators,\n                                  max_features=mtry,\n                                  oob_score=True,\n                                  random_state=11,\n                                  incr_feats=incr_feats,\n                                  decr_feats=decr_feats,\n                                  coef_calc_type=coef_calc_type)\nclf.fit(X, y)\n\n# Assess the model\ny_pred = clf.predict(X)\nacc_insample = np.sum(y == y_pred) / len(y)\nmcr_oob=clf.oob_score_"
      ],
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false
      }
    },
    {
      "source": [
        "Final notes\n-----------------------\nIn a real scenario we would optimise the hyperparameter `mtry` using using\nthe out-of-box (oob) score or cross-validation but this is \nnot covered in these basic examples. Enjoy!\n\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    }
  ]
}