CYOA-CFPB-Classification.ipynb 45.7 KB
Newer Older
Brian McMahan's avatar
Brian McMahan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Consumer Complaint Product Classification\n",
    "\n",
    "## Dataset Info\n",
    "\n",
    "The whole CFPB dataset can be found [here](https://www.consumerfinance.gov/data-research/consumer-complaints/#download-the-data)\n",
    "\n",
    "## Model Info\n",
    "\n",
    "Choose Your Own Adventure and Build Your Own Model!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "from argparse import Namespace\n",
    "from collections import Counter\n",
    "import json\n",
    "import os\n",
    "import re\n",
29
    "os.environ['OMP_NUM_THREADS'] = '4' \n",
Brian McMahan's avatar
Brian McMahan committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "from tqdm import tqdm_notebook\n",
    "\n",
    "from vocabulary import Vocabulary\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "plt.style.use('fivethirtyeight')\n",
    "plt.rcParams['figure.figsize'] = (14, 6)\n",
    "\n",
    "START_TOKEN = \"^\"\n",
    "END_TOKEN = \"_\"\n",
    "# on CFPB, this only truncates ~12% of the data\n",
    "# without this, the max length can be >5000\n",
    "# to see for yourself, set MAX_LENGTH_THRESHOLD to 6000\n",
    "# then run the dataset loader and the following code:\n",
    "# bc = np.bincount(dataset._split_df['train'].tokenized.map(len))\n",
    "# sum(bc[:400]) / sum(bc)\n",
    "MAX_LENGTH_THRESHOLD = 400"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataset Utilities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def count_tokens(x_data_list):\n",
    "    \"\"\"Count the tokens in the data list\n",
    "    \n",
    "    Args:\n",
    "        x_data_list (list(list(str))): a list of lists, each sublist is a list of string tokens. \n",
    "            In other words, a list of the data points where the data points have been tokenized.\n",
    "    Returns:\n",
    "        dict: a mapping from tokens to their counts \n",
    "    \n",
    "    \"\"\"\n",
    "    # alternatively\n",
    "    # return Counter([token for x_data in x_data_list for token in x_data])\n",
    "    counter = Counter()\n",
    "    for x_data in x_data_list:\n",
    "        for token in x_data:\n",
    "            counter[token] += 1\n",
    "    return counter\n",
    "\n",
    "def add_splits(df, target_y_column, split_proportions=(0.7, 0.15, 0.15), seed=0):\n",
    "    \"\"\"Add 'train', 'val', and 'test' splits to the dataset\n",
    "    \n",
    "    Args:\n",
    "        df (pd.DataFrame): the data frame to assign splits to\n",
    "        target_y_column (str): the name of the label column; in order to\n",
    "            preserve the class distribution between splits, the label column\n",
    "            is used to group the datapoints and splits are assigned within these groups.\n",
    "        split_proportions (tuple(float, float, float)): three floats which represent the\n",
    "            proportion in 'train', 'val, 'and 'test'. Must sum to 1. \n",
    "        seed (int): the random seed for making the shuffling deterministic. If the dataset and seed\n",
    "            are kept the same, the split assignment is deterministic. \n",
    "    Returns:\n",
    "        pd.DataFrame: the input dataframe with a new column for split assignments; note: row order\n",
    "            will have changed.\n",
    "            \n",
    "    \"\"\"\n",
    "    df_by_label = {label: [] for label in df[target_y_column].unique()}\n",
    "    for _, row in df.iterrows():\n",
    "        df_by_label[row[target_y_column]].append(row.to_dict())\n",
    "    \n",
    "    np.random.seed(seed)\n",
    "    \n",
    "    assert sum(split_proportions) == 1, \"`split_proportions` should sum to 1\"\n",
    "    train_p, val_p, test_p = split_proportions\n",
    "    \n",
    "    out_df = []\n",
    "    # to ensure consistent behavior, lexicographically sort the dictionary\n",
    "    for _, data_points in sorted(df_by_label.items()):\n",
    "        np.random.shuffle(data_points)\n",
    "        n_total = len(data_points)\n",
    "        n_train = int(train_p * n_total)\n",
    "        n_val = int(val_p * n_total)\n",
    "        \n",
    "        for data_point in data_points[:n_train]:\n",
    "            data_point['split'] = 'train'\n",
    "            \n",
    "        for data_point in data_points[n_train:n_train+n_val]:\n",
    "            data_point['split'] = 'val'\n",
    "            \n",
    "        for data_point in data_points[n_train+n_val:]:\n",
    "            data_point['split'] = 'test'\n",
    "        \n",
    "        out_df.extend(data_points)\n",
    "    \n",
    "    return pd.DataFrame(out_df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Supervised Text Vectorizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SupervisedTextVectorizer:\n",
    "    \"\"\"A composite data structure that uses Vocabularies to map text and its labels to integers\n",
    "    \n",
    "    Attributes:\n",
    "        token_vocab (Vocabulary): the vocabulary managing the mapping between text tokens and \n",
    "            the unique indices that represent them\n",
    "        label_voab (Vocabulary): the vocabulary managing the mapping between labels and the\n",
    "            unique indices that represent them.\n",
    "        max_seq_length (int): the length of the longest sequence (including start or end tokens\n",
    "            that will be prepended or appended).\n",
    "    \"\"\"\n",
    "    def __init__(self, token_vocab, label_vocab, max_seq_length):\n",
    "        \"\"\"Initialize the SupervisedTextVectorizer\n",
    "        \n",
    "        Args:\n",
    "            token_vocab (Vocabulary): the vocabulary managing the mapping between text tokens and \n",
    "                the unique indices that represent them\n",
    "            label_voab (Vocabulary): the vocabulary managing the mapping between labels and the\n",
    "                unique indices that represent them.\n",
    "            max_seq_length (int): the length of the longest sequence (including start or end tokens\n",
    "                that will be prepended or appended).\n",
    "        \"\"\"\n",
    "        self.token_vocab = token_vocab\n",
    "        self.label_vocab = label_vocab\n",
    "        self.max_seq_length = max_seq_length\n",
    "        \n",
    "    def _wrap_with_start_end(self, x_data):\n",
    "        \"\"\"Prepend the start token and append the end token.\n",
    "        \n",
    "        Args:\n",
    "            x_data (list(str)): the list of string tokens in the data point\n",
    "        Returns:\n",
    "            list(str): the list of string tokens with start token prepended and end token appended\n",
    "        \"\"\"\n",
    "        return [self.token_vocab.start_token] + x_data + [self.token_vocab.end_token]\n",
    "    \n",
    "    def vectorize(self, x_data, y_label):\n",
    "        \"\"\"Convert the data point and its label into their integer form\n",
    "        \n",
    "        Args:\n",
    "            x_data (list(str)): the list of string tokens in the data point\n",
    "            y_label (str,int): the label associated with the data point\n",
    "        Returns:\n",
    "            numpy.ndarray, int: x_data in vector form, padded to the max_seq_length; and \n",
    "                the label mapped to the integer that represents it\n",
    "        \"\"\"\n",
    "        x_data = self._wrap_with_start_end(x_data)\n",
    "        x_vector = np.zeros(self.max_seq_length).astype(np.int64)\n",
    "        x_data_indices = [self.token_vocab[token] for token in x_data]\n",
    "        x_vector[:len(x_data_indices)] = x_data_indices\n",
    "        y_index = self.label_vocab[y_label]\n",
    "        return x_vector, y_index\n",
    "    \n",
    "    def transform(self, x_data_list, y_label_list):\n",
    "        \"\"\"Transform a dataset by vectorizing each datapoint\n",
    "        \n",
    "        Args: \n",
    "            x_data_list (list(list(str))): a list of lists, each sublist contains string tokens\n",
    "            y_label_list (list(str,int)): a list of either strings or integers. the y label can come\n",
    "                as strings or integers, but they are remapped with the label_vocab to a unique integer\n",
    "        Returns:\n",
    "            np.ndarray(matrix), np.ndarray(vector): the vectorized x (matrix) and vectorized y (vector) \n",
    "        \"\"\"\n",
    "        x_matrix = []\n",
    "        y_vector = []\n",
    "        for x_data, y_label in zip(x_data_list, y_label_list):\n",
    "            x_vector, y_index = self.vectorize(x_data, y_label)\n",
    "            x_matrix.append(x_vector)\n",
    "            y_vector.append(y_index)\n",
    "        \n",
    "        return np.stack(x_matrix), np.stack(y_vector)\n",
    "    \n",
    "    @classmethod\n",
    "    def from_df(cls, df, target_x_column, target_y_column, token_count_cutoff=0):\n",
    "        \"\"\"Instantiate the SupervisedTextVectorizer from a standardized dataframe\n",
    "        \n",
    "        Standardized DataFrame has a special meaning:\n",
    "            there is a column that has been tokenized into a list of strings\n",
    "        \n",
    "        Args:\n",
    "            df (pd.DataFrame): the dataset with a tokenized text column and a label column\n",
    "            target_x_column (str): the name of the tokenized text column\n",
    "            target_y_column (str): the name of the label column\n",
    "            token_count_cutoff (int): [default=0] the minimum token frequency to add to the\n",
    "                token_vocab.  Any tokens that are less frequent will not be added.\n",
    "        Returns:\n",
    "            SupervisedTextVectorizer: the instantiated vectorizer\n",
    "        \"\"\"\n",
    "        # get the x data (the observations)\n",
    "        target_x_list = df[target_x_column].tolist()\n",
    "        # compute max sequence length, add 2 for the start, end tokens\n",
    "        max_seq_length = max(map(len, target_x_list)) + 2 \n",
    "        \n",
    "        # populate token vocab        \n",
    "        token_vocab = Vocabulary(use_unks=False,\n",
    "                                 use_mask=True,\n",
    "                                 use_start_end=True,\n",
    "                                 start_token=START_TOKEN,\n",
    "                                 end_token=END_TOKEN)\n",
    "        counts = count_tokens(target_x_list)\n",
    "        # sort counts in reverse order\n",
    "        for token, count in sorted(counts.items(), key=lambda x: x[1], reverse=True):\n",
    "            if count < token_count_cutoff:\n",
    "                break\n",
    "            token_vocab.add(token)\n",
    "\n",
    "        # populate label vocab\n",
    "        label_vocab = Vocabulary(use_unks=False, use_start_end=False, use_mask=False)\n",
    "        # add the sorted unique labels \n",
    "        label_vocab.add_many(sorted(df[target_y_column].unique()))\n",
    "        \n",
    "        return cls(token_vocab, label_vocab, max_seq_length)\n",
    "    \n",
    "    def save(self, filename):\n",
    "        \"\"\"Save the vectorizer using json to the file specified\n",
    "        \n",
    "        Args:\n",
    "            filename (str): the output file\n",
    "        \"\"\"\n",
    "        vec_dict = {\"token_vocab\": self.token_vocab.get_serializable_contents(),\n",
    "                    \"label_vocab\": self.label_vocab.get_serializable_contents(),\n",
    "                    'max_seq_length': self.max_seq_length}\n",
    "\n",
    "        with open(filename, \"wb\") as fp:\n",
    "            json.dump(vec_dict, fp)\n",
    "        \n",
    "    @classmethod\n",
    "    def load(cls, filename):\n",
    "        \"\"\"Load the vectorizer from the json file it was saved to\n",
    "        \n",
    "        Args:\n",
    "            filename (str): the file into which the vectorizer was saved.\n",
    "        Returns:\n",
    "            SupervisedTextVectorizer: the instantiated vectorizer\n",
    "        \"\"\"\n",
    "        with open(filename, \"rb\") as fp:\n",
    "            contents = json.load(fp)\n",
    "\n",
    "        contents[\"token_vocab\"] = Vocabulary.deserialize_from_contents(contents[\"token_vocab\"])\n",
    "        contents[\"label_vocab\"] = Vocabulary.deserialize_from_contents(contents[\"label_vocab\"])\n",
    "        return cls(**contents)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Supervised Text Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SupervisedTextDataset(Dataset):\n",
    "    \"\"\"\n",
    "    Attributes:\n",
    "        vectorizer (SupervisedTextVectorizer): an instantiated vectorizer\n",
    "        active_split (str): the string name of the active split\n",
    "        \n",
    "        # internal use\n",
    "        _split_df (dict): a mapping from split name to partitioned DataFrame\n",
    "        _vectorized (dict): a mapping from split to an x data matrix and y vector\n",
    "        _active_df (pd.DataFrame): the DataFrame corresponding to the split\n",
    "        _active_x (np.ndarray): a matrix of the vectorized text data\n",
    "        _active_y (np.ndarray): a vector of the vectorized labels\n",
    "    \"\"\"\n",
    "    def __init__(self, df, vectorizer, target_x_column, target_y_column):\n",
    "        \"\"\"Initialize the SupervisedTextDataset\n",
    "        \n",
    "        Args:\n",
    "            df (pd.DataFrame): the dataset with a text and label column\n",
    "            vectorizer (SupervisedTextVectorizer): an instantiated vectorizer\n",
    "            target_x_column (str): the column containing the tokenized text\n",
    "            target_y_column (str): the column containing the label\n",
    "        \"\"\"\n",
    "        self._split_df = {\n",
    "            'train': df[df.split=='train'],\n",
    "            'val': df[df.split=='val'],\n",
    "            'test': df[df.split=='test']\n",
    "        }\n",
    "        \n",
    "        self._vectorized = {}\n",
    "        for split_name, split_df in self._split_df.items():\n",
    "            self._vectorized[split_name] = \\\n",
    "                vectorizer.transform(x_data_list=split_df[target_x_column].tolist(), \n",
    "                                     y_label_list=split_df[target_y_column].tolist())\n",
    "        self.vectorizer = vectorizer\n",
    "        self.active_split = None\n",
    "        self._active_df = None\n",
    "        self._active_x = None\n",
    "        self._active_y = None\n",
    "        \n",
    "        self.set_split(\"train\")\n",
    "        \n",
    "    def set_split(self, split_name):\n",
    "        \"\"\"Set the active split\n",
    "        \n",
    "        Args:\n",
    "            split_name (str): the name of the split to make active; should\n",
    "                be one of 'train', 'val', or 'test'\n",
    "        \"\"\"\n",
    "        self.active_split = split_name\n",
    "        self._active_x, self._active_y = self._vectorized[split_name]\n",
    "        self._active_df = self._split_df[split_name]\n",
    "    \n",
    "    def __getitem__(self, index):\n",
    "        \"\"\"Return the data point corresponding to the index\n",
    "        \n",
    "        Args:\n",
    "            index (int): an int between 0 and len(self._active_x)\n",
    "        Returns:\n",
    "            dict: the data for this data point. Has the following form:\n",
    "                {\"x_data\": the vectorized text data point, \n",
    "                 \"y_target\": the index of the label for this data point, \n",
    "                 \"x_lengths\": method: the number of nonzeros in the vector,\n",
    "                 \"data_index\": the provided index for bookkeeping}\n",
    "        \"\"\"\n",
    "        return {\n",
    "            \"x_data\": self._active_x[index],\n",
    "            \"y_target\": self._active_y[index],\n",
    "            \"x_lengths\": len(self._active_x[index].nonzero()[0]),\n",
    "            \"data_index\": index\n",
    "        }\n",
    "    \n",
    "    def __len__(self):\n",
    "        \"\"\"The length of the active dataset\n",
    "        \n",
    "        Returns:\n",
    "            int: len(self._active_x)\n",
    "        \"\"\"\n",
    "        return self._active_x.shape[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataset Loading Function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "378998\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>product</th>\n",
       "      <th>complaint</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Debt collection</td>\n",
       "      <td>called rushmore loan management services for p...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Debt collection</td>\n",
       "      <td>upon looking at my credit file in of , i reali...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Mortgage</td>\n",
       "      <td>unlawful foreclosure . i have submitted a full...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Debt collection</td>\n",
       "      <td>grant and weber and have several accounts show...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Credit card or prepaid card</td>\n",
       "      <td>upon opening up a wells fargo checking account...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                       product  \\\n",
       "0              Debt collection   \n",
       "1              Debt collection   \n",
       "2                     Mortgage   \n",
       "3              Debt collection   \n",
       "4  Credit card or prepaid card   \n",
       "\n",
       "                                           complaint  \n",
       "0  called rushmore loan management services for p...  \n",
       "1  upon looking at my credit file in of , i reali...  \n",
       "2  unlawful foreclosure . i have submitted a full...  \n",
       "3  grant and weber and have several accounts show...  \n",
       "4  upon opening up a wells fargo checking account...  "
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.read_csv(\"../data/cfpb_complaints.csv\")\n",
    "print(len(df))\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "def character_tokenizer(input_string):\n",
    "    \"\"\"Tokenized a string a list of its characters\n",
    "    \n",
    "    Args:\n",
    "        input_string (str): the character string to tokenize\n",
    "    Returns:\n",
    "        list: a list of characters\n",
    "    \"\"\"\n",
    "    return list(input_string.lower())\n",
    "\n",
    "\n",
    "def simple_word_tokenizer(text):\n",
    "    \"\"\"Tokenize a sentence string into a list of words\n",
    "    \n",
    "    Args:\n",
    "        text (str): the sentence string to tokenize\n",
    "    \"\"\"\n",
    "    text = re.sub(r\"([.,!?])\", r\" \\1 \", text.lower())\n",
    "    tokenized = [tok for tok in text.split(\" \") if len(tok) > 0]\n",
    "    return tokenized[:MAX_LENGTH_THRESHOLD]\n",
    "    \n",
    "\n",
    "def load_cfpb_complaint_dataset(dataset_csv, tokenizer_func):\n",
    "    \"\"\"Load the cfpb complaint dataset \n",
    "    \n",
    "    Args:\n",
    "        dataset_csv (str): the location of the dataset\n",
    "        tokenizer_func (function): the tokenizing function to turn each datapoint into \n",
    "            its tokenized form\n",
    "    \"\"\"\n",
    "    df = add_splits(pd.read_csv(dataset_csv), \n",
    "                    target_y_column='product')\n",
    "    df['tokenized'] = df.complaint.apply(tokenizer_func)\n",
    "    vectorizer = SupervisedTextVectorizer.from_df(df, \n",
    "                                                  target_x_column='tokenized', \n",
    "                                                  target_y_column='product')\n",
    "    dataset = SupervisedTextDataset(df=df, \n",
    "                                    vectorizer=vectorizer, \n",
    "                                    target_x_column='tokenized', \n",
    "                                    target_y_column='product')\n",
    "    \n",
    "    return dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Verify it loads"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'x_data': array([   1,   16,    5,  194,    6,  221,  227,   49,    8,  981,    8,\n",
       "           3,    5,  781,    9, 2195,  132,   28, 2630,    3,   25,   13,\n",
       "          19,  190,    5,  194,    6,   10,  767,  811,    6,  133,   10,\n",
       "         390,   12,    5,   13,   51,    9,  517,   63,   13,  907,    3,\n",
       "           5,   64,    4,  180,  139,  372,   20,  221,  227,    6, 1127,\n",
       "          89,    4,  178,    7,   13,   51,   25,   38,  202,  199,  108,\n",
       "           6,  433,    7,   13,   51,    9,  243,   56,  781,    7, 1570,\n",
       "          14,    4,  151,  143,    3,   25,   21, 1475,    6,  506,   12,\n",
       "           5,   50,   19,  133,   10, 1282,  140,  107,   10,  458,    3,\n",
       "          18,   13,   14,   10, 1919,   53,  443,   22,  168,   58,  109,\n",
       "         190,    4,  375,  444,    3,  205,   14,    5,  120,  194,    6,\n",
       "           4,  151,  221,  227,   49,    6,  458,    9, 2195,  132,    7,\n",
       "         120,    4,  388,   93,   33, 1814,   13,   12,   11,   10,  458,\n",
       "           7, 1282,  120, 1196,   22,  168,  456,    6,    9,  109,    3,\n",
       "           5,   57,   19,  472,  164,   18,  707,    6,  896,    3,    5,\n",
       "          17,   64,    4,  180,  275,    7,  216,   23,   45,  120,   13,\n",
       "          51,   25,   38,  202,  199,  108,    6,  921,  350,    3,    5,\n",
       "          85,  216,   23,  180,  139,  394,    7,   13,   51,  101,  104,\n",
       "          19,  445,    6,   22,   95,    4,  102,   94,    6, 6575,    8,\n",
       "           7, 1499,    5,  572,  163,    4,  522,    3,   18,   21,   19,\n",
       "        2025,    6,   22,   28,    5,   38,  173,    6,  202,   65,  118,\n",
       "         211,   53,   38, 1004,  831,    3,    5,  452,  170,    5,   17,\n",
       "          43,  136, 2216,  181,    6,  142,   10,  153,    3,    5,   17,\n",
       "          39,   10, 2952,  180,   20,   95,  119,    3,  135, 1182,    8,\n",
       "           2,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
       "           0,    0,    0,    0,    0,    0]),\n",
       " 'y_target': 0,\n",
       " 'x_lengths': 265,\n",
       " 'data_index': 0}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset = load_cfpb_complaint_dataset(\"../data/cfpb_complaints.csv\", \n",
    "                                      simple_word_tokenizer)\n",
    "dataset[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Model\n",
    "\n",
    "Fill this part in :)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model Utilities"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Prototyping"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Args"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using CUDA: False\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "device(type='cpu')"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "args = Namespace(\n",
    "    # dataset\n",
    "    dataset_csv=\"../data/cfpb_complaints.csv\",\n",
    "    # model hyper parameters\n",
    "    # ADD OTHER MODEL HYPER PARAMETERS HERE\n",
    "    num_embeddings=-1,\n",
    "    num_classes=-1,\n",
    "    # training options\n",
    "    batch_size = 128,\n",
    "    cuda=False,\n",
    "    learning_rate=0.001,\n",
    "    num_epochs=100,\n",
    "    patience_threshold=3,\n",
    ")\n",
    "\n",
    "\n",
    "# Check CUDA\n",
    "if not torch.cuda.is_available():\n",
    "    args.cuda = False\n",
    "\n",
    "print(\"Using CUDA: {}\".format(args.cuda))\n",
    "\n",
    "args.device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n",
    "args.device"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training Utiltiies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_accuracy(y_pred, y_target):\n",
    "    \"\"\"Compute the accuracy between a matrix of predictions and a vector of label indices\n",
    "    \n",
    "    Args:\n",
    "        y_pred (torch.FloatTensor): [shape=(batch_size, num_classes)]\n",
    "            The matrix of predictions\n",
    "        y_true (torch.FloatTensor): [shape=(batch_size,)]\n",
    "            The vector of label indices\n",
    "    \"\"\"\n",
    "    y_pred_indices = y_pred.argmax(dim=1)\n",
    "    n_correct = torch.eq(y_pred_indices, y_target).sum().item()\n",
    "    return n_correct / len(y_pred_indices) * 100\n",
    "\n",
    "\n",
    "def generate_batches(dataset, batch_size, shuffle=True,\n",
    "                     drop_last=True, device=\"cpu\", dataloader_kwargs=None): \n",
    "    \"\"\"Generate batches from a dataset\n",
    "    \n",
    "    Args:\n",
    "        dataset (torch.utils.data.Dataset): the instantiated dataset\n",
    "        batch_size (int): the size of the batches\n",
    "        shuffle (bool): [default=True] batches are formed from shuffled indices\n",
    "        drop_last (bool): [default=True] don't return the final batch if it's smaller\n",
    "            than the specified batch size\n",
    "        device (str): [default=\"cpu\"] the device to move the tensors to\n",
    "        dataloader_kwargs (dict or None): [default=None] Any additional arguments to the\n",
    "            DataLoader can be specified\n",
    "    Yields:\n",
    "        dict: a dictionary mapping from tensor name to tensor object where the first\n",
    "            dimension of tensor object is the batch dimension\n",
    "    Note: \n",
    "        This function is mostly an iterator for the DataLoader, but has the added\n",
    "        feature that it moves the tensors to a target device. \n",
    "    \"\"\"\n",
    "    dataloader_kwargs = dataloader_kwargs or {}\n",
    "    \n",
    "    dataloader = DataLoader(dataset=dataset, batch_size=batch_size,\n",
    "                            shuffle=shuffle, drop_last=drop_last, **dataloader_kwargs)\n",
    "\n",
    "    for data_dict in dataloader:\n",
    "        out_data_dict = {}\n",
    "        for name, tensor in data_dict.items():\n",
    "            out_data_dict[name] = data_dict[name].to(device)\n",
    "        yield out_data_dict\n",
    "\n",
    "\n",
    "class TrainState:\n",
    "    \"\"\"A data structure for managing training state operations.\n",
    "    \n",
    "    The TrainState will monitor validation loss and everytime a new best loss\n",
    "        (lower is better) is observed, a couple things happen:\n",
    "        \n",
    "        1. The model is checkpointed\n",
    "        2. Patience is reset\n",
    "    \n",
    "    Attributes:\n",
    "        model (torch.nn.Module): the model being trained and will be\n",
    "            checkpointed during training.\n",
    "        dataset (SupervisedTextDataset, TextSequenceDataset): the dataset \n",
    "            which is being iterate during training; must have the `active_split`\n",
    "            attribute. \n",
    "        log_dir (str): the directory to output the checkpointed model \n",
    "        patience (int): the number of epochs since a new best loss was observed\n",
    "        \n",
    "        # Internal Use\n",
    "        _full_model_path (str): `log_dir/model_state_file`\n",
    "        _split (str): the active split\n",
    "        _best_loss (float): the best observed loss\n",
    "    \"\"\"\n",
    "    def __init__(self, model, dataset, log_dir, model_state_file=\"model.pth\"):\n",
    "        \"\"\"Initialize the TrainState\n",
    "        \n",
    "        Args:\n",
    "            model (torch.nn.Module): the model to be checkpointed during training\n",
    "            dataset (SupervisedTextDataset, TextSequenceDataset): the dataset \n",
    "                which is being iterate during training; must have the `active_split`\n",
    "                attribute. \n",
    "            log_dir (str): the directory to output the checkpointed model \n",
    "            model_state_file (str): the name of the checkpoint model\n",
    "        \"\"\"\n",
    "        self.model = model\n",
    "        self.dataset = dataset\n",
    "        self._full_model_path = os.path.join(log_dir, model_state_file)\n",
    "        if not os.path.exists(log_dir):\n",
    "            os.makedirs(log_dir)\n",
    "        self.log_dir = log_dir\n",
    "        \n",
    "        self._metrics_by_split = {\n",
    "            'train': {}, \n",
    "            'val': {}, \n",
    "            'test': {}\n",
    "        }\n",
    "        \n",
    "        self._split = 'train'\n",
    "        self._best_loss = 10**10\n",
    "        self.patience = 0\n",
    "        \n",
    "    def _init_metric(self, split, metric_name):\n",
    "        \"\"\"Initialize a metric to the specified split\n",
    "        \n",
    "        A dictionary is created in `self._metrics_by_split` with\n",
    "            the keys 'running', 'count', and 'history'. \n",
    "        \n",
    "        Args:\n",
    "            split (str): the target split to record the metric\n",
    "            metric_name (str): the name of the metric\n",
    "        \"\"\"\n",
    "        self._metrics_by_split[split][metric_name] = {\n",
    "            'running': 0.,\n",
    "            'count': 0,\n",
    "            'history': []\n",
    "        }\n",
    "        \n",
    "    def _update_metric(self, metric_name, metric_value):\n",
    "        \"\"\"Update a metric with an observed value\n",
    "        \n",
    "        Specifically, the running average is updated.\n",
    "        \n",
    "        Args:\n",
    "            metric_name (str): the name of the metric\n",
    "            metric_value (float): the observed value of the metric\n",
    "        \"\"\"\n",
    "        if metric_name not in self._metrics_by_split[self._split]:\n",
    "            self._init_metric(self._split, metric_name)\n",
    "        metric = self._metrics_by_split[self._split][metric_name]\n",
    "        metric['count'] += 1\n",
    "        metric['running'] += (metric_value - metric['running']) / metric['count']\n",
    "        \n",
    "    def set_split(self, split):\n",
    "        \"\"\"Set the dataset split\n",
    "        \n",
    "        Args:\n",
    "            split (str): the target split to set\n",
    "        \"\"\"\n",
    "        self._split = split\n",
    "        \n",
    "    def get_history(self, split, metric_name):\n",
    "        \"\"\"Get the history of values for any metric in any split\n",
    "        \n",
    "        Args:\n",
    "            split (str): the target split\n",
    "            metric_name (str): the target metric\n",
    "            \n",
    "        Returns:\n",
    "            list(float): the running average of each epoch for `metric_name` in `split` \n",
    "        \"\"\"\n",
    "        return self._metrics_by_split[split][metric_name]['history']\n",
    "    \n",
    "    def get_value_of(self, split, metric_name):\n",
    "        \"\"\"Retrieve the running average of any metric in any split\n",
    "        \n",
    "        Args:\n",
    "            split (str): the target split\n",
    "            metric_name (str): the target metric\n",
    "            \n",
    "        Returns:\n",
    "            float: the running average for `metric_name` in `split`\n",
    "        \"\"\"\n",
    "        return self._metrics_by_split[split][metric_name]['running']\n",
    "        \n",
    "    def log_metrics(self, **metrics):\n",
    "        \"\"\"Log some values for some metrics\n",
    "        \n",
    "        Args:\n",
    "            metrics (kwargs): pass keyword args with the form `metric_name=metric_value`\n",
    "                to log the metric values into the attribute `_metrics_by_split`.\n",
    "        \"\"\"\n",
    "        self._split = self.dataset.active_split\n",
    "        for metric_name, metric_value in metrics.items():\n",
    "            self._update_metric(metric_name, metric_value)\n",
    "            \n",
    "    def log_epoch_end(self):\n",
    "        \"\"\"Log the end of the epoch. \n",
    "        \n",
    "        Some key functions happen at the end of the epoch:\n",
    "            - for each metric in each split running averages, counts, \n",
    "              and history are updated\n",
    "            - the model is checkpointed if a new best value is observed\n",
    "            - patience is incremented if a new best value is not observed\n",
    "        \"\"\"\n",
    "        for split_dict in self._metrics_by_split.values():\n",
    "            for metric_dict in split_dict.values():\n",
    "                metric_dict['history'].append(metric_dict['running'])\n",
    "                metric_dict['running'] = 0.0\n",
    "                metric_dict['count'] = 0\n",
    "                \n",
    "        if 'loss' in self._metrics_by_split['val']:\n",
    "            val_loss = self._metrics_by_split['val']['loss']['history'][-1]\n",
    "            if val_loss < self._best_loss:\n",
    "                self._best_loss = val_loss\n",
    "                self.save_model()\n",
    "                self.patience = 0\n",
    "            else:\n",
    "                self.patience += 1\n",
    "    \n",
    "    def save_model(self):\n",
    "        \"\"\" Save `model` to `log_dir/model_state_file` \"\"\"\n",
    "        torch.save(self.model.state_dict(), self._full_model_path)\n",
    "    \n",
    "    def reload_best(self):\n",
    "        \"\"\" reload `log_dir/model_state_file` to `model` \"\"\"\n",
    "        if os.path.exists(self._full_model_path):\n",
    "            self.model.load_state_dict(torch.load(self._full_model_path))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Instantiation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = load_cfpb_complaint_dataset(args.dataset_csv, \n",
    "                                      tokenizer_func=simple_word_tokenizer)\n",
    "\n",
    "args.num_embeddings = len(dataset.vectorizer.token_vocab)\n",
    "args.num_classes = len(dataset.vectorizer.label_vocab)\n",
    "\n",
    "# model = ...."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training Routine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Credit reporting, credit repair services, or other personal consumer reports    19077\n",
       "Debt collection                                                                 17945\n",
       "Mortgage                                                                        11041\n",
       "Credit reporting                                                                 6633\n",
       "Student loan                                                                     4512\n",
       "Credit card or prepaid card                                                      4402\n",
       "Credit card                                                                      3955\n",
       "Bank account or service                                                          3125\n",
       "Checking or savings account                                                      2646\n",
       "Consumer Loan                                                                    1989\n",
       "Vehicle loan or lease                                                            1174\n",
       "Money transfer, virtual currency, or money service                               1127\n",
       "Payday loan, title loan, or personal loan                                         902\n",
       "Payday loan                                                                       366\n",
       "Money transfers                                                                   314\n",
       "Prepaid card                                                                      304\n",
       "Other financial service                                                            60\n",
       "Virtual currency                                                                    2\n",
       "Name: product, dtype: int64"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset._split_df['train']['product'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = model.to(args.device)\n",
    "\n",
    "train_state = TrainState(model, 'model.pth', './logs/cfpb_complaints/v1')\n",
    "\n",
    "optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)\n",
    "\n",
    "loss_func = nn.CrossEntropyLoss()\n",
    "\n",
    "\n",
For faster browsing, not all history is shown. View entire blame