├── .github └── workflows │ └── main.yml ├── .gitignore ├── 00_Numpy.ipynb ├── 01_Tensor.ipynb ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── docs ├── .gitignore ├── Gemfile ├── Gemfile.lock ├── Numpy.html ├── _config.yml ├── _data │ ├── alerts.yml │ ├── definitions.yml │ ├── glossary.yml │ ├── sidebars │ │ └── home_sidebar.yml │ ├── tags.yml │ ├── terms.yml │ └── topnav.yml ├── _includes │ ├── archive.html │ ├── callout.html │ ├── footer.html │ ├── google_analytics.html │ ├── head.html │ ├── head_print.html │ ├── image.html │ ├── important.html │ ├── initialize_shuffle.html │ ├── inline_image.html │ ├── links.html │ ├── note.html │ ├── search_google_custom.html │ ├── search_simple_jekyll.html │ ├── sidebar.html │ ├── tip.html │ ├── toc.html │ ├── topnav.html │ └── warning.html ├── _layouts │ ├── default.html │ ├── default_print.html │ ├── none.html │ ├── page.html │ └── page_print.html ├── css │ ├── bootstrap.min.css │ ├── boxshadowproperties.css │ ├── customstyles.css │ ├── font-awesome.min.css │ ├── fonts │ │ ├── FontAwesome.otf │ │ ├── fontawesome-webfont.eot │ │ ├── fontawesome-webfont.svg │ │ ├── fontawesome-webfont.ttf │ │ ├── fontawesome-webfont.woff │ │ └── fontawesome-webfont.woff2 │ ├── modern-business.css │ ├── printstyles.css │ ├── syntax.css │ ├── theme-blue.css │ └── theme-green.css ├── feed.xml ├── fonts │ ├── FontAwesome.otf │ ├── fontawesome-webfont.eot │ ├── fontawesome-webfont.svg │ ├── fontawesome-webfont.ttf │ ├── fontawesome-webfont.woff │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.svg │ ├── glyphicons-halflings-regular.ttf │ ├── glyphicons-halflings-regular.woff │ └── glyphicons-halflings-regular.woff2 ├── images │ ├── company_logo.png │ ├── company_logo_big.png │ ├── doc_example.png │ ├── export_example.png │ ├── favicon.ico │ └── workflowarrow.png ├── index.html ├── js │ ├── customscripts.js │ ├── jekyll-search.js │ ├── jquery.ba-throttle-debounce.min.js │ ├── jquery.navgoco.min.js │ ├── jquery.shuffle.min.js │ └── toc.js ├── licenses │ ├── LICENSE │ └── LICENSE-BSD-NAVGOCO.txt ├── sidebar.json ├── sitemap.xml └── tooltips.json ├── examples └── Numpy Example.ipynb ├── fastai2_tabular_hybrid ├── __init__.py ├── _nbdev.py ├── numpy.py └── tensor.py ├── index.ipynb ├── settings.ini └── setup.py /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v1 8 | - uses: actions/setup-python@v1 9 | with: 10 | python-version: '3.6' 11 | architecture: 'x64' 12 | - name: Install the library 13 | run: | 14 | pip install nbdev jupyter 15 | pip install -e . 16 | - name: Read all notebooks 17 | run: | 18 | nbdev_read_nbs 19 | - name: Check if all notebooks are cleaned 20 | run: | 21 | echo "Check we are starting with clean git checkout" 22 | if [ -n "$(git status -uno -s)" ]; then echo "git status is not clean"; false; fi 23 | echo "Trying to strip out notebooks" 24 | nbdev_clean_nbs 25 | echo "Check that strip out was unnecessary" 26 | git status -s # display the status to see which nbs need cleaning up 27 | if [ -n "$(git status -uno -s)" ]; then echo -e "!!! Detected unstripped out notebooks\n!!!Remember to run nbdev_install_git_hooks"; false; fi 28 | - name: Check if there is no diff library/notebooks 29 | run: | 30 | if [ -n "$(nbdev_diff_nbs)" ]; then echo -e "!!! Detected difference between the notebooks and the library"; false; fi 31 | - name: Run tests 32 | run: | 33 | nbdev_test_nbs 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.bak 2 | .gitattributes 3 | .last_checked 4 | .gitconfig 5 | *.bak 6 | *.log 7 | *~ 8 | ~* 9 | _tmp* 10 | tmp* 11 | tags 12 | 13 | # Byte-compiled / optimized / DLL files 14 | __pycache__/ 15 | *.py[cod] 16 | *$py.class 17 | 18 | # C extensions 19 | *.so 20 | 21 | # Distribution / packaging 22 | .Python 23 | env/ 24 | build/ 25 | develop-eggs/ 26 | dist/ 27 | downloads/ 28 | eggs/ 29 | .eggs/ 30 | lib/ 31 | lib64/ 32 | parts/ 33 | sdist/ 34 | var/ 35 | wheels/ 36 | *.egg-info/ 37 | .installed.cfg 38 | *.egg 39 | 40 | # PyInstaller 41 | # Usually these files are written by a python script from a template 42 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 43 | *.manifest 44 | *.spec 45 | 46 | # Installer logs 47 | pip-log.txt 48 | pip-delete-this-directory.txt 49 | 50 | # Unit test / coverage reports 51 | htmlcov/ 52 | .tox/ 53 | .coverage 54 | .coverage.* 55 | .cache 56 | nosetests.xml 57 | coverage.xml 58 | *.cover 59 | .hypothesis/ 60 | 61 | # Translations 62 | *.mo 63 | *.pot 64 | 65 | # Django stuff: 66 | *.log 67 | local_settings.py 68 | 69 | # Flask stuff: 70 | instance/ 71 | .webassets-cache 72 | 73 | # Scrapy stuff: 74 | .scrapy 75 | 76 | # Sphinx documentation 77 | docs/_build/ 78 | 79 | # PyBuilder 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # celery beat schedule file 89 | celerybeat-schedule 90 | 91 | # SageMath parsed files 92 | *.sage.py 93 | 94 | # dotenv 95 | .env 96 | 97 | # virtualenv 98 | .venv 99 | venv/ 100 | ENV/ 101 | 102 | # Spyder project settings 103 | .spyderproject 104 | .spyproject 105 | 106 | # Rope project settings 107 | .ropeproject 108 | 109 | # mkdocs documentation 110 | /site 111 | 112 | # mypy 113 | .mypy_cache/ 114 | 115 | .vscode 116 | *.swp 117 | 118 | # osx generated files 119 | .DS_Store 120 | .DS_Store? 121 | .Trashes 122 | ehthumbs.db 123 | Thumbs.db 124 | .idea 125 | 126 | # pytest 127 | .pytest_cache 128 | 129 | # tools/trust-doc-nbs 130 | docs_src/.last_checked 131 | 132 | # symlinks to fastai 133 | docs_src/fastai 134 | tools/fastai 135 | 136 | # link checker 137 | checklink/cookies.txt 138 | 139 | # .gitconfig is now autogenerated 140 | .gitconfig 141 | 142 | -------------------------------------------------------------------------------- /00_Numpy.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "# default_exp numpy" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "# 00_Numpy\n", 17 | "\n", 18 | "> Building an example `Dataset` and `DataLoader` with `NumPy`" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "#hide\n", 28 | "from nbdev.showdoc import *" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "#export\n", 38 | "from fastai2.tabular.all import *" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": {}, 44 | "source": [ 45 | "For our data we'll first utilize `TabularPandas` for pre-processing. One potential is to use `TabularPandas` for pre-processing only, or to integrate `NumPy` directly into it" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "path = untar_data(URLs.ADULT_SAMPLE)\n", 55 | "df = pd.read_csv(path/'adult.csv')" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']\n", 65 | "cont_names = ['age', 'fnlwgt', 'education-num']\n", 66 | "procs = [Categorify, FillMissing, Normalize]\n", 67 | "y_names = 'salary'\n", 68 | "splits = RandomSplitter()(range_of(df))" 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": {}, 74 | "source": [ 75 | "We'll still build our regular `TabularPandas`, as we haven't done any `NumPy` modifications yet" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "to = TabularPandas(df, procs=procs, cat_names=cat_names, cont_names=cont_names,\n", 85 | " y_names=y_names, splits=splits)" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "#export\n", 95 | "class NumpyDataset():\n", 96 | " \"A `Numpy` dataset object from `TabularPandas`\"\n", 97 | " def __init__(self, to:TabularPandas):\n", 98 | " self.cats = to.cats.to_numpy().astype(np.long)\n", 99 | " self.conts = to.conts.to_numpy().astype(np.float32)\n", 100 | " self.ys = to.ys.to_numpy()\n", 101 | " \n", 102 | " def __getitem__(self, idx): \n", 103 | " idx = idx[0]\n", 104 | " return self.cats[idx:idx+self.bs], self.conts[idx:idx+self.bs], self.ys[idx:idx+self.bs]\n", 105 | " \n", 106 | " def __len__(self): return len(self.cats)" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": null, 112 | "metadata": {}, 113 | "outputs": [], 114 | "source": [ 115 | "ds = NumpyDataset(to)" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [ 124 | "ds.bs = 3" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": {}, 131 | "outputs": [], 132 | "source": [ 133 | "a,b,c = ds[[0]]\n", 134 | "test_eq(len(a), 3)" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": null, 140 | "metadata": {}, 141 | "outputs": [], 142 | "source": [ 143 | "#export\n", 144 | "class NumpyDataLoader(DataLoader):\n", 145 | " def __init__(self, dataset, bs=1, **kwargs):\n", 146 | " \"A `DataLoader` for a `NumpyDataset`\"\n", 147 | " super().__init__(dataset, bs=bs, **kwargs)\n", 148 | " self.dataset.bs = bs\n", 149 | " \n", 150 | " def create_item(self, s): return s\n", 151 | " \n", 152 | " def create_batch(self, b):\n", 153 | " cat, cont, y = self.dataset[b]\n", 154 | " return tensor(cat).to(self.device), tensor(cont).to(self.device), tensor(y).to(self.device)" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | "dl = NumpyDataLoader(ds, bs=3)" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": null, 169 | "metadata": {}, 170 | "outputs": [], 171 | "source": [ 172 | "batch = next(iter(dl))" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": null, 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "test_eq(len(dl), len(ds)//3+1)" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "#export\n", 191 | "@patch\n", 192 | "def shuffle_fn(x:NumpyDataLoader):\n", 193 | " \"Shuffle the interior dataset\"\n", 194 | " rng = np.random.permutation(len(x.dataset))\n", 195 | " x.dataset.cats = x.dataset.cats[rng]\n", 196 | " x.dataset.conts = x.dataset.conts[rng]\n", 197 | " x.dataset.ys = x.dataset.ys[rng]" 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": null, 203 | "metadata": {}, 204 | "outputs": [], 205 | "source": [ 206 | "#export\n", 207 | "@patch\n", 208 | "def get_idxs(x:NumpyDataLoader):\n", 209 | " \"Get index's to select\"\n", 210 | " idxs = Inf.count if x.indexed else Inf.nones\n", 211 | " if x.n is not None: idxs = list(range(len(x.dataset)))\n", 212 | " if x.shuffle: x.shuffle_fn()\n", 213 | " return idxs" 214 | ] 215 | }, 216 | { 217 | "cell_type": "markdown", 218 | "metadata": {}, 219 | "source": [ 220 | "To ensure that we still see an improvement, we'll compare timings" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "train_ds = NumpyDataset(to.train)\n", 230 | "valid_ds = NumpyDataset(to.valid)" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": null, 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "train_dl = NumpyDataLoader(train_ds, bs=64, shuffle=True, drop_last=True)\n", 240 | "valid_dl = NumpyDataLoader(valid_ds, bs=64)" 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": null, 246 | "metadata": {}, 247 | "outputs": [], 248 | "source": [ 249 | "dls = to.dataloaders(bs=64)" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": {}, 256 | "outputs": [ 257 | { 258 | "name": "stdout", 259 | "output_type": "stream", 260 | "text": [ 261 | "31.2 ms ± 35.8 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 262 | ] 263 | } 264 | ], 265 | "source": [ 266 | "%%timeit\n", 267 | "# Numpy\n", 268 | "for _ in train_dl: pass" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": null, 274 | "metadata": {}, 275 | "outputs": [ 276 | { 277 | "name": "stdout", 278 | "output_type": "stream", 279 | "text": [ 280 | "1.02 s ± 784 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 281 | ] 282 | } 283 | ], 284 | "source": [ 285 | "%%timeit\n", 286 | "# fastai\n", 287 | "for _ in dls[0]: pass" 288 | ] 289 | }, 290 | { 291 | "cell_type": "code", 292 | "execution_count": null, 293 | "metadata": {}, 294 | "outputs": [ 295 | { 296 | "name": "stdout", 297 | "output_type": "stream", 298 | "text": [ 299 | "7.35 ms ± 12.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" 300 | ] 301 | } 302 | ], 303 | "source": [ 304 | "%%timeit\n", 305 | "# Numpy\n", 306 | "for _ in valid_dl: pass" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": null, 312 | "metadata": {}, 313 | "outputs": [ 314 | { 315 | "name": "stdout", 316 | "output_type": "stream", 317 | "text": [ 318 | "250 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 319 | ] 320 | } 321 | ], 322 | "source": [ 323 | "%%timeit\n", 324 | "# fastai\n", 325 | "for _ in dls[1]: pass" 326 | ] 327 | }, 328 | { 329 | "cell_type": "code", 330 | "execution_count": null, 331 | "metadata": {}, 332 | "outputs": [], 333 | "source": [ 334 | "# export\n", 335 | "class NumpyDataLoaders(DataLoaders):\n", 336 | " def __init__(self, to, bs=64, val_bs=None, shuffle_train=True, device='cpu', **kwargs):\n", 337 | " train_ds = NumpyDataset(to.train)\n", 338 | " valid_ds = NumpyDataset(to.valid)\n", 339 | " val_bs = bs if val_bs is None else val_bs\n", 340 | " train = NumpyDataLoader(train_ds, bs=bs, shuffle=shuffle_train, device=device, drop_last=True, **kwargs)\n", 341 | " valid = NumpyDataLoader(valid_ds, bs=val_bs, shuffle=False, device=device, **kwargs)\n", 342 | " super().__init__(train, valid, device=device, **kwargs)" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": null, 348 | "metadata": {}, 349 | "outputs": [], 350 | "source": [ 351 | "df_np = df.to_numpy()" 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": null, 357 | "metadata": {}, 358 | "outputs": [], 359 | "source": [ 360 | "col_names = df.columns" 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": null, 366 | "metadata": {}, 367 | "outputs": [], 368 | "source": [ 369 | "idx_2_col = dict(zip(range(len(col_names)), col_names)); idx_2_col\n", 370 | "col_2_idx = {v: k for k, v in idx_2_col.items()}" 371 | ] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "execution_count": null, 376 | "metadata": {}, 377 | "outputs": [], 378 | "source": [ 379 | "cat_idxs = [col_2_idx[name] for name in cat_names]\n", 380 | "cont_idxs = [col_2_idx[name] for name in cont_names]\n", 381 | "y_idxs = [col_2_idx[name] for name in [y_names]]\n" 382 | ] 383 | }, 384 | { 385 | "cell_type": "code", 386 | "execution_count": null, 387 | "metadata": {}, 388 | "outputs": [ 389 | { 390 | "data": { 391 | "text/plain": [ 392 | "['age', 'fnlwgt', 'education-num']" 393 | ] 394 | }, 395 | "execution_count": null, 396 | "metadata": {}, 397 | "output_type": "execute_result" 398 | } 399 | ], 400 | "source": [ 401 | "class NumpyFillMissing(TabularProc):\n", 402 | " def __init__(self, fill_strategy=FillStrategy.median, add_col=True, fill_vals=None):\n", 403 | " if fill_vals is None: fill_vals = defaultdict(int)\n", 404 | " store_attr(self, 'fill_strategy,add_col,fill_vals')\n", 405 | " def setups(self, dsets):\n", 406 | " missing = [np.isnan(np.sum(df_np[:,idx])) for idx in cont_idxs]\n", 407 | " self.na_dict = {n:self.fill_strategy(dsets[n])}" 408 | ] 409 | }, 410 | { 411 | "cell_type": "code", 412 | "execution_count": null, 413 | "metadata": {}, 414 | "outputs": [ 415 | { 416 | "data": { 417 | "text/plain": [ 418 | "[False, False, True]" 419 | ] 420 | }, 421 | "execution_count": null, 422 | "metadata": {}, 423 | "output_type": "execute_result" 424 | } 425 | ], 426 | "source": [ 427 | "fs = FillStrategy.median\n", 428 | "missing = [np.isnan(np.sum(df_np[:,idx])) for idx in cont_idxs]; missing" 429 | ] 430 | }, 431 | { 432 | "cell_type": "code", 433 | "execution_count": null, 434 | "metadata": {}, 435 | "outputs": [], 436 | "source": [ 437 | "missing = {}\n", 438 | "for idx in cont_idxs:\n", 439 | " missing[idx] = np.isnan(np.sum(df_np[:,idx]))" 440 | ] 441 | }, 442 | { 443 | "cell_type": "code", 444 | "execution_count": null, 445 | "metadata": {}, 446 | "outputs": [ 447 | { 448 | "data": { 449 | "text/plain": [ 450 | "{0: False, 2: False, 4: True}" 451 | ] 452 | }, 453 | "execution_count": null, 454 | "metadata": {}, 455 | "output_type": "execute_result" 456 | } 457 | ], 458 | "source": [ 459 | "missing" 460 | ] 461 | }, 462 | { 463 | "cell_type": "code", 464 | "execution_count": null, 465 | "metadata": {}, 466 | "outputs": [ 467 | { 468 | "data": { 469 | "text/plain": [ 470 | "{0: False, 2: False, 4: True}" 471 | ] 472 | }, 473 | "execution_count": null, 474 | "metadata": {}, 475 | "output_type": "execute_result" 476 | } 477 | ], 478 | "source": [ 479 | "missing" 480 | ] 481 | }, 482 | { 483 | "cell_type": "code", 484 | "execution_count": null, 485 | "metadata": {}, 486 | "outputs": [ 487 | { 488 | "data": { 489 | "text/plain": [ 490 | "" 491 | ] 492 | }, 493 | "execution_count": null, 494 | "metadata": {}, 495 | "output_type": "execute_result" 496 | } 497 | ], 498 | "source": [ 499 | "fs" 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "metadata": {}, 506 | "outputs": [ 507 | { 508 | "data": { 509 | "text/plain": [ 510 | "dict_keys([0, 2, 4])" 511 | ] 512 | }, 513 | "execution_count": null, 514 | "metadata": {}, 515 | "output_type": "execute_result" 516 | } 517 | ], 518 | "source": [ 519 | "missing.keys()" 520 | ] 521 | }, 522 | { 523 | "cell_type": "code", 524 | "execution_count": null, 525 | "metadata": {}, 526 | "outputs": [ 527 | { 528 | "ename": "AttributeError", 529 | "evalue": "'numpy.ndarray' object has no attribute 'median'", 530 | "output_type": "error", 531 | "traceback": [ 532 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 533 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", 534 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m {n:fs(df_np[:,n], defaultdict(int))\n\u001b[0;32m----> 2\u001b[0;31m for n in missing.keys()}\n\u001b[0m", 535 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m 1\u001b[0m {n:fs(df_np[:,n], defaultdict(int))\n\u001b[0;32m----> 2\u001b[0;31m for n in missing.keys()}\n\u001b[0m", 536 | "\u001b[0;32m~/anaconda3/envs/fastai2/lib/python3.7/site-packages/fastai2/tabular/core.py\u001b[0m in \u001b[0;36mmedian\u001b[0;34m(c, fill)\u001b[0m\n\u001b[1;32m 251\u001b[0m \u001b[0;32mclass\u001b[0m \u001b[0mFillStrategy\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 252\u001b[0m \u001b[0;34m\"Namespace containing the various filling strategies.\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 253\u001b[0;31m \u001b[0;32mdef\u001b[0m \u001b[0mmedian\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mc\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mfill\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mc\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmedian\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 254\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mconstant\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mc\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mfill\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mfill\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 255\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmode\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mc\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mfill\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mc\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdropna\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvalue_counts\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0midxmax\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 537 | "\u001b[0;31mAttributeError\u001b[0m: 'numpy.ndarray' object has no attribute 'median'" 538 | ] 539 | } 540 | ], 541 | "source": [ 542 | "{n:fs(df_np[:,n], defaultdict(int))\n", 543 | "for n in missing.keys()}" 544 | ] 545 | }, 546 | { 547 | "cell_type": "code", 548 | "execution_count": null, 549 | "metadata": {}, 550 | "outputs": [ 551 | { 552 | "ename": "AttributeError", 553 | "evalue": "'numpy.ndarray' object has no attribute 'isnan'", 554 | "output_type": "error", 555 | "traceback": [ 556 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 557 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", 558 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mall\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdf_np\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mcont_idxs\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0maxis\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0misnan\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 559 | "\u001b[0;31mAttributeError\u001b[0m: 'numpy.ndarray' object has no attribute 'isnan'" 560 | ] 561 | } 562 | ], 563 | "source": [ 564 | "np.all(df_np[:,cont_idxs], axis=1).isnan()" 565 | ] 566 | }, 567 | { 568 | "cell_type": "code", 569 | "execution_count": null, 570 | "metadata": {}, 571 | "outputs": [ 572 | { 573 | "data": { 574 | "text/plain": [ 575 | "array([[49, 101320, 12.0],\n", 576 | " [44, 236746, 14.0],\n", 577 | " [38, 96185, nan],\n", 578 | " ...,\n", 579 | " [53, 157069, 12.0],\n", 580 | " [32, 217296, 9.0],\n", 581 | " [26, 182308, 10.0]], dtype=object)" 582 | ] 583 | }, 584 | "execution_count": null, 585 | "metadata": {}, 586 | "output_type": "execute_result" 587 | } 588 | ], 589 | "source": [ 590 | "df_np[:,cont_idxs]" 591 | ] 592 | }, 593 | { 594 | "cell_type": "code", 595 | "execution_count": null, 596 | "metadata": {}, 597 | "outputs": [], 598 | "source": [ 599 | "class TabularNumpy(CollBase, GetAttr, FilteredBase):\n", 600 | " _default, with_cont='procs',True\n", 601 | " def __init__(self, df):\n", 602 | " super().__init__(df)" 603 | ] 604 | }, 605 | { 606 | "cell_type": "code", 607 | "execution_count": null, 608 | "metadata": {}, 609 | "outputs": [], 610 | "source": [ 611 | "t_np = TabularNumpy(df_np)" 612 | ] 613 | }, 614 | { 615 | "cell_type": "code", 616 | "execution_count": null, 617 | "metadata": {}, 618 | "outputs": [ 619 | { 620 | "data": { 621 | "text/plain": [ 622 | "32561" 623 | ] 624 | }, 625 | "execution_count": null, 626 | "metadata": {}, 627 | "output_type": "execute_result" 628 | } 629 | ], 630 | "source": [ 631 | "len(t_np)" 632 | ] 633 | }, 634 | { 635 | "cell_type": "code", 636 | "execution_count": null, 637 | "metadata": {}, 638 | "outputs": [], 639 | "source": [ 640 | "class TabularNumpy(Tabular):\n", 641 | " _default, with_cont='procs',True\n", 642 | " def __init__(self, df, procs=None, cat_names=None, cont_names=None, y_names=None, y_block=None, splits=None,\n", 643 | " do_setup=True, device=None, inplace=False, reduce_memory=True):\n", 644 | " self.df = df[cat_names+cont_names+y_names].to_numpy()\n", 645 | " self.idx_2_col = dict(zip(range(len(df.columns)), df.columns))\n", 646 | " self.col_2_idx = {v: k for k, v in self.idx_2_col.items()}\n", 647 | " " 648 | ] 649 | }, 650 | { 651 | "cell_type": "code", 652 | "execution_count": null, 653 | "metadata": {}, 654 | "outputs": [], 655 | "source": [ 656 | "class Tabular(CollBase, GetAttr, FilteredBase):\n", 657 | " \"A `DataFrame` wrapper that knows which cols are cont/cat/y, and returns rows in `__getitem__`\"\n", 658 | " _default,with_cont='procs',True\n", 659 | " def __init__(self, df, procs=None, cat_names=None, cont_names=None, y_names=None, y_block=None, splits=None,\n", 660 | " do_setup=True, device=None, inplace=False, reduce_memory=True):\n", 661 | " if inplace and splits is not None and pd.options.mode.chained_assignment is not None:\n", 662 | " warn(\"Using inplace with splits will trigger a pandas error. Set `pd.options.mode.chained_assignment=None` to avoid it.\")\n", 663 | " if not inplace: df = df.copy()\n", 664 | " if splits is not None: df = df.iloc[sum(splits, [])]\n", 665 | " self.dataloaders = delegates(self._dl_type.__init__)(self.dataloaders)\n", 666 | " super().__init__(df)\n", 667 | "\n", 668 | " self.y_names,self.device = L(y_names),device\n", 669 | " if y_block is None and self.y_names:\n", 670 | " # Make ys categorical if they're not numeric\n", 671 | " ys = df[self.y_names]\n", 672 | " if len(ys.select_dtypes(include='number').columns)!=len(ys.columns): y_block = CategoryBlock()\n", 673 | " else: y_block = RegressionBlock()\n", 674 | " if y_block is not None and do_setup:\n", 675 | " if callable(y_block): y_block = y_block()\n", 676 | " procs = L(procs) + y_block.type_tfms\n", 677 | " self.cat_names,self.cont_names,self.procs = L(cat_names),L(cont_names),Pipeline(procs)\n", 678 | " self.split = len(df) if splits is None else len(splits[0])\n", 679 | " if reduce_memory:\n", 680 | " if len(self.cat_names) > 0: self.reduce_cats()\n", 681 | " if len(self.cont_names) > 0: self.reduce_conts()\n", 682 | " if do_setup: self.setup()\n", 683 | "\n", 684 | " def new(self, df):\n", 685 | " return type(self)(df, do_setup=False, reduce_memory=False, y_block=TransformBlock(),\n", 686 | " **attrdict(self, 'procs','cat_names','cont_names','y_names', 'device'))\n", 687 | "\n", 688 | " def subset(self, i): return self.new(self.items[slice(0,self.split) if i==0 else slice(self.split,len(self))])\n", 689 | " def copy(self): self.items = self.items.copy(); return self\n", 690 | " def decode(self): return self.procs.decode(self)\n", 691 | " def decode_row(self, row): return self.new(pd.DataFrame(row).T).decode().items.iloc[0]\n", 692 | " def reduce_cats(self): self.train[self.cat_names] = self.train[self.cat_names].astype('category')\n", 693 | " def reduce_conts(self): self[self.cont_names] = self[self.cont_names].astype(np.float32)\n", 694 | " def show(self, max_n=10, **kwargs): display_df(self.new(self.all_cols[:max_n]).decode().items)\n", 695 | " def setup(self): self.procs.setup(self)\n", 696 | " def process(self): self.procs(self)\n", 697 | " def loc(self): return self.items.loc\n", 698 | " def iloc(self): return _TabIloc(self)\n", 699 | " def targ(self): return self.items[self.y_names]\n", 700 | " def x_names (self): return self.cat_names + self.cont_names\n", 701 | " def n_subsets(self): return 2\n", 702 | " def y(self): return self[self.y_names[0]]\n", 703 | " def new_empty(self): return self.new(pd.DataFrame({}, columns=self.items.columns))\n", 704 | " def to_device(self, d=None):\n", 705 | " self.device = d\n", 706 | " return self\n", 707 | "\n", 708 | " def all_col_names (self):\n", 709 | " ys = [n for n in self.y_names if n in self.items.columns]\n", 710 | " return self.x_names + self.y_names if len(ys) == len(self.y_names) else self.x_names" 711 | ] 712 | }, 713 | { 714 | "cell_type": "code", 715 | "execution_count": null, 716 | "metadata": {}, 717 | "outputs": [], 718 | "source": [] 719 | } 720 | ], 721 | "metadata": { 722 | "kernelspec": { 723 | "display_name": "Python 3", 724 | "language": "python", 725 | "name": "python3" 726 | } 727 | }, 728 | "nbformat": 4, 729 | "nbformat_minor": 2 730 | } 731 | -------------------------------------------------------------------------------- /01_Tensor.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "# default_exp tensor" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "# 01_Tensor\n", 17 | "\n", 18 | "> Building an example `Dataset` and `DataLoader` with PyTorch `Tensors`" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "#hide\n", 28 | "from nbdev.showdoc import *" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "#export\n", 38 | "from fastai2.tabular.all import *" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": {}, 44 | "source": [ 45 | "For our data we'll first utilize `TabularPandas` for pre-processing, as there has not been any modifications to `TabularPandas` yet." 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "path = untar_data(URLs.ADULT_SAMPLE)\n", 55 | "df = pd.read_csv(path/'adult.csv')" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']\n", 65 | "cont_names = ['age', 'fnlwgt', 'education-num']\n", 66 | "procs = [Categorify, FillMissing, Normalize]\n", 67 | "y_names = 'salary'\n", 68 | "splits = RandomSplitter()(range_of(df))" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "to = TabularPandas(df, procs=procs, cat_names=cat_names, cont_names=cont_names,\n", 78 | " y_names=y_names, splits=splits)" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "# TensorDataLoaders" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "#export\n", 95 | "class TensorDataset():\n", 96 | " \"A `Tensor` dataset object from `TabularPandas`\"\n", 97 | " def __init__(self, to:TabularPandas, device='cpu'):\n", 98 | " self.cats = tensor(to.cats.to_numpy()).to(device=device, dtype=torch.long)\n", 99 | " self.conts = tensor(to.conts.to_numpy()).to(device=device, dtype=torch.float32)\n", 100 | " self.ys = tensor(to.ys.to_numpy()).to(device)\n", 101 | " self.device = device\n", 102 | " \n", 103 | " def __getitem__(self, idx): \n", 104 | " idx = idx[0]\n", 105 | " return self.cats[idx:idx+self.bs], self.conts[idx:idx+self.bs], self.ys[idx:idx+self.bs]\n", 106 | " \n", 107 | " def __len__(self): return len(self.cats)" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [ 115 | { 116 | "data": { 117 | "text/markdown": [ 118 | "

class TensorDataset[source]

\n", 119 | "\n", 120 | "> TensorDataset(**`to`**:`TabularPandas`, **`device`**=*`'cpu'`*)\n", 121 | "\n", 122 | "A `Tensor` dataset object from `TabularPandas`" 123 | ], 124 | "text/plain": [ 125 | "" 126 | ] 127 | }, 128 | "metadata": {}, 129 | "output_type": "display_data" 130 | } 131 | ], 132 | "source": [ 133 | "show_doc(TensorDataset)" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": {}, 140 | "outputs": [], 141 | "source": [ 142 | "#hide\n", 143 | "ds = TensorDataset(to)" 144 | ] 145 | }, 146 | { 147 | "cell_type": "code", 148 | "execution_count": null, 149 | "metadata": {}, 150 | "outputs": [], 151 | "source": [ 152 | "#hide\n", 153 | "ds.bs = 3\n", 154 | "a,b,c = ds[[0]]\n", 155 | "test_eq(len(a), 3)" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": null, 161 | "metadata": {}, 162 | "outputs": [], 163 | "source": [ 164 | "#export\n", 165 | "class TensorDataLoader(DataLoader):\n", 166 | " \"A `DataLoader` for a `TensorDataset`\"\n", 167 | " def __init__(self, dataset, bs=1, **kwargs):\n", 168 | " super().__init__(dataset, bs=bs, **kwargs)\n", 169 | " self.dataset.bs = bs\n", 170 | " \n", 171 | " def create_item(self, s): return s\n", 172 | " \n", 173 | " def create_batch(self, b):\n", 174 | " cat, cont, y = self.dataset[b]\n", 175 | " return cat.to(self.device), cont.to(self.device), y.to(self.device)" 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": null, 181 | "metadata": {}, 182 | "outputs": [ 183 | { 184 | "data": { 185 | "text/markdown": [ 186 | "

class TensorDataLoader[source]

\n", 187 | "\n", 188 | "> TensorDataLoader(**`dataset`**, **`bs`**=*`1`*, **\\*\\*`kwargs`**) :: `DataLoader`\n", 189 | "\n", 190 | "A `DataLoader` for a [`TensorDataset`](/fastai2_tabular_hybrid/Tensor#TensorDataset)" 191 | ], 192 | "text/plain": [ 193 | "" 194 | ] 195 | }, 196 | "metadata": {}, 197 | "output_type": "display_data" 198 | } 199 | ], 200 | "source": [ 201 | "show_doc(TensorDataLoader)" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": null, 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "#hide\n", 211 | "ds = TensorDataset(to)\n", 212 | "dl = TensorDataLoader(ds, bs=3)\n", 213 | "batch = next(iter(dl))\n", 214 | "test_eq(len(dl), len(ds)//3+1)" 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": null, 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [ 223 | "#export\n", 224 | "@patch\n", 225 | "def shuffle_fn(x:TensorDataLoader):\n", 226 | " \"Shuffle the interior dataset\"\n", 227 | " rng = torch.randperm(len(x.dataset))\n", 228 | " x.dataset.cats = x.dataset.cats[rng]\n", 229 | " x.dataset.conts = x.dataset.conts[rng]\n", 230 | " x.dataset.ys = x.dataset.ys[rng]" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": null, 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "#export\n", 240 | "@patch\n", 241 | "def get_idxs(x:TensorDataLoader):\n", 242 | " \"Get index's to select\"\n", 243 | " idxs = Inf.count if x.indexed else Inf.nones\n", 244 | " if x.n is not None: idxs = list(range(len(x.dataset)))\n", 245 | " if x.shuffle: x.shuffle_fn()\n", 246 | " return idxs" 247 | ] 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "metadata": {}, 252 | "source": [ 253 | "Compare performance between fastai DataLoader, and both CPU and GPU TensorDataLoader." 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "metadata": {}, 260 | "outputs": [], 261 | "source": [ 262 | "train_ds = TensorDataset(to.train)\n", 263 | "valid_ds = TensorDataset(to.valid)" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": null, 269 | "metadata": {}, 270 | "outputs": [], 271 | "source": [ 272 | "train_dl = TensorDataLoader(train_ds, bs=64, shuffle=True, drop_last=True)\n", 273 | "valid_dl = TensorDataLoader(valid_ds, bs=64)" 274 | ] 275 | }, 276 | { 277 | "cell_type": "code", 278 | "execution_count": null, 279 | "metadata": {}, 280 | "outputs": [], 281 | "source": [ 282 | "train_ds_gpu = TensorDataset(to.train, 'cuda')\n", 283 | "valid_ds_gpu = TensorDataset(to.valid, 'cuda')" 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": null, 289 | "metadata": {}, 290 | "outputs": [], 291 | "source": [ 292 | "train_dl_gpu = TensorDataLoader(train_ds_gpu, bs=64, shuffle=True, drop_last=True, device='cuda')\n", 293 | "valid_dl_gpu = TensorDataLoader(valid_ds_gpu, bs=64, device='cuda')" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": null, 299 | "metadata": {}, 300 | "outputs": [], 301 | "source": [ 302 | "dls = to.dataloaders(bs=64)" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": null, 308 | "metadata": {}, 309 | "outputs": [ 310 | { 311 | "name": "stdout", 312 | "output_type": "stream", 313 | "text": [ 314 | "28.3 ms ± 62.5 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 315 | ] 316 | } 317 | ], 318 | "source": [ 319 | "%%timeit\n", 320 | "# Tensor CPU\n", 321 | "for _ in train_dl: pass" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": null, 327 | "metadata": {}, 328 | "outputs": [ 329 | { 330 | "name": "stdout", 331 | "output_type": "stream", 332 | "text": [ 333 | "34.1 ms ± 31.6 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 334 | ] 335 | } 336 | ], 337 | "source": [ 338 | "%%timeit\n", 339 | "# Tensor GPU\n", 340 | "for _ in train_dl_gpu: pass" 341 | ] 342 | }, 343 | { 344 | "cell_type": "code", 345 | "execution_count": null, 346 | "metadata": {}, 347 | "outputs": [ 348 | { 349 | "name": "stdout", 350 | "output_type": "stream", 351 | "text": [ 352 | "1.1 s ± 2.06 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 353 | ] 354 | } 355 | ], 356 | "source": [ 357 | "%%timeit\n", 358 | "# fastai\n", 359 | "for _ in dls[0]: pass" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": null, 365 | "metadata": {}, 366 | "outputs": [ 367 | { 368 | "name": "stdout", 369 | "output_type": "stream", 370 | "text": [ 371 | "6.63 ms ± 4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" 372 | ] 373 | } 374 | ], 375 | "source": [ 376 | "%%timeit\n", 377 | "# Tensor CPU\n", 378 | "for _ in valid_dl: pass" 379 | ] 380 | }, 381 | { 382 | "cell_type": "code", 383 | "execution_count": null, 384 | "metadata": {}, 385 | "outputs": [ 386 | { 387 | "name": "stdout", 388 | "output_type": "stream", 389 | "text": [ 390 | "8.35 ms ± 3.54 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" 391 | ] 392 | } 393 | ], 394 | "source": [ 395 | "%%timeit\n", 396 | "# Tensor GPU\n", 397 | "for _ in valid_dl_gpu: pass" 398 | ] 399 | }, 400 | { 401 | "cell_type": "code", 402 | "execution_count": null, 403 | "metadata": {}, 404 | "outputs": [ 405 | { 406 | "name": "stdout", 407 | "output_type": "stream", 408 | "text": [ 409 | "271 ms ± 658 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 410 | ] 411 | } 412 | ], 413 | "source": [ 414 | "%%timeit\n", 415 | "# fastai\n", 416 | "for _ in dls[1]: pass" 417 | ] 418 | }, 419 | { 420 | "cell_type": "code", 421 | "execution_count": null, 422 | "metadata": {}, 423 | "outputs": [], 424 | "source": [ 425 | "# export\n", 426 | "class TensorDataLoaders(DataLoaders):\n", 427 | " \"A set of two `TensorDataLoader` from a `TabularPandas` object\"\n", 428 | " def __init__(self, to:TabularPandas, bs=64, val_bs=None, shuffle_train=True,\n", 429 | " device='cpu', dataset_device=None, **kwargs):\n", 430 | " dataset_device = device if dataset_device is None else dataset_device\n", 431 | " train_ds = TensorDataset(to.train, dataset_device)\n", 432 | " valid_ds = TensorDataset(to.valid, dataset_device)\n", 433 | " val_bs = bs*2 if val_bs is None else val_bs\n", 434 | " train = TensorDataLoader(train_ds, bs=bs, shuffle=shuffle_train, device=device, drop_last=True, **kwargs)\n", 435 | " valid = TensorDataLoader(valid_ds, bs=val_bs, shuffle=False, device=device, **kwargs)\n", 436 | " super().__init__(train, valid, device=device, **kwargs)" 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "metadata": {}, 443 | "outputs": [ 444 | { 445 | "data": { 446 | "text/markdown": [ 447 | "

class TensorDataLoaders[source]

\n", 448 | "\n", 449 | "> TensorDataLoaders(**`to`**:`TabularPandas`, **`bs`**=*`64`*, **`val_bs`**=*`None`*, **`shuffle_train`**=*`True`*, **`device`**=*`'cpu'`*, **`dataset_device`**=*`None`*, **\\*\\*`kwargs`**) :: `DataLoaders`\n", 450 | "\n", 451 | "A set of two [`TensorDataLoader`](/fastai2_tabular_hybrid/Tensor#TensorDataLoader) from a `TabularPandas` object" 452 | ], 453 | "text/plain": [ 454 | "" 455 | ] 456 | }, 457 | "metadata": {}, 458 | "output_type": "display_data" 459 | } 460 | ], 461 | "source": [ 462 | "show_doc(TensorDataLoaders)" 463 | ] 464 | }, 465 | { 466 | "cell_type": "markdown", 467 | "metadata": {}, 468 | "source": [ 469 | "`TensorDataLoaders` show a 20x speedup compared to `TabularPandas`. In general this `DataLoader` will set up your entire dataset on either the GPU or CPU based on `device`. Use `CPU` if the dataset will not fit into memory" 470 | ] 471 | }, 472 | { 473 | "cell_type": "markdown", 474 | "metadata": {}, 475 | "source": [ 476 | "Compare performance between DataLoaders when batching to GPU." 477 | ] 478 | }, 479 | { 480 | "cell_type": "code", 481 | "execution_count": null, 482 | "metadata": {}, 483 | "outputs": [], 484 | "source": [ 485 | "dls = TensorDataLoaders(to, dataset_device='cpu', device='cuda')" 486 | ] 487 | }, 488 | { 489 | "cell_type": "code", 490 | "execution_count": null, 491 | "metadata": {}, 492 | "outputs": [ 493 | { 494 | "name": "stdout", 495 | "output_type": "stream", 496 | "text": [ 497 | "52.6 ms ± 57.9 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 498 | ] 499 | } 500 | ], 501 | "source": [ 502 | "%%timeit\n", 503 | "# Tensor CPU to GPU\n", 504 | "for _ in dls[0]: pass" 505 | ] 506 | }, 507 | { 508 | "cell_type": "code", 509 | "execution_count": null, 510 | "metadata": {}, 511 | "outputs": [], 512 | "source": [ 513 | "dls = TensorDataLoaders(to, device='cuda')" 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "execution_count": null, 519 | "metadata": {}, 520 | "outputs": [ 521 | { 522 | "name": "stdout", 523 | "output_type": "stream", 524 | "text": [ 525 | "33.8 ms ± 49.7 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 526 | ] 527 | } 528 | ], 529 | "source": [ 530 | "%%timeit\n", 531 | "# Tensor GPU to GPU\n", 532 | "for _ in dls[0]: pass" 533 | ] 534 | }, 535 | { 536 | "cell_type": "code", 537 | "execution_count": null, 538 | "metadata": {}, 539 | "outputs": [], 540 | "source": [ 541 | "dls = to.dataloaders(bs=64, device='cuda')" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "execution_count": null, 547 | "metadata": {}, 548 | "outputs": [ 549 | { 550 | "name": "stdout", 551 | "output_type": "stream", 552 | "text": [ 553 | "1.11 s ± 441 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 554 | ] 555 | } 556 | ], 557 | "source": [ 558 | "%%timeit\n", 559 | "# fastai to GPU\n", 560 | "for _ in dls[0]: pass" 561 | ] 562 | }, 563 | { 564 | "cell_type": "code", 565 | "execution_count": null, 566 | "metadata": {}, 567 | "outputs": [], 568 | "source": [] 569 | } 570 | ], 571 | "metadata": { 572 | "kernelspec": { 573 | "display_name": "Python 3", 574 | "language": "python", 575 | "name": "python3" 576 | } 577 | }, 578 | "nbformat": 4, 579 | "nbformat_minor": 2 580 | } 581 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | ## How to get started 4 | 5 | Before anything else, please install the git hooks that run automatic scripts during each commit and merge to strip the notebooks of superfluous metadata (and avoid merge conflicts). After cloning the repository, run the following command inside it: 6 | ``` 7 | nbdev_install_git_hooks 8 | ``` 9 | 10 | ## Did you find a bug? 11 | 12 | * Ensure the bug was not already reported by searching on GitHub under Issues. 13 | * If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring. 14 | * Be sure to add the complete error messages. 15 | 16 | #### Did you write a patch that fixes a bug? 17 | 18 | * Open a new GitHub pull request with the patch. 19 | * Ensure that your PR includes a test that fails without your patch, and pass with it. 20 | * Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. 21 | 22 | ## PR submission guidelines 23 | 24 | * Keep each PR focused. While it's more convenient, do not combine several unrelated fixes together. Create as many branches as needing to keep each PR focused. 25 | * Do not mix style changes/fixes with "functional" changes. It's very difficult to review such PRs and it most likely get rejected. 26 | * Do not add/remove vertical whitespace. Preserve the original style of the file you edit as much as you can. 27 | * Do not turn an already submitted PR into your development playground. If after you submitted PR, you discovered that more work is needed - close the PR, do the required work and then submit a new PR. Otherwise each of your commits requires attention from maintainers of the project. 28 | * If, however, you submitted a PR and received a request for changes, you should proceed with commits inside that PR, so that the maintainer can see the incremental fixes and won't need to review the whole PR again. In the exception case where you realize it'll take many many commits to complete the requests, then it's probably best to close the PR, do the work and then submit it again. Use common sense where you'd choose one way over another. 29 | 30 | ## Do you want to contribute to the documentation? 31 | 32 | * Docs are automatically created from the notebooks in the nbs folder. 33 | 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include settings.ini 2 | include LICENSE 3 | include CONTRIBUTING.md 4 | include README.md 5 | recursive-exclude * __pycache__ 6 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SRC = $(wildcard ./*.ipynb) 2 | 3 | all: fastai2_tabular_hybrid docs 4 | 5 | fastai2_tabular_hybrid: $(SRC) 6 | nbdev_build_lib 7 | touch fastai2_tabular_hybrid 8 | 9 | docs_serve: docs 10 | cd docs && bundle exec jekyll serve 11 | 12 | docs: $(SRC) 13 | nbdev_build_docs 14 | touch docs 15 | 16 | test: 17 | nbdev_test_nbs 18 | 19 | release: pypi 20 | nbdev_bump_version 21 | 22 | pypi: dist 23 | twine upload --repository pypi dist/* 24 | 25 | dist: clean 26 | python setup.py sdist bdist_wheel 27 | 28 | clean: 29 | rm -rf dist -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fastai2_tabular_hybrid 2 | > Hybrid approaches to supporting more datatypes with fastai2 tabular 3 | 4 | # Contributers: 5 | [![](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/images/0)](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/links/0)[![](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/images/1)](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/links/1)[![](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/images/2)](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/links/2)[![](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/images/3)](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/links/3)[![](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/images/4)](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/links/4)[![](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/images/5)](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/links/5)[![](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/images/6)](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/links/6)[![](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/images/7)](https://sourcerer.io/fame/muellerzr/muellerzr/fastai2_tabular_hybrid/links/7) 6 | 7 | # DataLoaders: 8 | 9 | * **NumpyDataloader**: uses NumPy as the backend to speed up performance up to ~8X fast.ai’s TabularPandas DataLoader. 10 | * **TensorDataloader**: uses PyTorch Tensor as the backend to speed up performance up to ~20X fast.ai’s TabularPandas DataLoader if entire Dataset can fit into GPU memory. 11 | 12 | # Contributers: 13 | 14 | * Zachary Mueller 15 | * Benjamin Warner 16 | 17 | # Directions for Contributing: 18 | 19 | 1. Fork this repository into your GitHub Account 20 | 2. Ensure that `nbdev` is installed on your system 21 | 3. Make any changes and ensure that you run the following **before** commiting: 22 | * `nbdev_build_lib` 23 | * `nbdev_clean_nbs` 24 | 4. Open a Pull Request with the library, and choose "From fork" to open one with the main repository. 25 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | _site/ 2 | -------------------------------------------------------------------------------- /docs/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem 'github-pages', group: :jekyll_plugins 4 | 5 | 6 | # Added at 2019-11-25 10:11:40 -0800 by jhoward: 7 | gem "jekyll", "~> 3.7" 8 | -------------------------------------------------------------------------------- /docs/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | activesupport (4.2.11.1) 5 | i18n (~> 0.7) 6 | minitest (~> 5.1) 7 | thread_safe (~> 0.3, >= 0.3.4) 8 | tzinfo (~> 1.1) 9 | addressable (2.7.0) 10 | public_suffix (>= 2.0.2, < 5.0) 11 | coffee-script (2.4.1) 12 | coffee-script-source 13 | execjs 14 | coffee-script-source (1.11.1) 15 | colorator (1.1.0) 16 | commonmarker (0.17.13) 17 | ruby-enum (~> 0.5) 18 | concurrent-ruby (1.1.5) 19 | dnsruby (1.61.3) 20 | addressable (~> 2.5) 21 | em-websocket (0.5.1) 22 | eventmachine (>= 0.12.9) 23 | http_parser.rb (~> 0.6.0) 24 | ethon (0.12.0) 25 | ffi (>= 1.3.0) 26 | eventmachine (1.2.7) 27 | execjs (2.7.0) 28 | faraday (0.17.0) 29 | multipart-post (>= 1.2, < 3) 30 | ffi (1.11.3) 31 | forwardable-extended (2.6.0) 32 | gemoji (3.0.1) 33 | github-pages (202) 34 | activesupport (= 4.2.11.1) 35 | github-pages-health-check (= 1.16.1) 36 | jekyll (= 3.8.5) 37 | jekyll-avatar (= 0.6.0) 38 | jekyll-coffeescript (= 1.1.1) 39 | jekyll-commonmark-ghpages (= 0.1.6) 40 | jekyll-default-layout (= 0.1.4) 41 | jekyll-feed (= 0.11.0) 42 | jekyll-gist (= 1.5.0) 43 | jekyll-github-metadata (= 2.12.1) 44 | jekyll-mentions (= 1.4.1) 45 | jekyll-optional-front-matter (= 0.3.0) 46 | jekyll-paginate (= 1.1.0) 47 | jekyll-readme-index (= 0.2.0) 48 | jekyll-redirect-from (= 0.14.0) 49 | jekyll-relative-links (= 0.6.0) 50 | jekyll-remote-theme (= 0.4.0) 51 | jekyll-sass-converter (= 1.5.2) 52 | jekyll-seo-tag (= 2.5.0) 53 | jekyll-sitemap (= 1.2.0) 54 | jekyll-swiss (= 0.4.0) 55 | jekyll-theme-architect (= 0.1.1) 56 | jekyll-theme-cayman (= 0.1.1) 57 | jekyll-theme-dinky (= 0.1.1) 58 | jekyll-theme-hacker (= 0.1.1) 59 | jekyll-theme-leap-day (= 0.1.1) 60 | jekyll-theme-merlot (= 0.1.1) 61 | jekyll-theme-midnight (= 0.1.1) 62 | jekyll-theme-minimal (= 0.1.1) 63 | jekyll-theme-modernist (= 0.1.1) 64 | jekyll-theme-primer (= 0.5.3) 65 | jekyll-theme-slate (= 0.1.1) 66 | jekyll-theme-tactile (= 0.1.1) 67 | jekyll-theme-time-machine (= 0.1.1) 68 | jekyll-titles-from-headings (= 0.5.1) 69 | jemoji (= 0.10.2) 70 | kramdown (= 1.17.0) 71 | liquid (= 4.0.0) 72 | listen (= 3.1.5) 73 | mercenary (~> 0.3) 74 | minima (= 2.5.0) 75 | nokogiri (>= 1.10.4, < 2.0) 76 | rouge (= 3.11.0) 77 | terminal-table (~> 1.4) 78 | github-pages-health-check (1.16.1) 79 | addressable (~> 2.3) 80 | dnsruby (~> 1.60) 81 | octokit (~> 4.0) 82 | public_suffix (~> 3.0) 83 | typhoeus (~> 1.3) 84 | html-pipeline (2.12.2) 85 | activesupport (>= 2) 86 | nokogiri (>= 1.4) 87 | http_parser.rb (0.6.0) 88 | i18n (0.9.5) 89 | concurrent-ruby (~> 1.0) 90 | jekyll (3.8.5) 91 | addressable (~> 2.4) 92 | colorator (~> 1.0) 93 | em-websocket (~> 0.5) 94 | i18n (~> 0.7) 95 | jekyll-sass-converter (~> 1.0) 96 | jekyll-watch (~> 2.0) 97 | kramdown (~> 1.14) 98 | liquid (~> 4.0) 99 | mercenary (~> 0.3.3) 100 | pathutil (~> 0.9) 101 | rouge (>= 1.7, < 4) 102 | safe_yaml (~> 1.0) 103 | jekyll-avatar (0.6.0) 104 | jekyll (~> 3.0) 105 | jekyll-coffeescript (1.1.1) 106 | coffee-script (~> 2.2) 107 | coffee-script-source (~> 1.11.1) 108 | jekyll-commonmark (1.3.1) 109 | commonmarker (~> 0.14) 110 | jekyll (>= 3.7, < 5.0) 111 | jekyll-commonmark-ghpages (0.1.6) 112 | commonmarker (~> 0.17.6) 113 | jekyll-commonmark (~> 1.2) 114 | rouge (>= 2.0, < 4.0) 115 | jekyll-default-layout (0.1.4) 116 | jekyll (~> 3.0) 117 | jekyll-feed (0.11.0) 118 | jekyll (~> 3.3) 119 | jekyll-gist (1.5.0) 120 | octokit (~> 4.2) 121 | jekyll-github-metadata (2.12.1) 122 | jekyll (~> 3.4) 123 | octokit (~> 4.0, != 4.4.0) 124 | jekyll-mentions (1.4.1) 125 | html-pipeline (~> 2.3) 126 | jekyll (~> 3.0) 127 | jekyll-optional-front-matter (0.3.0) 128 | jekyll (~> 3.0) 129 | jekyll-paginate (1.1.0) 130 | jekyll-readme-index (0.2.0) 131 | jekyll (~> 3.0) 132 | jekyll-redirect-from (0.14.0) 133 | jekyll (~> 3.3) 134 | jekyll-relative-links (0.6.0) 135 | jekyll (~> 3.3) 136 | jekyll-remote-theme (0.4.0) 137 | addressable (~> 2.0) 138 | jekyll (~> 3.5) 139 | rubyzip (>= 1.2.1, < 3.0) 140 | jekyll-sass-converter (1.5.2) 141 | sass (~> 3.4) 142 | jekyll-seo-tag (2.5.0) 143 | jekyll (~> 3.3) 144 | jekyll-sitemap (1.2.0) 145 | jekyll (~> 3.3) 146 | jekyll-swiss (0.4.0) 147 | jekyll-theme-architect (0.1.1) 148 | jekyll (~> 3.5) 149 | jekyll-seo-tag (~> 2.0) 150 | jekyll-theme-cayman (0.1.1) 151 | jekyll (~> 3.5) 152 | jekyll-seo-tag (~> 2.0) 153 | jekyll-theme-dinky (0.1.1) 154 | jekyll (~> 3.5) 155 | jekyll-seo-tag (~> 2.0) 156 | jekyll-theme-hacker (0.1.1) 157 | jekyll (~> 3.5) 158 | jekyll-seo-tag (~> 2.0) 159 | jekyll-theme-leap-day (0.1.1) 160 | jekyll (~> 3.5) 161 | jekyll-seo-tag (~> 2.0) 162 | jekyll-theme-merlot (0.1.1) 163 | jekyll (~> 3.5) 164 | jekyll-seo-tag (~> 2.0) 165 | jekyll-theme-midnight (0.1.1) 166 | jekyll (~> 3.5) 167 | jekyll-seo-tag (~> 2.0) 168 | jekyll-theme-minimal (0.1.1) 169 | jekyll (~> 3.5) 170 | jekyll-seo-tag (~> 2.0) 171 | jekyll-theme-modernist (0.1.1) 172 | jekyll (~> 3.5) 173 | jekyll-seo-tag (~> 2.0) 174 | jekyll-theme-primer (0.5.3) 175 | jekyll (~> 3.5) 176 | jekyll-github-metadata (~> 2.9) 177 | jekyll-seo-tag (~> 2.0) 178 | jekyll-theme-slate (0.1.1) 179 | jekyll (~> 3.5) 180 | jekyll-seo-tag (~> 2.0) 181 | jekyll-theme-tactile (0.1.1) 182 | jekyll (~> 3.5) 183 | jekyll-seo-tag (~> 2.0) 184 | jekyll-theme-time-machine (0.1.1) 185 | jekyll (~> 3.5) 186 | jekyll-seo-tag (~> 2.0) 187 | jekyll-titles-from-headings (0.5.1) 188 | jekyll (~> 3.3) 189 | jekyll-watch (2.2.1) 190 | listen (~> 3.0) 191 | jemoji (0.10.2) 192 | gemoji (~> 3.0) 193 | html-pipeline (~> 2.2) 194 | jekyll (~> 3.0) 195 | kramdown (1.17.0) 196 | liquid (4.0.0) 197 | listen (3.1.5) 198 | rb-fsevent (~> 0.9, >= 0.9.4) 199 | rb-inotify (~> 0.9, >= 0.9.7) 200 | ruby_dep (~> 1.2) 201 | mercenary (0.3.6) 202 | mini_portile2 (2.6.1) 203 | minima (2.5.0) 204 | jekyll (~> 3.5) 205 | jekyll-feed (~> 0.9) 206 | jekyll-seo-tag (~> 2.1) 207 | minitest (5.13.0) 208 | multipart-post (2.1.1) 209 | nokogiri (1.12.5) 210 | mini_portile2 (~> 2.6.1) 211 | racc (~> 1.4) 212 | octokit (4.14.0) 213 | sawyer (~> 0.8.0, >= 0.5.3) 214 | pathutil (0.16.2) 215 | forwardable-extended (~> 2.6) 216 | public_suffix (3.1.1) 217 | racc (1.5.2) 218 | rb-fsevent (0.10.3) 219 | rb-inotify (0.10.0) 220 | ffi (~> 1.0) 221 | rouge (3.11.0) 222 | ruby-enum (0.7.2) 223 | i18n 224 | ruby_dep (1.5.0) 225 | rubyzip (2.0.0) 226 | safe_yaml (1.0.5) 227 | sass (3.7.4) 228 | sass-listen (~> 4.0.0) 229 | sass-listen (4.0.0) 230 | rb-fsevent (~> 0.9, >= 0.9.4) 231 | rb-inotify (~> 0.9, >= 0.9.7) 232 | sawyer (0.8.2) 233 | addressable (>= 2.3.5) 234 | faraday (> 0.8, < 2.0) 235 | terminal-table (1.8.0) 236 | unicode-display_width (~> 1.1, >= 1.1.1) 237 | thread_safe (0.3.6) 238 | typhoeus (1.3.1) 239 | ethon (>= 0.9.0) 240 | tzinfo (1.2.5) 241 | thread_safe (~> 0.1) 242 | unicode-display_width (1.6.0) 243 | 244 | PLATFORMS 245 | ruby 246 | 247 | DEPENDENCIES 248 | github-pages 249 | jekyll (~> 3.7) 250 | 251 | BUNDLED WITH 252 | 2.0.2 253 | -------------------------------------------------------------------------------- /docs/Numpy.html: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | title: 00_Numpy 4 | 5 | keywords: fastai 6 | sidebar: home_sidebar 7 | 8 | summary: "Building an example `Dataset` and `DataLoader` with `NumPy`" 9 | description: "Building an example `Dataset` and `DataLoader` with `NumPy`" 10 | --- 11 | 20 | 21 |
22 | 23 | {% raw %} 24 | 25 |
26 | 27 |
28 | {% endraw %} 29 | 30 | {% raw %} 31 | 32 |
33 | 34 |
35 | {% endraw %} 36 | 37 |
38 |
39 |

For our data we'll first utilize TabularPandas for pre-processing. One potential is to use TabularPandas for pre-processing only, or to integrate NumPy directly into it

40 | 41 |
42 |
43 |
44 | {% raw %} 45 | 46 |
47 |
48 | 49 |
50 |
51 |
path = untar_data(URLs.ADULT_SAMPLE)
 52 | df = pd.read_csv(path/'adult.csv')
 53 | 
54 | 55 |
56 |
57 |
58 | 59 |
60 | {% endraw %} 61 | 62 | {% raw %} 63 | 64 |
65 |
66 | 67 |
68 |
69 |
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']
 70 | cont_names = ['age', 'fnlwgt', 'education-num']
 71 | procs = [Categorify, FillMissing, Normalize]
 72 | y_names = 'salary'
 73 | splits = RandomSplitter()(range_of(df))
 74 | 
75 | 76 |
77 |
78 |
79 | 80 |
81 | {% endraw %} 82 | 83 |
84 |
85 |

We'll still build our regular TabularPandas, as we haven't done any NumPy modifications yet

86 | 87 |
88 |
89 |
90 | {% raw %} 91 | 92 |
93 |
94 | 95 |
96 |
97 |
to = TabularPandas(df, procs=procs, cat_names=cat_names, cont_names=cont_names,
 98 |                    y_names=y_names, splits=splits)
 99 | 
100 | 101 |
102 |
103 |
104 | 105 |
106 | {% endraw %} 107 | 108 | {% raw %} 109 | 110 |
111 | 112 |
113 | {% endraw %} 114 | 115 | {% raw %} 116 | 117 |
118 | 119 |
120 |
121 | 122 |
123 | 124 | 125 |
126 |

class NumpyDataset[source]

NumpyDataset(to:TabularPandas)

127 |
128 |

A Numpy dataset object from TabularPandas

129 | 130 |
131 | 132 |
133 | 134 |
135 |
136 | 137 |
138 | {% endraw %} 139 | 140 | {% raw %} 141 | 142 |
143 |
144 | 145 |
146 |
147 |
ds = NumpyDataset(to)
148 | 
149 | 150 |
151 |
152 |
153 | 154 |
155 | {% endraw %} 156 | 157 | {% raw %} 158 | 159 |
160 |
161 | 162 |
163 |
164 |
ds.bs = 3
165 | 
166 | 167 |
168 |
169 |
170 | 171 |
172 | {% endraw %} 173 | 174 | {% raw %} 175 | 176 |
177 |
178 | 179 |
180 |
181 |
a,b,c = ds[[0]]
182 | test_eq(len(a), 3)
183 | 
184 | 185 |
186 |
187 |
188 | 189 |
190 | {% endraw %} 191 | 192 | {% raw %} 193 | 194 |
195 | 196 |
197 | {% endraw %} 198 | 199 | {% raw %} 200 | 201 |
202 | 203 |
204 |
205 | 206 |
207 | 208 | 209 |
210 |

class NumpyDataLoader[source]

NumpyDataLoader(dataset, bs=1, **kwargs) :: DataLoader

211 |
212 |

Inherit from this to have all attr accesses in self._xtra passed down to self.default

213 | 214 |
215 | 216 |
217 | 218 |
219 |
220 | 221 |
222 | {% endraw %} 223 | 224 | {% raw %} 225 | 226 |
227 |
228 | 229 |
230 |
231 |
dl = NumpyDataLoader(ds, bs=3)
232 | 
233 | 234 |
235 |
236 |
237 | 238 |
239 | {% endraw %} 240 | 241 | {% raw %} 242 | 243 |
244 |
245 | 246 |
247 |
248 |
batch = next(iter(dl))
249 | 
250 | 251 |
252 |
253 |
254 | 255 |
256 | {% endraw %} 257 | 258 | {% raw %} 259 | 260 |
261 |
262 | 263 |
264 |
265 |
test_eq(len(dl), len(ds)//3+1)
266 | 
267 | 268 |
269 |
270 |
271 | 272 |
273 | {% endraw %} 274 | 275 | {% raw %} 276 | 277 |
278 | 279 |
280 | {% endraw %} 281 | 282 | {% raw %} 283 | 284 |
285 | 286 |
287 |
288 | 289 |
290 | 291 | 292 |
293 |

NumpyDataLoader.shuffle_fn[source]

NumpyDataLoader.shuffle_fn(x:NumpyDataLoader)

294 |
295 |

Shuffle the interior dataset

296 | 297 |
298 | 299 |
300 | 301 |
302 |
303 | 304 |
305 | {% endraw %} 306 | 307 | {% raw %} 308 | 309 |
310 | 311 |
312 | {% endraw %} 313 | 314 | {% raw %} 315 | 316 |
317 | 318 |
319 |
320 | 321 |
322 | 323 | 324 |
325 |

NumpyDataLoader.get_idxs[source]

NumpyDataLoader.get_idxs(x:NumpyDataLoader)

326 |
327 |

Get index's to select

328 | 329 |
330 | 331 |
332 | 333 |
334 |
335 | 336 |
337 | {% endraw %} 338 | 339 |
340 |
341 |

To ensure that we still see an improvement, we'll compare timings

342 | 343 |
344 |
345 |
346 | {% raw %} 347 | 348 |
349 |
350 | 351 |
352 |
353 |
train_ds = NumpyDataset(to.train)
354 | valid_ds = NumpyDataset(to.valid)
355 | 
356 | 357 |
358 |
359 |
360 | 361 |
362 | {% endraw %} 363 | 364 | {% raw %} 365 | 366 |
367 |
368 | 369 |
370 |
371 |
train_dl = NumpyDataLoader(train_ds, bs=64, shuffle=True, drop_last=True)
372 | valid_dl = NumpyDataLoader(valid_ds, bs=64)
373 | 
374 | 375 |
376 |
377 |
378 | 379 |
380 | {% endraw %} 381 | 382 | {% raw %} 383 | 384 |
385 |
386 | 387 |
388 |
389 |
dls = to.dataloaders(bs=64)
390 | 
391 | 392 |
393 |
394 |
395 | 396 |
397 | {% endraw %} 398 | 399 | {% raw %} 400 | 401 |
402 |
403 | 404 |
405 |
406 |
%%timeit
407 | # Numpy
408 | for _ in train_dl: pass
409 | 
410 | 411 |
412 |
413 |
414 | 415 |
416 |
417 | 418 |
419 | 420 |
421 |
31.2 ms ± 35.8 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
422 | 
423 |
424 |
425 | 426 |
427 |
428 | 429 |
430 | {% endraw %} 431 | 432 | {% raw %} 433 | 434 |
435 |
436 | 437 |
438 |
439 |
%%timeit
440 | # fastai
441 | for _ in dls[0]: pass
442 | 
443 | 444 |
445 |
446 |
447 | 448 |
449 |
450 | 451 |
452 | 453 |
454 |
1.02 s ± 784 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
455 | 
456 |
457 |
458 | 459 |
460 |
461 | 462 |
463 | {% endraw %} 464 | 465 | {% raw %} 466 | 467 |
468 |
469 | 470 |
471 |
472 |
%%timeit
473 | # Numpy
474 | for _ in valid_dl: pass
475 | 
476 | 477 |
478 |
479 |
480 | 481 |
482 |
483 | 484 |
485 | 486 |
487 |
7.35 ms ± 12.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
488 | 
489 |
490 |
491 | 492 |
493 |
494 | 495 |
496 | {% endraw %} 497 | 498 | {% raw %} 499 | 500 |
501 |
502 | 503 |
504 |
505 |
%%timeit
506 | # fastai
507 | for _ in dls[1]: pass
508 | 
509 | 510 |
511 |
512 |
513 | 514 |
515 |
516 | 517 |
518 | 519 |
520 |
250 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
521 | 
522 |
523 |
524 | 525 |
526 |
527 | 528 |
529 | {% endraw %} 530 | 531 | {% raw %} 532 | 533 |
534 | 535 |
536 | {% endraw %} 537 | 538 | {% raw %} 539 | 540 |
541 | 542 |
543 |
544 | 545 |
546 | 547 | 548 |
549 |

class NumpyDataLoaders[source]

NumpyDataLoaders(to, bs=64, val_bs=None, shuffle_train=True, device='cpu', **kwargs) :: DataLoaders

550 |
551 |

Basic wrapper around several DataLoaders.

552 | 553 |
554 | 555 |
556 | 557 |
558 |
559 | 560 |
561 | {% endraw %} 562 | 563 |
564 | 565 | 566 | -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | repository: muellerzr/fastai2_tabular_hybrid 2 | output: web 3 | topnav_title: fastai2_tabular_hybrid 4 | site_title: fastai2_tabular_hybrid 5 | company_name: Zachary Mueller 6 | description: Hybrid approaches to help speed up fastai tabular 7 | # Set to false to disable KaTeX math 8 | use_math: true 9 | # Add Google analytics id if you have one and want to use it here 10 | google_analytics: 11 | # See http://nbdev.fast.ai/search for help with adding Search 12 | google_search: 13 | 14 | host: 127.0.0.1 15 | # the preview server used. Leave as is. 16 | port: 4000 17 | # the port where the preview is rendered. 18 | 19 | exclude: 20 | - .idea/ 21 | - .gitignore 22 | - vendor 23 | 24 | exclude: [vendor] 25 | 26 | highlighter: rouge 27 | markdown: kramdown 28 | kramdown: 29 | input: GFM 30 | auto_ids: true 31 | hard_wrap: false 32 | syntax_highlighter: rouge 33 | 34 | collections: 35 | tooltips: 36 | output: false 37 | 38 | defaults: 39 | - 40 | scope: 41 | path: "" 42 | type: "pages" 43 | values: 44 | layout: "page" 45 | comments: true 46 | search: true 47 | sidebar: home_sidebar 48 | topnav: topnav 49 | - 50 | scope: 51 | path: "" 52 | type: "tooltips" 53 | values: 54 | layout: "page" 55 | comments: true 56 | search: true 57 | tooltip: true 58 | 59 | sidebars: 60 | - home_sidebar 61 | permalink: pretty 62 | 63 | theme: jekyll-theme-cayman 64 | baseurl: /fastai2_tabular_hybrid/ -------------------------------------------------------------------------------- /docs/_data/alerts.yml: -------------------------------------------------------------------------------- 1 | tip: '