{
  "nbformat_minor": 0, 
  "nbformat": 4, 
  "cells": [
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "%matplotlib inline"
      ], 
      "outputs": [], 
      "metadata": {
        "collapsed": false
      }
    }, 
    {
      "source": [
        "\n# How to fit a basic model\n\n\nThese examples show how to fit a model using MonoRuleRandomForest.\n `MonoRuleRandomForest` first fits a forest ensemble using `sci-kit learn's`\nRandomForestClassifier, then filters the leaves to remove leaf 'rules' that\nare not monotone compliant. One consequence of this is that you need\nsufficient trees to ensure a reasonable number of leaves are left. \n\n"
      ], 
      "cell_type": "markdown", 
      "metadata": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "import numpy as np\nimport monorulerf as monorulerf\nfrom sklearn.datasets import load_boston"
      ], 
      "outputs": [], 
      "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": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "data = load_boston()\ny = data['target']\nX = data['data']\nfeatures = data['feature_names']"
      ], 
      "outputs": [], 
      "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": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "y[y< 21]=-1 # convert real output to 50-50 binary classification\ny[y>=21]=+1"
      ], 
      "outputs": [], 
      "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": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "incr_feats=[6,9]\ndecr_feats=[1,8,13]"
      ], 
      "outputs": [], 
      "metadata": {
        "collapsed": false
      }
    }, 
    {
      "source": [
        "Fit a MonoRuleRandomForest 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": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "# Specify hyperparams for model solution (normally optimised via oob_score or \n# CV)\nmtry=3\nn_estimators = 200\n# Solve model\nclf = monorulerf.MonoRuleRandomForest(n_estimators=n_estimators,\n                                             max_features=mtry,\n                                             n_jobs=1, oob_score=True,\n                                             random_state=11, criterion='gini',\n                                             incr_feats=incr_feats,\n                                             decr_feats=decr_feats)\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_"
      ], 
      "outputs": [], 
      "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": {}
    }
  ], 
  "metadata": {
    "kernelspec": {
      "display_name": "Python 2", 
      "name": "python2", 
      "language": "python"
    }, 
    "language_info": {
      "mimetype": "text/x-python", 
      "nbconvert_exporter": "python", 
      "name": "python", 
      "file_extension": ".py", 
      "version": "2.7.12", 
      "pygments_lexer": "ipython2", 
      "codemirror_mode": {
        "version": 2, 
        "name": "ipython"
      }
    }
  }
}