| 1 |
{ |
| 2 |
"cells": [ |
| 3 |
{ |
| 4 |
"cell_type": "markdown", |
| 5 |
"metadata": {}, |
| 6 |
"source": [ |
| 7 |
"### Outlier Detection with `bqplot`\n", |
| 8 |
"---" |
| 9 |
] |
| 10 |
}, |
| 11 |
{ |
| 12 |
"cell_type": "markdown", |
| 13 |
"metadata": {}, |
| 14 |
"source": [ |
| 15 |
"In this notebook, we create a class `DNA` that leverages the new bqplot canvas based [HeatMap](https://github.com/bloomberg/bqplot/blob/master/examples/Marks/HeatMap.ipynb) along with the ipywidgets Range Slider to help us detect and clean outliers in our data. The class accepts a DataFrame and allows you to visually and programmatically filter your outliers. The cleaned DataFrame can then be retrieved through a simple convenience function." |
| 16 |
] |
| 17 |
}, |
| 18 |
{ |
| 19 |
"cell_type": "code", |
| 20 |
"execution_count": null, |
| 21 |
"metadata": {}, |
| 22 |
"outputs": [], |
| 23 |
"source": [ |
| 24 |
"from bqplot import (DateScale, ColorScale, HeatMap, \n", |
| 25 |
" Figure, LinearScale, OrdinalScale, Axis)\n", |
| 26 |
"from scipy.stats import percentileofscore\n", |
| 27 |
"from scipy.interpolate import interp1d\n", |
| 28 |
"import bqplot.pyplot as plt\n", |
| 29 |
"from traitlets import List, Float, observe\n", |
| 30 |
"from ipywidgets import IntRangeSlider, Layout, VBox, HBox, jslink\n", |
| 31 |
"from pandas import DatetimeIndex\n", |
| 32 |
"import numpy as np\n", |
| 33 |
"import pandas as pd\n", |
| 34 |
"\n", |
| 35 |
"def quantile_space(x, q1=0.1, q2=0.9):\n", |
| 36 |
" '''\n", |
| 37 |
" Returns a function that squashes quantiles between q1 and q2\n", |
| 38 |
" '''\n", |
| 39 |
" q1_x, q2_x = np.percentile(x, [q1, q2])\n", |
| 40 |
" qs = np.percentile(x, np.linspace(0, 100, 100))\n", |
| 41 |
" def get_quantile(t):\n", |
| 42 |
" return np.interp(t, qs, np.linspace(0, 100, 100))\n", |
| 43 |
" def f(y):\n", |
| 44 |
" return np.interp(get_quantile(y), [0, q1, q2, 100], [-1, 0, 0, 1])\n", |
| 45 |
" return f\n", |
| 46 |
"\n", |
| 47 |
"class DNA(VBox):\n", |
| 48 |
" \n", |
| 49 |
" colors = List()\n", |
| 50 |
" q1 = Float()\n", |
| 51 |
" q2 = Float()\n", |
| 52 |
" \n", |
| 53 |
" def __init__(self, data, **kwargs):\n", |
| 54 |
" self.data = data\n", |
| 55 |
" date_x, date_y = False, False\n", |
| 56 |
" transpose = kwargs.pop('transpose', False)\n", |
| 57 |
" if transpose is True:\n", |
| 58 |
" if type(data.index) is DatetimeIndex:\n", |
| 59 |
" self.x_scale = DateScale()\n", |
| 60 |
" if type(data.columns) is DatetimeIndex:\n", |
| 61 |
" self.y_scale = DateScale()\n", |
| 62 |
" x, y = list(data.columns.values), data.index.values\n", |
| 63 |
" else:\n", |
| 64 |
" if type(data.index) is DatetimeIndex:\n", |
| 65 |
" date_x = True\n", |
| 66 |
" if type(data.columns) is DatetimeIndex:\n", |
| 67 |
" date_y = True\n", |
| 68 |
" x, y = data.index.values, list(data.columns.values)\n", |
| 69 |
" \n", |
| 70 |
" self.q1, self.q2 = kwargs.pop('quantiles', (1, 99))\n", |
| 71 |
" \n", |
| 72 |
" self.quant_func = quantile_space(self.data.values.flatten(), q1=self.q1, q2=self.q2)\n", |
| 73 |
" self.colors = kwargs.pop('colors', ['Red', 'Black', 'Green'])\n", |
| 74 |
" \n", |
| 75 |
" self.x_scale = DateScale() if date_x is True else LinearScale()\n", |
| 76 |
" self.y_scale = DateScale() if date_y is True else OrdinalScale(padding_y=0)\n", |
| 77 |
" self.color_scale = ColorScale(colors=self.colors)\n", |
| 78 |
" self.heat_map = HeatMap(color=self.quant_func(self.data.T), x=x, y=y, scales={'x': self.x_scale, 'y': self.y_scale,\n", |
| 79 |
" 'color': self.color_scale})\n", |
| 80 |
" self.x_ax = Axis(scale=self.x_scale)\n", |
| 81 |
" self.y_ax = Axis(scale=self.y_scale, orientation='vertical')\n", |
| 82 |
" show_axes = kwargs.pop('show_axes', True)\n", |
| 83 |
" self.axes = [self.x_ax, self.y_ax] if show_axes is True else []\n", |
| 84 |
" \n", |
| 85 |
" self.height = kwargs.pop('height', '800px')\n", |
| 86 |
" self.layout = kwargs.pop('layout', Layout(width='100%', height=self.height, flex='1'))\n", |
| 87 |
" self.fig_margin = kwargs.pop('fig_margin', {'top': 60, 'bottom': 60, 'left': 150, 'right': 0})\n", |
| 88 |
" kwargs.setdefault('padding_y', 0.0)\n", |
| 89 |
" \n", |
| 90 |
" self.create_interaction(**kwargs)\n", |
| 91 |
" \n", |
| 92 |
" self.figure = Figure(marks=[self.heat_map], axes=self.axes, fig_margin=self.fig_margin, \n", |
| 93 |
" layout=self.layout, min_aspect_ratio=0.,**kwargs)\n", |
| 94 |
" \n", |
| 95 |
" super(VBox, self).__init__(children=[self.range_slider, self.figure], layout=Layout(align_items='center',\n", |
| 96 |
" width='100%',\n", |
| 97 |
" height='100%'),\n", |
| 98 |
" **kwargs)\n", |
| 99 |
" \n", |
| 100 |
" def create_interaction(self, **kwargs):\n", |
| 101 |
" self.range_slider = IntRangeSlider(description='Filter Range', value=(self.q1, self.q2), layout=Layout(width='100%'))\n", |
| 102 |
" self.range_slider.observe(self.slid_changed, 'value')\n", |
| 103 |
" self.observe(self.changed, ['q1', 'q2'])\n", |
| 104 |
" \n", |
| 105 |
" \n", |
| 106 |
" def slid_changed(self, new):\n", |
| 107 |
" self.q1 = self.range_slider.value[0]\n", |
| 108 |
" self.q2 = self.range_slider.value[1]\n", |
| 109 |
" \n", |
| 110 |
" def changed(self, new):\n", |
| 111 |
" self.range_slider.value = (self.q1, self.q2)\n", |
| 112 |
" \n", |
| 113 |
" self.quant_func = quantile_space(self.data.values.flatten(), q1=self.q1, q2=self.q2)\n", |
| 114 |
" self.heat_map.color = self.quant_func(self.data.T)\n", |
| 115 |
" \n", |
| 116 |
" def get_filtered_df(self, fill_type='median'):\n", |
| 117 |
" q1_x, q2_x = np.percentile(self.data, [self.q1, self.q2])\n", |
| 118 |
" if fill_type == 'median':\n", |
| 119 |
" return self.data[(self.data >= q1_x) & (self.data <= q2_x)].apply(lambda x: x.fillna(x.median()))\n", |
| 120 |
" elif fill_type == 'mean':\n", |
| 121 |
" return self.data[(self.data >= q1_x) & (self.data <= q2_x)].apply(lambda x: x.fillna(x.mean()))\n", |
| 122 |
" else:\n", |
| 123 |
" raise ValueError(\"fill_type must be one of ('median', 'mean')\")" |
| 124 |
] |
| 125 |
}, |
| 126 |
{ |
| 127 |
"cell_type": "markdown", |
| 128 |
"metadata": {}, |
| 129 |
"source": [ |
| 130 |
"We define the size of our matrix here. Larger matrices require a larger height." |
| 131 |
] |
| 132 |
}, |
| 133 |
{ |
| 134 |
"cell_type": "code", |
| 135 |
"execution_count": null, |
| 136 |
"metadata": {}, |
| 137 |
"outputs": [], |
| 138 |
"source": [ |
| 139 |
"size = 100" |
| 140 |
] |
| 141 |
}, |
| 142 |
{ |
| 143 |
"cell_type": "code", |
| 144 |
"execution_count": null, |
| 145 |
"metadata": {}, |
| 146 |
"outputs": [], |
| 147 |
"source": [ |
| 148 |
"def num_to_col_letters(num):\n", |
| 149 |
" letters = ''\n", |
| 150 |
" while num:\n", |
| 151 |
" mod = (num - 1) % 26\n", |
| 152 |
" letters += chr(mod + 65)\n", |
| 153 |
" num = (num - 1) // 26\n", |
| 154 |
" return ''.join(reversed(letters))\n", |
| 155 |
"\n", |
| 156 |
"letters = []\n", |
| 157 |
"\n", |
| 158 |
"for i in range(1, size+1):\n", |
| 159 |
" letters.append(num_to_col_letters(i))" |
| 160 |
] |
| 161 |
}, |
| 162 |
{ |
| 163 |
"cell_type": "code", |
| 164 |
"execution_count": null, |
| 165 |
"metadata": {}, |
| 166 |
"outputs": [], |
| 167 |
"source": [ |
| 168 |
"data = pd.DataFrame(np.random.randn(size, size), columns=letters)" |
| 169 |
] |
| 170 |
}, |
| 171 |
{ |
| 172 |
"cell_type": "code", |
| 173 |
"execution_count": null, |
| 174 |
"metadata": {}, |
| 175 |
"outputs": [], |
| 176 |
"source": [ |
| 177 |
"data_dna = DNA(data, title='DNA of our Data', height='1400px', colors=['Red', 'White', 'Green'])\n", |
| 178 |
"data_dna" |
| 179 |
] |
| 180 |
}, |
| 181 |
{ |
| 182 |
"cell_type": "markdown", |
| 183 |
"metadata": {}, |
| 184 |
"source": [ |
| 185 |
"Instead of setting the quantiles by the sliders, we can also set them programmatically. Using a range of (5, 95) restricts the data considerably." |
| 186 |
] |
| 187 |
}, |
| 188 |
{ |
| 189 |
"cell_type": "code", |
| 190 |
"execution_count": null, |
| 191 |
"metadata": {}, |
| 192 |
"outputs": [], |
| 193 |
"source": [ |
| 194 |
"data_dna.q1, data_dna.q2 = 5, 95" |
| 195 |
] |
| 196 |
}, |
| 197 |
{ |
| 198 |
"cell_type": "markdown", |
| 199 |
"metadata": {}, |
| 200 |
"source": [ |
| 201 |
"Now, we can use the convenience function to extract a clean DataFrame." |
| 202 |
] |
| 203 |
}, |
| 204 |
{ |
| 205 |
"cell_type": "code", |
| 206 |
"execution_count": null, |
| 207 |
"metadata": { |
| 208 |
"scrolled": true |
| 209 |
}, |
| 210 |
"outputs": [], |
| 211 |
"source": [ |
| 212 |
"data_clean = data_dna.get_filtered_df()" |
| 213 |
] |
| 214 |
}, |
| 215 |
{ |
| 216 |
"cell_type": "markdown", |
| 217 |
"metadata": {}, |
| 218 |
"source": [ |
| 219 |
"The DNA fills outliers with the mean of the column. Alternately, we can fill the outliers by the mean." |
| 220 |
] |
| 221 |
}, |
| 222 |
{ |
| 223 |
"cell_type": "code", |
| 224 |
"execution_count": null, |
| 225 |
"metadata": {}, |
| 226 |
"outputs": [], |
| 227 |
"source": [ |
| 228 |
"data_mean = data_dna.get_filtered_df(fill_type='mean')" |
| 229 |
] |
| 230 |
}, |
| 231 |
{ |
| 232 |
"cell_type": "markdown", |
| 233 |
"metadata": {}, |
| 234 |
"source": [ |
| 235 |
"We can also visualize the new DataFrame the same way to test how our outliers look now." |
| 236 |
] |
| 237 |
}, |
| 238 |
{ |
| 239 |
"cell_type": "code", |
| 240 |
"execution_count": null, |
| 241 |
"metadata": {}, |
| 242 |
"outputs": [], |
| 243 |
"source": [ |
| 244 |
"DNA(data_clean, title='Cleaned Data', height='1200px', colors=['Red', 'White', 'Green'])" |
| 245 |
] |
| 246 |
} |
| 247 |
], |
| 248 |
"metadata": { |
| 249 |
"anaconda-cloud": {}, |
| 250 |
"kernelspec": { |
| 251 |
"display_name": "Python 3", |
| 252 |
"language": "python", |
| 253 |
"name": "python3" |
| 254 |
}, |
| 255 |
"language_info": { |
| 256 |
"codemirror_mode": { |
| 257 |
"name": "ipython", |
| 258 |
"version": 3 |
| 259 |
}, |
| 260 |
"file_extension": ".py", |
| 261 |
"mimetype": "text/x-python", |
| 262 |
"name": "python", |
| 263 |
"nbconvert_exporter": "python", |
| 264 |
"pygments_lexer": "ipython3", |
| 265 |
"version": "3.7.6" |
| 266 |
} |
| 267 |
}, |
| 268 |
"nbformat": 4, |
| 269 |
"nbformat_minor": 2 |
| 270 |
} |