├── CNN ├── requirements.txt ├── config.yaml ├── model.py ├── train.py ├── utils.py └── TextClassifierCNN.ipynb ├── .gitignore ├── README.md └── LICENSE /CNN/requirements.txt: -------------------------------------------------------------------------------- 1 | keras 2 | nltk 3 | numpy 4 | pandas 5 | regex 6 | sklearn 7 | tensorflow 8 | tensorflow-datasets==4.0.1 9 | tensorflowjs 10 | transformers 11 | pyyaml 12 | -------------------------------------------------------------------------------- /CNN/config.yaml: -------------------------------------------------------------------------------- 1 | app: cnn-model 2 | task: text-clf 3 | output: 4 | path: ./models/ 5 | 6 | dataset: 7 | plugin: text 8 | file: 9 | path: dataset.csv 10 | 11 | input_features: 12 | text: Text 13 | labels: ClassIndex 14 | 15 | trn_val_splits: 16 | # Split based on a column's values: specify only the column containing a 17 | # the string "validation" for validation examples. 18 | # { type: fixed, value: "dataset"} 19 | 20 | # Random split 21 | { type: random, value: 0.2 } 22 | 23 | module: 24 | embedding_dim: 64 25 | dropout_rate: 0.3 26 | 27 | tokeniser: 28 | tokeniser: keras 29 | max_seq_length: 75 30 | pad: true 31 | 32 | training: 33 | batch_size: 16 34 | epochs: 5 35 | lr: 1.6e-04 36 | 37 | # Important for reproducibility 38 | random_state: 42 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Data folder 132 | data 133 | 134 | # Mac OS files 135 | .DS_Store 136 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TextClassifierModels 2 | Repository containing the code to develop a Neural based text classifier. 3 | 4 | ## Models 5 | 6 | In the repository there are various models implemented for text classification. 7 | In order to access a _ready-to-explore_ version one can have a look at the notebooks provided. 8 | Models are quite heavy and memory consuming, so it is really advised to use a GPU machine to run their training tasks. 9 | 10 | ### Available models 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 |
ModelDemoDetailsCLIAccuracy score on AG news dataset
CNN TextClassifier
29 | Open In ColabClassify texts with labels from the AG news database making use of a convolutional neural network.python3 -m train -c config.yaml 90.71
webApp
source
BERT TextClassifier
49 | Open In ColabClassify texts with labels from the AG news database making use of an attention model, based on BERT.python3 -m train -c config.yaml 93.95
webApp
source
63 | -------------------------------------------------------------------------------- /CNN/model.py: -------------------------------------------------------------------------------- 1 | ### 2 | ### model.py 3 | ### 4 | ### Created by Oscar de Felice on 23/10/2020. 5 | ### Copyright © 2020 Oscar de Felice. 6 | ### 7 | ### This program is free software: you can redistribute it and/or modify 8 | ### it under the terms of the GNU General Public License as published by 9 | ### the Free Software Foundation, either version 3 of the License, or 10 | ### (at your option) any later version. 11 | ### 12 | ### This program is distributed in the hope that it will be useful, 13 | ### but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ### GNU General Public License for more details. 16 | ### 17 | ### You should have received a copy of the GNU General Public License 18 | ### along with this program. If not, see . 19 | ### 20 | ######################################################################## 21 | ### 22 | ### model.py 23 | ### This module contains the model definition 24 | """ 25 | CNN Model for text classification. 26 | """ 27 | 28 | # import libraries 29 | import tensorflow as tf 30 | import tensorflow_datasets as tfds 31 | from tensorflow.keras.models import Sequential 32 | from tensorflow.keras.layers import Activation, Conv1D, Dense, Dropout, Embedding, GlobalMaxPool1D, MaxPool1D 33 | 34 | # default values 35 | optimizer = tf.keras.optimizers.Adam() 36 | loss = tf.keras.losses.CategoricalCrossentropy() 37 | 38 | 39 | def buildModel( vocab_size, 40 | emb_dim, 41 | max_len, 42 | num_classes, 43 | dropout_rate, 44 | optimizer = optimizer, 45 | loss = loss, 46 | name = 'CNN_for_text_classification'): 47 | """ 48 | Function to build a CNN model for text classification. 49 | 50 | Parameters 51 | ---------- 52 | vocab_size : int 53 | number of words in the vocabulary. 54 | 55 | emb_dim : int 56 | dimension of the embedding space. 57 | 58 | max_len : int 59 | maximal length of the input sequences. 60 | 61 | num_classes : int 62 | number of unique labels, it is also the number of 63 | units of the last dense layer. 64 | 65 | dropout_rate : int 66 | dropout hyperparameter, i.e. the probability of dropping 67 | a given node in the layer. 68 | dropout_rate = 0 is equivalent to no dropout. 69 | 70 | optimizer : optimizer object in Keras 71 | default : Adam optimizer 72 | 73 | loss : loss object in Keras 74 | default : Categorical Crossentropy 75 | 76 | name : str 77 | name of the model. 78 | default : 'CNN_for_text_classification' 79 | 80 | Return 81 | ------ 82 | A Keras model object. 83 | 84 | """ 85 | # build the model 86 | 87 | model = Sequential(name = name) 88 | model.add(Embedding(vocab_size, output_dim = emb_dim, input_length=max_len)) 89 | model.add(Dropout(dropout_rate)) 90 | model.add(Conv1D(50, 3, activation='relu', padding='same', strides=1)) 91 | model.add(MaxPool1D()) 92 | model.add(Dropout(dropout_rate)) 93 | model.add(Conv1D(100, 3, activation='relu', padding='same', strides=1)) 94 | model.add(MaxPool1D()) 95 | model.add(Dropout(dropout_rate)) 96 | model.add(Conv1D(200, 3, activation='relu', padding='same', strides=1)) 97 | model.add(GlobalMaxPool1D()) 98 | model.add(Dropout(dropout_rate)) 99 | model.add(Dense(100)) 100 | model.add(Activation('relu')) 101 | model.add(Dropout(dropout_rate)) 102 | model.add(Dense(num_classes)) 103 | model.add(Activation('softmax')) 104 | model.compile(loss=loss, metrics=['acc'], optimizer=optimizer) 105 | print(model.summary()) 106 | 107 | return model 108 | -------------------------------------------------------------------------------- /CNN/train.py: -------------------------------------------------------------------------------- 1 | ### 2 | ### train.py 3 | ### 4 | ### Created by Oscar de Felice on 23/10/2020. 5 | ### Copyright © 2020 Oscar de Felice. 6 | ### 7 | ### This program is free software: you can redistribute it and/or modify 8 | ### it under the terms of the GNU General Public License as published by 9 | ### the Free Software Foundation, either version 3 of the License, or 10 | ### (at your option) any later version. 11 | ### 12 | ### This program is distributed in the hope that it will be useful, 13 | ### but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ### GNU General Public License for more details. 16 | ### 17 | ### You should have received a copy of the GNU General Public License 18 | ### along with this program. If not, see . 19 | ### 20 | ######################################################################## 21 | ### 22 | ### train.py 23 | ### This module contains the script to train the model via CLI. 24 | """ 25 | To train the model this type in a command line prompt 26 | the command 27 | 28 | python3 -m train [-h] [-c CONFIG] 29 | 30 | where CONFIG is the yaml file path containing configuration variables. 31 | """ 32 | 33 | import argparse 34 | from model import buildModel 35 | from utils import getTokeniser, loadConfig, loadData, splitData, tokenise, printReport 36 | 37 | # let user feed in 1 parameter, the configuration file 38 | parser = argparse.ArgumentParser() 39 | parser.add_argument('-c', '--config', type=str, dest='config', 40 | help='path of the configuration file') 41 | args = parser.parse_args() 42 | configFile = args.config 43 | 44 | ## load configuration and store it in a dictionary 45 | config = loadConfig(configFile) 46 | 47 | ## variables 48 | # path of csv file containing data 49 | input_data = config['dataset']['file']['path'] 50 | # split mode (random or fixed) and value (test_rate or validation column in df) 51 | split_mode = config['trn_val_splits']['type'] 52 | split_value = config['trn_val_splits']['value'] 53 | # random state seed for pseudorandom processes 54 | random_state = config['random_state'] 55 | # name of the column containing text data 56 | text_col = config['input_features']['text'] 57 | # name of the column containing labels 58 | labels = config['input_features']['labels'] 59 | # tokeniser object 60 | tokeniser_conf = config['tokeniser']['tokeniser'] 61 | tokeniser = getTokeniser(tokeniser_conf) 62 | # max sequence length 63 | max_len = config['tokeniser']['max_seq_length'] 64 | # pad to max_seq_length 65 | pad = config['tokeniser']['pad'] 66 | # embedding dimension 67 | embedding_dim = config['module']['embedding_dim'] 68 | # dropout rate 69 | dropout_rate = config['module']['dropout_rate'] 70 | # batch size 71 | batch_size = config['training']['batch_size'] 72 | # number of epochs 73 | n_epochs = config['training']['epochs'] 74 | # learning rate 75 | learning_rate = config['training']['lr'] 76 | # output file for the report 77 | outfile = config['output']['path'] 78 | 79 | 80 | ## load data 81 | df, n_classes = loadData(input_data, labels) 82 | 83 | ## train, test split 84 | df_train, df_test = splitData(df, split_mode, split_value, random_state) 85 | 86 | ## text-to-sequence encoding 87 | X_train, vocab_size = tokenise(tokeniser, df_train, text_col, max_len, 88 | padding = pad, mode = 'train') 89 | X_test = tokenise(tokeniser, df_test, text_col, max_len, padding = pad, 90 | mode = 'test') 91 | 92 | ## convert labels to one-hot encoder 93 | y_train = encodeLabels(df_train, labels) 94 | y_test = encodeLabels(df_test, labels) 95 | 96 | ## convert to tensorflow datasets 97 | train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)) 98 | test_dataset = tf.data.Dataset.from_tensor_slices((X_test, y_test)) 99 | ds_train = train_dataset.shuffle(10000).batch(batch_size) 100 | ds_test = test_dataset.batch(batch_size) 101 | 102 | 103 | ## define deep learning model calssifier 104 | model = buildModel(vocab_size, embedding_dim, max_len, n_classes, dropout_rate) 105 | 106 | ## train the model 107 | model.fit(ds_train, epochs=n_epochs, validation_data=ds_test) 108 | 109 | printReport(model, X_test, y_test, target_names = df[labels].unique(), 110 | outfile=outfile) 111 | -------------------------------------------------------------------------------- /CNN/utils.py: -------------------------------------------------------------------------------- 1 | ### 2 | ### utils.py 3 | ### 4 | ### Created by Oscar de Felice on 23/10/2020. 5 | ### Copyright © 2020 Oscar de Felice. 6 | ### 7 | ### This program is free software: you can redistribute it and/or modify 8 | ### it under the terms of the GNU General Public License as published by 9 | ### the Free Software Foundation, either version 3 of the License, or 10 | ### (at your option) any later version. 11 | ### 12 | ### This program is distributed in the hope that it will be useful, 13 | ### but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ### GNU General Public License for more details. 16 | ### 17 | ### You should have received a copy of the GNU General Public License 18 | ### along with this program. If not, see . 19 | ### 20 | ######################################################################## 21 | ### 22 | ### utils.py 23 | ### This module contains helper functions for train and model. 24 | 25 | # import libraries 26 | import tensorflow_datasets as tfds 27 | import pandas as pd 28 | pd.options.mode.chained_assignment = None # default='warn' 29 | from sklearn.metrics import classification_report 30 | from sklearn import preprocessing 31 | from sklearn.model_selection import train_test_split 32 | import yaml 33 | from keras.preprocessing.sequence import pad_sequences 34 | from keras.utils import to_categorical 35 | 36 | import re 37 | import string 38 | from datetime import datetime 39 | 40 | import nltk 41 | nltk.download('punkt') 42 | nltk.download('stopwords') 43 | from nltk.corpus import stopwords 44 | from nltk.tokenize import word_tokenize 45 | 46 | def getTokeniser(tokeniser_conf): 47 | if tokeniser_conf == 'keras': 48 | from keras.preprocessing.text import Tokenizer 49 | return Tokenizer(lower = True) 50 | else: 51 | raise ValueError(f'{tokeniser_conf} is not a valid option for tokeniser') 52 | 53 | def loadConfig(configFile): 54 | with open(configFile, 'r') as stream: 55 | try: 56 | return yaml.safe_load(stream) 57 | except yaml.YAMLError as error: 58 | print(error) 59 | 60 | def loadData(data, label_col, **kwargs): 61 | """ 62 | Function to download and store data into a dataset. 63 | 64 | Parameters 65 | ---------- 66 | data : str 67 | path to data file (csv). 68 | 69 | label_col : str 70 | name of the column containing labels. 71 | 72 | Returns 73 | ------- 74 | pandas dataframe containing data. 75 | n_classes : int 76 | nuber of classes for text classification. 77 | """ 78 | df = pd.read_csv(data, **kwargs) 79 | return df, len(df[label_col].unique()) 80 | 81 | def splitData( df, split_mode, split_value, random_state = None): 82 | """ 83 | Function to split data into train and validation sets. 84 | 85 | Parameters 86 | ---------- 87 | df : pandas dataframe 88 | dataframe to be splitted 89 | 90 | split_mode : str 91 | string indicating whether the split is random or 92 | based on the value in a specific column 93 | 94 | split_value : float or str 95 | if split is random, which fraction of df has to be 96 | taken as validation set. 97 | if split is value based, the name of the column to 98 | look at. 99 | 100 | random_state : int 101 | seed to recover reproducibility in pseudorandom 102 | operations. 103 | 104 | Return 105 | ------ 106 | df_train, df_test : pandas dataframes 107 | pandas dataframes containing train and test 108 | data respectively. 109 | """ 110 | 111 | if split_mode == 'random': 112 | df_train, df_test = train_test_split( df, test_size=split_value, 113 | random_state=random_state) 114 | elif split_mode == 'fixed': 115 | test_mask = df[split_value] == 'validation' 116 | df_test = df[test_mask] 117 | df_train = df[~test_mask] 118 | 119 | else: 120 | raise ValueError(f'{split_mode} is not a valid option for split_mode.') 121 | 122 | return df_train, df_test 123 | 124 | def remove_punc(text): 125 | text = re.sub('\[.*?\]', '', text) 126 | text = re.sub('https?://\S+|www\.\S+', '', text) 127 | text = re.sub('<.*?>+', '', text) 128 | text = re.sub('[%s]' % re.escape(string.punctuation), '', text) 129 | text = re.sub('\n', '', text) 130 | text = re.sub('\w*\d\w*', '', text) 131 | return text 132 | 133 | def remove_stopwords(text): 134 | """ 135 | Functions to remove stopwords. 136 | """ 137 | list1 = [word for word in text.split() if 138 | word not in stopwords.words('english')] 139 | 140 | return " ".join(list1) 141 | 142 | def preprocess( df, text_col): 143 | """ 144 | Function to preprocess text data. 145 | 146 | Parameters 147 | ---------- 148 | df : pandas dataframe 149 | dataframe containing text data. 150 | 151 | text_col : str 152 | column name containing text to be transformed. 153 | 154 | Returns 155 | ------- 156 | NoneType, it updates df[text_col] with stopwords and punctuation 157 | removed. 158 | """ 159 | 160 | df[text_col] = df[text_col].apply(lambda x: remove_punc(x)) 161 | df[text_col] = df[text_col].apply(lambda x: remove_stopwords(x)) 162 | 163 | 164 | def tokenise( tokeniser, 165 | df, 166 | text_col, 167 | max_len, 168 | padding = True, 169 | mode = 'train'): 170 | """ 171 | Function to operate the text-to-sequence conversion. 172 | 173 | Parameters 174 | ---------- 175 | tokeniser : tokeniser object 176 | 177 | df : pandas dataframe 178 | dataframe containing text data in a column. 179 | 180 | text_col : str 181 | name of the column containing text to tokenise. 182 | 183 | max_len : int 184 | maximal lenght of the tokenised sequence. 185 | Texts in text_col longer than max_len are truncated. 186 | Shorter ones are padded with special token. 187 | 188 | padding : bool 189 | Set to True to add pad tokens to sequences shorter than 190 | max_len. 191 | default : True 192 | 193 | mode : str 194 | train mode indicates to operate the tokeniser fit on 195 | sequences. 196 | test mode just convert text to sequences. 197 | 198 | Return 199 | ------ 200 | numpy array of shape (len(df), max_len) 201 | This contains a numerical sequence per row corresponding to the 202 | encoding of each df[text_col] row. 203 | In mode train returns also the vocab_size. 204 | """ 205 | preprocess(df, text_col) 206 | 207 | if mode == 'train': 208 | tokeniser = tokeniser 209 | tokeniser.fit_on_texts(df[text_col]) 210 | vocab_size = len(tokeniser.word_index) + 1 211 | elif mode == 'test': 212 | tokeniser = tokeniser 213 | else: 214 | raise ValueError(f'{mode} is not a valid option.') 215 | 216 | tokenised_texts = tokeniser.texts_to_sequences(df[text_col]) 217 | if padding: 218 | tokenised_texts = pad_sequences(tokenised_texts, maxlen=max_len) 219 | 220 | if mode == 'train': 221 | return tokenised_texts, vocab_size 222 | else: 223 | return tokenised_texts 224 | 225 | def encodeLabels(df, label_col, mode): 226 | """ 227 | Function to apply the one-hot encoder to labels. 228 | 229 | Parameters 230 | ---------- 231 | df : pandas dataframe 232 | dataframe containing data. 233 | 234 | label_col : str 235 | name of the column containing labels. 236 | """ 237 | 238 | encoded_labels = preprocessing.LabelEncoder() 239 | 240 | y = encoded_labels.fit_transform(df[label_col]) 241 | 242 | return to_categorical(y) 243 | 244 | def printReport(model, x_test, y_test, 245 | target_names = None, 246 | num_digits = 4, 247 | outfile = None): 248 | """ 249 | Function to print classification report. 250 | 251 | Parameters 252 | ---------- 253 | y_true : list of float 254 | the test labels. 255 | 256 | y_predict : list of float 257 | model predictions for labels. 258 | 259 | label_names : list of str 260 | list of names for labels. 261 | If None there will appear numbers (indices 262 | of label list). 263 | default : None 264 | 265 | num_digits : int 266 | the number of digits to show in the report. 267 | default : 4 268 | 269 | outfile : str or NoneType 270 | A path to a file .txt to be filled with classification 271 | report. 272 | If None, prints on screen. 273 | default : None 274 | 275 | """ 276 | y_pred = to_categorical(np.argmax(model.predict(X_test), axis=1)) 277 | 278 | if outfile != None: 279 | original_stdout = sys.stdout # Save a reference to the original standard output 280 | 281 | filename = outfile + datetime.now() + '.txt' 282 | 283 | with open(filename, 'w') as f: 284 | sys.stdout = f # Change the standard output to the file we created. 285 | print(classification_report(y_test, y_pred, 286 | target_names=label_names, 287 | digits = num_digits)) 288 | 289 | sys.stdout = original_stdout # Reset the standard output to its 290 | # original value. 291 | 292 | else: 293 | print(classification_report(y_test, y_pred, target_names=label_names, 294 | digits = num_digits)) 295 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /CNN/TextClassifierCNN.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "TextClassifierCNN.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [], 9 | "toc_visible": true, 10 | "authorship_tag": "ABX9TyOffx5VoApOv7F1Sivbux2h", 11 | "include_colab_link": true 12 | }, 13 | "kernelspec": { 14 | "name": "python3", 15 | "display_name": "Python 3" 16 | }, 17 | "accelerator": "GPU" 18 | }, 19 | "cells": [ 20 | { 21 | "cell_type": "markdown", 22 | "metadata": { 23 | "id": "view-in-github", 24 | "colab_type": "text" 25 | }, 26 | "source": [ 27 | "\"Open" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": { 33 | "id": "Ixp1DaiY3AHe" 34 | }, 35 | "source": [ 36 | "# Installation and Configuration" 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": { 42 | "id": "u1UScWlo3EW-" 43 | }, 44 | "source": [ 45 | "Google Colab offers free GPU and even TPU. For the purpose of simpler setup, we will stick to GPU. Attention models are quite big, so we need to be aware that we are constrained by 12 GB of VRAM in Google Colab as Tesla K80 is used.\n", 46 | "\n", 47 | "First, let's check if you have GPU enabled in your session here in Colab. You can do it by running the following code." 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "metadata": { 53 | "id": "jd0tT7HQ2shq", 54 | "outputId": "be8f5046-c53d-44eb-a880-411c07f5983c", 55 | "colab": { 56 | "base_uri": "https://localhost:8080/", 57 | "height": 34 58 | } 59 | }, 60 | "source": [ 61 | "import tensorflow as tf\n", 62 | "\n", 63 | "# Get the GPU device name.\n", 64 | "device_name = tf.test.gpu_device_name()\n", 65 | "\n", 66 | "# The device name should look like the following:\n", 67 | "if device_name == '/device:GPU:0':\n", 68 | " print('Found GPU at: {}'.format(device_name))\n", 69 | "else: \n", 70 | " raise SystemError('GPU device not found')" 71 | ], 72 | "execution_count": 1, 73 | "outputs": [ 74 | { 75 | "output_type": "stream", 76 | "text": [ 77 | "Found GPU at: /device:GPU:0\n" 78 | ], 79 | "name": "stdout" 80 | } 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "metadata": { 86 | "id": "OxjF4kWs3z68" 87 | }, 88 | "source": [ 89 | "If you do not have the GPU enabled, just go to:\n", 90 | "\n", 91 | "`Edit -> Notebook Settings -> Hardware accelerator -> Set to GPU`\n", 92 | "\n", 93 | "To fine-tune our model, we need a couple of libraries to install first. \n", 94 | "TensorFlow 2 is already preinstalled, so the missing ones are [transformers](https://github.com/huggingface/transformers) and [TensorFlow datasets](https://github.com/tensorflow/datasets). This allows us to very easily import already pre-trained models for TensorFlow 2 and fine-tune with Keras API. " 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "metadata": { 100 | "id": "7H1RuNQe3lR_" 101 | }, 102 | "source": [ 103 | "%%bash\n", 104 | "pip install -q transformers tensorflow_datasets==4.0.1 " 105 | ], 106 | "execution_count": 2, 107 | "outputs": [] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": { 112 | "id": "tEp4PrNXh1Ps" 113 | }, 114 | "source": [ 115 | "In addition, we install [Tensorflow.JS](https://www.tensorflow.org/js). This will be useful to export our model once trained to deploy it on a web app." 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "metadata": { 121 | "id": "YA3ObIdl7ZFG" 122 | }, 123 | "source": [ 124 | "%%bash\n", 125 | "pip install -q tensorflowjs" 126 | ], 127 | "execution_count": 3, 128 | "outputs": [] 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "metadata": { 133 | "id": "7Ckrcntu4XD_" 134 | }, 135 | "source": [ 136 | "# Loading AG News dataset" 137 | ] 138 | }, 139 | { 140 | "cell_type": "markdown", 141 | "metadata": { 142 | "id": "j1xSGNbC4YXn" 143 | }, 144 | "source": [ 145 | "We will use [ag_news dataset](https://www.tensorflow.org/datasets/catalog/ag_news_subset).\n", 146 | "\n", 147 | "The AG's news topic classification dataset is constructed by Xiang Zhang (xiang.zhang@nyu.edu) from the complete dataset of 1 million of news. It is used as a text classification benchmark in the following paper: Xiang Zhang, Junbo Zhao, Yann LeCun. Character-level Convolutional Networks for Text Classification. Advances in Neural Information Processing Systems 28 (NIPS 2015).\n", 148 | "\n", 149 | "The AG's news topic classification dataset is constructed by choosing 4 largest classes from the original corpus. Each class contains 30,000 training samples and 1,900 testing samples. The total number of training samples is 120,000 and testing 7,600.\n", 150 | "\n", 151 | "Although we could load data very quickly just with `tensorflow_datasets` library, with the following code\n", 152 | "\n", 153 | "```python\n", 154 | "import tensorflow_datasets as tfds\n", 155 | "\n", 156 | "(ds_train, ds_test), ds_info = tfds.load('ag_news_subset', \n", 157 | " split = (tfds.Split.TRAIN, tfds.Split.TEST),\n", 158 | " as_supervised=True,\n", 159 | " with_info=True\n", 160 | " )\n", 161 | "\n", 162 | "print('info', ds_info)\n", 163 | "```\n", 164 | "\n", 165 | "Note how the code above returns a dictionary \n", 166 | "```python\n", 167 | "FeaturesDict({\n", 168 | " 'description': Text(shape=(), dtype=tf.string),\n", 169 | " 'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=4),\n", 170 | " 'title': Text(shape=(), dtype=tf.string),\n", 171 | "})\n", 172 | "```\n", 173 | "\n", 174 | "We want to operate some preprocessing, thus we are going to load data through the usual pandas dataframe from csv, and then convert to a tensorflow dataset, which is the robust, and ready-to-parallel computing format we want to use." 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "metadata": { 180 | "id": "kq7---q-mOwg", 181 | "outputId": "0f162301-673a-43d0-fa06-a3e8bc9f7231", 182 | "colab": { 183 | "base_uri": "https://localhost:8080/", 184 | "height": 1000 185 | } 186 | }, 187 | "source": [ 188 | "%%bash\n", 189 | "wget https://s3.amazonaws.com/fast-ai-nlp/ag_news_csv.tgz\n", 190 | "mkdir -p data && tar -xvzf ag_news_csv.tgz -C data/" 191 | ], 192 | "execution_count": 4, 193 | "outputs": [ 194 | { 195 | "output_type": "stream", 196 | "text": [ 197 | "ag_news_csv/\n", 198 | "ag_news_csv/train.csv\n", 199 | "ag_news_csv/readme.txt\n", 200 | "ag_news_csv/test.csv\n", 201 | "ag_news_csv/classes.txt\n" 202 | ], 203 | "name": "stdout" 204 | }, 205 | { 206 | "output_type": "stream", 207 | "text": [ 208 | "--2020-10-26 10:51:13-- https://s3.amazonaws.com/fast-ai-nlp/ag_news_csv.tgz\n", 209 | "Resolving s3.amazonaws.com (s3.amazonaws.com)... 52.217.64.158\n", 210 | "Connecting to s3.amazonaws.com (s3.amazonaws.com)|52.217.64.158|:443... connected.\n", 211 | "HTTP request sent, awaiting response... 200 OK\n", 212 | "Length: 11784419 (11M) [application/x-tar]\n", 213 | "Saving to: ‘ag_news_csv.tgz.1’\n", 214 | "\n", 215 | " 0K .......... .......... .......... .......... .......... 0% 1.65M 7s\n", 216 | " 50K .......... .......... .......... .......... .......... 0% 1.68M 7s\n", 217 | " 100K .......... .......... .......... .......... .......... 1% 1.68M 7s\n", 218 | " 150K .......... .......... .......... .......... .......... 1% 144M 5s\n", 219 | " 200K .......... .......... .......... .......... .......... 2% 1.70M 5s\n", 220 | " 250K .......... .......... .......... .......... .......... 2% 94.5M 4s\n", 221 | " 300K .......... .......... .......... .......... .......... 3% 178M 4s\n", 222 | " 350K .......... .......... .......... .......... .......... 3% 164M 3s\n", 223 | " 400K .......... .......... .......... .......... .......... 3% 174M 3s\n", 224 | " 450K .......... .......... .......... .......... .......... 4% 1.76M 3s\n", 225 | " 500K .......... .......... .......... .......... .......... 4% 166M 3s\n", 226 | " 550K .......... .......... .......... .......... .......... 5% 171M 3s\n", 227 | " 600K .......... .......... .......... .......... .......... 5% 158M 2s\n", 228 | " 650K .......... .......... .......... .......... .......... 6% 154M 2s\n", 229 | " 700K .......... .......... .......... .......... .......... 6% 148M 2s\n", 230 | " 750K .......... .......... .......... .......... .......... 6% 133M 2s\n", 231 | " 800K .......... .......... .......... .......... .......... 7% 168M 2s\n", 232 | " 850K .......... .......... .......... .......... .......... 7% 183M 2s\n", 233 | " 900K .......... .......... .......... .......... .......... 8% 180M 2s\n", 234 | " 950K .......... .......... .......... .......... .......... 8% 1.84M 2s\n", 235 | " 1000K .......... .......... .......... .......... .......... 9% 123M 2s\n", 236 | " 1050K .......... .......... .......... .......... .......... 9% 161M 2s\n", 237 | " 1100K .......... .......... .......... .......... .......... 9% 156M 2s\n", 238 | " 1150K .......... .......... .......... .......... .......... 10% 155M 2s\n", 239 | " 1200K .......... .......... .......... .......... .......... 10% 141M 1s\n", 240 | " 1250K .......... .......... .......... .......... .......... 11% 153M 1s\n", 241 | " 1300K .......... .......... .......... .......... .......... 11% 173M 1s\n", 242 | " 1350K .......... .......... .......... .......... .......... 12% 151M 1s\n", 243 | " 1400K .......... .......... .......... .......... .......... 12% 161M 1s\n", 244 | " 1450K .......... .......... .......... .......... .......... 13% 151M 1s\n", 245 | " 1500K .......... .......... .......... .......... .......... 13% 137M 1s\n", 246 | " 1550K .......... .......... .......... .......... .......... 13% 159M 1s\n", 247 | " 1600K .......... .......... .......... .......... .......... 14% 174M 1s\n", 248 | " 1650K .......... .......... .......... .......... .......... 14% 154M 1s\n", 249 | " 1700K .......... .......... .......... .......... .......... 15% 143M 1s\n", 250 | " 1750K .......... .......... .......... .......... .......... 15% 175M 1s\n", 251 | " 1800K .......... .......... .......... .......... .......... 16% 195M 1s\n", 252 | " 1850K .......... .......... .......... .......... .......... 16% 173M 1s\n", 253 | " 1900K .......... .......... .......... .......... .......... 16% 163M 1s\n", 254 | " 1950K .......... .......... .......... .......... .......... 17% 2.10M 1s\n", 255 | " 2000K .......... .......... .......... .......... .......... 17% 179M 1s\n", 256 | " 2050K .......... .......... .......... .......... .......... 18% 221M 1s\n", 257 | " 2100K .......... .......... .......... .......... .......... 18% 136M 1s\n", 258 | " 2150K .......... .......... .......... .......... .......... 19% 156M 1s\n", 259 | " 2200K .......... .......... .......... .......... .......... 19% 73.1M 1s\n", 260 | " 2250K .......... .......... .......... .......... .......... 19% 62.2M 1s\n", 261 | " 2300K .......... .......... .......... .......... .......... 20% 74.2M 1s\n", 262 | " 2350K .......... .......... .......... .......... .......... 20% 85.5M 1s\n", 263 | " 2400K .......... .......... .......... .......... .......... 21% 184M 1s\n", 264 | " 2450K .......... .......... .......... .......... .......... 21% 109M 1s\n", 265 | " 2500K .......... .......... .......... .......... .......... 22% 152M 1s\n", 266 | " 2550K .......... .......... .......... .......... .......... 22% 133M 1s\n", 267 | " 2600K .......... .......... .......... .......... .......... 23% 192M 1s\n", 268 | " 2650K .......... .......... .......... .......... .......... 23% 234M 1s\n", 269 | " 2700K .......... .......... .......... .......... .......... 23% 199M 1s\n", 270 | " 2750K .......... .......... .......... .......... .......... 24% 220M 1s\n", 271 | " 2800K .......... .......... .......... .......... .......... 24% 260M 1s\n", 272 | " 2850K .......... .......... .......... .......... .......... 25% 88.7M 1s\n", 273 | " 2900K .......... .......... .......... .......... .......... 25% 109M 1s\n", 274 | " 2950K .......... .......... .......... .......... .......... 26% 195M 1s\n", 275 | " 3000K .......... .......... .......... .......... .......... 26% 185M 1s\n", 276 | " 3050K .......... .......... .......... .......... .......... 26% 182M 1s\n", 277 | " 3100K .......... .......... .......... .......... .......... 27% 149M 1s\n", 278 | " 3150K .......... .......... .......... .......... .......... 27% 193M 1s\n", 279 | " 3200K .......... .......... .......... .......... .......... 28% 180M 1s\n", 280 | " 3250K .......... .......... .......... .......... .......... 28% 183M 1s\n", 281 | " 3300K .......... .......... .......... .......... .......... 29% 160M 1s\n", 282 | " 3350K .......... .......... .......... .......... .......... 29% 189M 1s\n", 283 | " 3400K .......... .......... .......... .......... .......... 29% 196M 1s\n", 284 | " 3450K .......... .......... .......... .......... .......... 30% 172M 0s\n", 285 | " 3500K .......... .......... .......... .......... .......... 30% 171M 0s\n", 286 | " 3550K .......... .......... .......... .......... .......... 31% 183M 0s\n", 287 | " 3600K .......... .......... .......... .......... .......... 31% 211M 0s\n", 288 | " 3650K .......... .......... .......... .......... .......... 32% 200M 0s\n", 289 | " 3700K .......... .......... .......... .......... .......... 32% 199M 0s\n", 290 | " 3750K .......... .......... .......... .......... .......... 33% 225M 0s\n", 291 | " 3800K .......... .......... .......... .......... .......... 33% 201M 0s\n", 292 | " 3850K .......... .......... .......... .......... .......... 33% 200M 0s\n", 293 | " 3900K .......... .......... .......... .......... .......... 34% 175M 0s\n", 294 | " 3950K .......... .......... .......... .......... .......... 34% 2.95M 0s\n", 295 | " 4000K .......... .......... .......... .......... .......... 35% 199M 0s\n", 296 | " 4050K .......... .......... .......... .......... .......... 35% 236M 0s\n", 297 | " 4100K .......... .......... .......... .......... .......... 36% 221M 0s\n", 298 | " 4150K .......... .......... .......... .......... .......... 36% 206M 0s\n", 299 | " 4200K .......... .......... .......... .......... .......... 36% 119M 0s\n", 300 | " 4250K .......... .......... .......... .......... .......... 37% 133M 0s\n", 301 | " 4300K .......... .......... .......... .......... .......... 37% 92.0M 0s\n", 302 | " 4350K .......... .......... .......... .......... .......... 38% 163M 0s\n", 303 | " 4400K .......... .......... .......... .......... .......... 38% 216M 0s\n", 304 | " 4450K .......... .......... .......... .......... .......... 39% 235M 0s\n", 305 | " 4500K .......... .......... .......... .......... .......... 39% 184M 0s\n", 306 | " 4550K .......... .......... .......... .......... .......... 39% 214M 0s\n", 307 | " 4600K .......... .......... .......... .......... .......... 40% 245M 0s\n", 308 | " 4650K .......... .......... .......... .......... .......... 40% 210M 0s\n", 309 | " 4700K .......... .......... .......... .......... .......... 41% 193M 0s\n", 310 | " 4750K .......... .......... .......... .......... .......... 41% 219M 0s\n", 311 | " 4800K .......... .......... .......... .......... .......... 42% 230M 0s\n", 312 | " 4850K .......... .......... .......... .......... .......... 42% 235M 0s\n", 313 | " 4900K .......... .......... .......... .......... .......... 43% 199M 0s\n", 314 | " 4950K .......... .......... .......... .......... .......... 43% 204M 0s\n", 315 | " 5000K .......... .......... .......... .......... .......... 43% 211M 0s\n", 316 | " 5050K .......... .......... .......... .......... .......... 44% 237M 0s\n", 317 | " 5100K .......... .......... .......... .......... .......... 44% 183M 0s\n", 318 | " 5150K .......... .......... .......... .......... .......... 45% 167M 0s\n", 319 | " 5200K .......... .......... .......... .......... .......... 45% 196M 0s\n", 320 | " 5250K .......... .......... .......... .......... .......... 46% 262M 0s\n", 321 | " 5300K .......... .......... .......... .......... .......... 46% 197M 0s\n", 322 | " 5350K .......... .......... .......... .......... .......... 46% 180M 0s\n", 323 | " 5400K .......... .......... .......... .......... .......... 47% 195M 0s\n", 324 | " 5450K .......... .......... .......... .......... .......... 47% 194M 0s\n", 325 | " 5500K .......... .......... .......... .......... .......... 48% 154M 0s\n", 326 | " 5550K .......... .......... .......... .......... .......... 48% 200M 0s\n", 327 | " 5600K .......... .......... .......... .......... .......... 49% 227M 0s\n", 328 | " 5650K .......... .......... .......... .......... .......... 49% 210M 0s\n", 329 | " 5700K .......... .......... .......... .......... .......... 49% 201M 0s\n", 330 | " 5750K .......... .......... .......... .......... .......... 50% 219M 0s\n", 331 | " 5800K .......... .......... .......... .......... .......... 50% 248M 0s\n", 332 | " 5850K .......... .......... .......... .......... .......... 51% 231M 0s\n", 333 | " 5900K .......... .......... .......... .......... .......... 51% 185M 0s\n", 334 | " 5950K .......... .......... .......... .......... .......... 52% 217M 0s\n", 335 | " 6000K .......... .......... .......... .......... .......... 52% 210M 0s\n", 336 | " 6050K .......... .......... .......... .......... .......... 53% 211M 0s\n", 337 | " 6100K .......... .......... .......... .......... .......... 53% 200M 0s\n", 338 | " 6150K .......... .......... .......... .......... .......... 53% 224M 0s\n", 339 | " 6200K .......... .......... .......... .......... .......... 54% 212M 0s\n", 340 | " 6250K .......... .......... .......... .......... .......... 54% 238M 0s\n", 341 | " 6300K .......... .......... .......... .......... .......... 55% 196M 0s\n", 342 | " 6350K .......... .......... .......... .......... .......... 55% 247M 0s\n", 343 | " 6400K .......... .......... .......... .......... .......... 56% 208M 0s\n", 344 | " 6450K .......... .......... .......... .......... .......... 56% 224M 0s\n", 345 | " 6500K .......... .......... .......... .......... .......... 56% 212M 0s\n", 346 | " 6550K .......... .......... .......... .......... .......... 57% 221M 0s\n", 347 | " 6600K .......... .......... .......... .......... .......... 57% 237M 0s\n", 348 | " 6650K .......... .......... .......... .......... .......... 58% 250M 0s\n", 349 | " 6700K .......... .......... .......... .......... .......... 58% 215M 0s\n", 350 | " 6750K .......... .......... .......... .......... .......... 59% 270M 0s\n", 351 | " 6800K .......... .......... .......... .......... .......... 59% 3.14M 0s\n", 352 | " 6850K .......... .......... .......... .......... .......... 59% 234M 0s\n", 353 | " 6900K .......... .......... .......... .......... .......... 60% 211M 0s\n", 354 | " 6950K .......... .......... .......... .......... .......... 60% 209M 0s\n", 355 | " 7000K .......... .......... .......... .......... .......... 61% 249M 0s\n", 356 | " 7050K .......... .......... .......... .......... .......... 61% 216M 0s\n", 357 | " 7100K .......... .......... .......... .......... .......... 62% 197M 0s\n", 358 | " 7150K .......... .......... .......... .......... .......... 62% 240M 0s\n", 359 | " 7200K .......... .......... .......... .......... .......... 62% 234M 0s\n", 360 | " 7250K .......... .......... .......... .......... .......... 63% 224M 0s\n", 361 | " 7300K .......... .......... .......... .......... .......... 63% 207M 0s\n", 362 | " 7350K .......... .......... .......... .......... .......... 64% 230M 0s\n", 363 | " 7400K .......... .......... .......... .......... .......... 64% 219M 0s\n", 364 | " 7450K .......... .......... .......... .......... .......... 65% 225M 0s\n", 365 | " 7500K .......... .......... .......... .......... .......... 65% 196M 0s\n", 366 | " 7550K .......... .......... .......... .......... .......... 66% 223M 0s\n", 367 | " 7600K .......... .......... .......... .......... .......... 66% 262M 0s\n", 368 | " 7650K .......... .......... .......... .......... .......... 66% 228M 0s\n", 369 | " 7700K .......... .......... .......... .......... .......... 67% 187M 0s\n", 370 | " 7750K .......... .......... .......... .......... .......... 67% 257M 0s\n", 371 | " 7800K .......... .......... .......... .......... .......... 68% 234M 0s\n", 372 | " 7850K .......... .......... .......... .......... .......... 68% 251M 0s\n", 373 | " 7900K .......... .......... .......... .......... .......... 69% 203M 0s\n", 374 | " 7950K .......... .......... .......... .......... .......... 69% 210M 0s\n", 375 | " 8000K .......... .......... .......... .......... .......... 69% 213M 0s\n", 376 | " 8050K .......... .......... .......... .......... .......... 70% 242M 0s\n", 377 | " 8100K .......... .......... .......... .......... .......... 70% 197M 0s\n", 378 | " 8150K .......... .......... .......... .......... .......... 71% 230M 0s\n", 379 | " 8200K .......... .......... .......... .......... .......... 71% 242M 0s\n", 380 | " 8250K .......... .......... .......... .......... .......... 72% 223M 0s\n", 381 | " 8300K .......... .......... .......... .......... .......... 72% 128M 0s\n", 382 | " 8350K .......... .......... .......... .......... .......... 72% 207M 0s\n", 383 | " 8400K .......... .......... .......... .......... .......... 73% 242M 0s\n", 384 | " 8450K .......... .......... .......... .......... .......... 73% 228M 0s\n", 385 | " 8500K .......... .......... .......... .......... .......... 74% 204M 0s\n", 386 | " 8550K .......... .......... .......... .......... .......... 74% 236M 0s\n", 387 | " 8600K .......... .......... .......... .......... .......... 75% 114M 0s\n", 388 | " 8650K .......... .......... .......... .......... .......... 75% 243M 0s\n", 389 | " 8700K .......... .......... .......... .......... .......... 76% 194M 0s\n", 390 | " 8750K .......... .......... .......... .......... .......... 76% 229M 0s\n", 391 | " 8800K .......... .......... .......... .......... .......... 76% 143M 0s\n", 392 | " 8850K .......... .......... .......... .......... .......... 77% 201M 0s\n", 393 | " 8900K .......... .......... .......... .......... .......... 77% 188M 0s\n", 394 | " 8950K .......... .......... .......... .......... .......... 78% 188M 0s\n", 395 | " 9000K .......... .......... .......... .......... .......... 78% 230M 0s\n", 396 | " 9050K .......... .......... .......... .......... .......... 79% 233M 0s\n", 397 | " 9100K .......... .......... .......... .......... .......... 79% 206M 0s\n", 398 | " 9150K .......... .......... .......... .......... .......... 79% 235M 0s\n", 399 | " 9200K .......... .......... .......... .......... .......... 80% 113M 0s\n", 400 | " 9250K .......... .......... .......... .......... .......... 80% 221M 0s\n", 401 | " 9300K .......... .......... .......... .......... .......... 81% 199M 0s\n", 402 | " 9350K .......... .......... .......... .......... .......... 81% 221M 0s\n", 403 | " 9400K .......... .......... .......... .......... .......... 82% 246M 0s\n", 404 | " 9450K .......... .......... .......... .......... .......... 82% 241M 0s\n", 405 | " 9500K .......... .......... .......... .......... .......... 82% 186M 0s\n", 406 | " 9550K .......... .......... .......... .......... .......... 83% 256M 0s\n", 407 | " 9600K .......... .......... .......... .......... .......... 83% 222M 0s\n", 408 | " 9650K .......... .......... .......... .......... .......... 84% 267M 0s\n", 409 | " 9700K .......... .......... .......... .......... .......... 84% 3.04M 0s\n", 410 | " 9750K .......... .......... .......... .......... .......... 85% 210M 0s\n", 411 | " 9800K .......... .......... .......... .......... .......... 85% 209M 0s\n", 412 | " 9850K .......... .......... .......... .......... .......... 86% 214M 0s\n", 413 | " 9900K .......... .......... .......... .......... .......... 86% 201M 0s\n", 414 | " 9950K .......... .......... .......... .......... .......... 86% 242M 0s\n", 415 | " 10000K .......... .......... .......... .......... .......... 87% 221M 0s\n", 416 | " 10050K .......... .......... .......... .......... .......... 87% 252M 0s\n", 417 | " 10100K .......... .......... .......... .......... .......... 88% 195M 0s\n", 418 | " 10150K .......... .......... .......... .......... .......... 88% 248M 0s\n", 419 | " 10200K .......... .......... .......... .......... .......... 89% 246M 0s\n", 420 | " 10250K .......... .......... .......... .......... .......... 89% 212M 0s\n", 421 | " 10300K .......... .......... .......... .......... .......... 89% 184M 0s\n", 422 | " 10350K .......... .......... .......... .......... .......... 90% 206M 0s\n", 423 | " 10400K .......... .......... .......... .......... .......... 90% 219M 0s\n", 424 | " 10450K .......... .......... .......... .......... .......... 91% 239M 0s\n", 425 | " 10500K .......... .......... .......... .......... .......... 91% 232M 0s\n", 426 | " 10550K .......... .......... .......... .......... .......... 92% 197M 0s\n", 427 | " 10600K .......... .......... .......... .......... .......... 92% 229M 0s\n", 428 | " 10650K .......... .......... .......... .......... .......... 92% 225M 0s\n", 429 | " 10700K .......... .......... .......... .......... .......... 93% 212M 0s\n", 430 | " 10750K .......... .......... .......... .......... .......... 93% 209M 0s\n", 431 | " 10800K .......... .......... .......... .......... .......... 94% 231M 0s\n", 432 | " 10850K .......... .......... .......... .......... .......... 94% 202M 0s\n", 433 | " 10900K .......... .......... .......... .......... .......... 95% 231M 0s\n", 434 | " 10950K .......... .......... .......... .......... .......... 95% 181M 0s\n", 435 | " 11000K .......... .......... .......... .......... .......... 96% 189M 0s\n", 436 | " 11050K .......... .......... .......... .......... .......... 96% 215M 0s\n", 437 | " 11100K .......... .......... .......... .......... .......... 96% 180M 0s\n", 438 | " 11150K .......... .......... .......... .......... .......... 97% 152M 0s\n", 439 | " 11200K .......... .......... .......... .......... .......... 97% 162M 0s\n", 440 | " 11250K .......... .......... .......... .......... .......... 98% 180M 0s\n", 441 | " 11300K .......... .......... .......... .......... .......... 98% 83.4M 0s\n", 442 | " 11350K .......... .......... .......... .......... .......... 99% 154M 0s\n", 443 | " 11400K .......... .......... .......... .......... .......... 99% 191M 0s\n", 444 | " 11450K .......... .......... .......... .......... .......... 99% 149M 0s\n", 445 | " 11500K ........ 100% 155M=0.3s\n", 446 | "\n", 447 | "2020-10-26 10:51:14 (37.3 MB/s) - ‘ag_news_csv.tgz.1’ saved [11784419/11784419]\n", 448 | "\n" 449 | ], 450 | "name": "stderr" 451 | } 452 | ] 453 | }, 454 | { 455 | "cell_type": "code", 456 | "metadata": { 457 | "id": "Rzxp8lfO4OC5", 458 | "outputId": "24c42252-9a48-4b59-ac04-0ca7eeddd328", 459 | "colab": { 460 | "base_uri": "https://localhost:8080/", 461 | "height": 391 462 | } 463 | }, 464 | "source": [ 465 | "import pandas as pd\n", 466 | "\n", 467 | "train_data = pd.read_csv('/content/data/ag_news_csv/train.csv', engine='python', encoding='utf-8', header =None, names=['Class Index',\t'Title',\t'Description'])\n", 468 | "test_data = pd.read_csv('/content/data/ag_news_csv/test.csv', engine='python', encoding='utf-8', header = None, names=['Class Index',\t'Title',\t'Description'])\n", 469 | "\n", 470 | "print('Training set summary\\n')\n", 471 | "print(train_data.describe())\n", 472 | "print('Test set summary\\n')\n", 473 | "print(test_data.describe())" 474 | ], 475 | "execution_count": 5, 476 | "outputs": [ 477 | { 478 | "output_type": "stream", 479 | "text": [ 480 | "Training set summary\n", 481 | "\n", 482 | " Class Index\n", 483 | "count 120000.000000\n", 484 | "mean 2.500000\n", 485 | "std 1.118039\n", 486 | "min 1.000000\n", 487 | "25% 1.750000\n", 488 | "50% 2.500000\n", 489 | "75% 3.250000\n", 490 | "max 4.000000\n", 491 | "Test set summary\n", 492 | "\n", 493 | " Class Index\n", 494 | "count 7600.000000\n", 495 | "mean 2.500000\n", 496 | "std 1.118108\n", 497 | "min 1.000000\n", 498 | "25% 1.750000\n", 499 | "50% 2.500000\n", 500 | "75% 3.250000\n", 501 | "max 4.000000\n" 502 | ], 503 | "name": "stdout" 504 | } 505 | ] 506 | }, 507 | { 508 | "cell_type": "markdown", 509 | "metadata": { 510 | "id": "KS2Nc-Nx4uyE" 511 | }, 512 | "source": [ 513 | "Now let's explore the examples for fine-tunning. We can just take the top 5 examples and labels by `ds_train.take(5)`, so that we can explore the dataset without the need to iterate over whole 25000 examples in train dataset. " 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "metadata": { 519 | "id": "rC6vxjRm4mvN", 520 | "outputId": "7390772a-fa8d-49fe-88d8-0f87d1c71277", 521 | "colab": { 522 | "base_uri": "https://localhost:8080/", 523 | "height": 204 524 | } 525 | }, 526 | "source": [ 527 | "train_data.head()" 528 | ], 529 | "execution_count": 6, 530 | "outputs": [ 531 | { 532 | "output_type": "execute_result", 533 | "data": { 534 | "text/html": [ 535 | "
\n", 536 | "\n", 549 | "\n", 550 | " \n", 551 | " \n", 552 | " \n", 553 | " \n", 554 | " \n", 555 | " \n", 556 | " \n", 557 | " \n", 558 | " \n", 559 | " \n", 560 | " \n", 561 | " \n", 562 | " \n", 563 | " \n", 564 | " \n", 565 | " \n", 566 | " \n", 567 | " \n", 568 | " \n", 569 | " \n", 570 | " \n", 571 | " \n", 572 | " \n", 573 | " \n", 574 | " \n", 575 | " \n", 576 | " \n", 577 | " \n", 578 | " \n", 579 | " \n", 580 | " \n", 581 | " \n", 582 | " \n", 583 | " \n", 584 | " \n", 585 | " \n", 586 | " \n", 587 | " \n", 588 | " \n", 589 | " \n", 590 | "
Class IndexTitleDescription
03Wall St. Bears Claw Back Into the Black (Reuters)Reuters - Short-sellers, Wall Street's dwindli...
13Carlyle Looks Toward Commercial Aerospace (Reu...Reuters - Private investment firm Carlyle Grou...
23Oil and Economy Cloud Stocks' Outlook (Reuters)Reuters - Soaring crude prices plus worries\\ab...
33Iraq Halts Oil Exports from Main Southern Pipe...Reuters - Authorities have halted oil export\\f...
43Oil prices soar to all-time record, posing new...AFP - Tearaway world oil prices, toppling reco...
\n", 591 | "
" 592 | ], 593 | "text/plain": [ 594 | " Class Index ... Description\n", 595 | "0 3 ... Reuters - Short-sellers, Wall Street's dwindli...\n", 596 | "1 3 ... Reuters - Private investment firm Carlyle Grou...\n", 597 | "2 3 ... Reuters - Soaring crude prices plus worries\\ab...\n", 598 | "3 3 ... Reuters - Authorities have halted oil export\\f...\n", 599 | "4 3 ... AFP - Tearaway world oil prices, toppling reco...\n", 600 | "\n", 601 | "[5 rows x 3 columns]" 602 | ] 603 | }, 604 | "metadata": { 605 | "tags": [] 606 | }, 607 | "execution_count": 6 608 | } 609 | ] 610 | }, 611 | { 612 | "cell_type": "code", 613 | "metadata": { 614 | "id": "kXNeph92CCuv", 615 | "outputId": "1f971127-6c20-4357-96cf-9c0ff5e2b759", 616 | "colab": { 617 | "base_uri": "https://localhost:8080/", 618 | "height": 204 619 | } 620 | }, 621 | "source": [ 622 | "test_data.head()" 623 | ], 624 | "execution_count": 7, 625 | "outputs": [ 626 | { 627 | "output_type": "execute_result", 628 | "data": { 629 | "text/html": [ 630 | "
\n", 631 | "\n", 644 | "\n", 645 | " \n", 646 | " \n", 647 | " \n", 648 | " \n", 649 | " \n", 650 | " \n", 651 | " \n", 652 | " \n", 653 | " \n", 654 | " \n", 655 | " \n", 656 | " \n", 657 | " \n", 658 | " \n", 659 | " \n", 660 | " \n", 661 | " \n", 662 | " \n", 663 | " \n", 664 | " \n", 665 | " \n", 666 | " \n", 667 | " \n", 668 | " \n", 669 | " \n", 670 | " \n", 671 | " \n", 672 | " \n", 673 | " \n", 674 | " \n", 675 | " \n", 676 | " \n", 677 | " \n", 678 | " \n", 679 | " \n", 680 | " \n", 681 | " \n", 682 | " \n", 683 | " \n", 684 | " \n", 685 | "
Class IndexTitleDescription
03Fears for T N pension after talksUnions representing workers at Turner Newall...
14The Race is On: Second Private Team Sets Launc...SPACE.com - TORONTO, Canada -- A second\\team o...
24Ky. Company Wins Grant to Study Peptides (AP)AP - A company founded by a chemistry research...
34Prediction Unit Helps Forecast Wildfires (AP)AP - It's barely dawn when Mike Fitzpatrick st...
44Calif. Aims to Limit Farm-Related Smog (AP)AP - Southern California's smog-fighting agenc...
\n", 686 | "
" 687 | ], 688 | "text/plain": [ 689 | " Class Index ... Description\n", 690 | "0 3 ... Unions representing workers at Turner Newall...\n", 691 | "1 4 ... SPACE.com - TORONTO, Canada -- A second\\team o...\n", 692 | "2 4 ... AP - A company founded by a chemistry research...\n", 693 | "3 4 ... AP - It's barely dawn when Mike Fitzpatrick st...\n", 694 | "4 4 ... AP - Southern California's smog-fighting agenc...\n", 695 | "\n", 696 | "[5 rows x 3 columns]" 697 | ] 698 | }, 699 | "metadata": { 700 | "tags": [] 701 | }, 702 | "execution_count": 7 703 | } 704 | ] 705 | }, 706 | { 707 | "cell_type": "markdown", 708 | "metadata": { 709 | "id": "lsqhVrrmDWQ2" 710 | }, 711 | "source": [ 712 | "## Import libraries" 713 | ] 714 | }, 715 | { 716 | "cell_type": "markdown", 717 | "metadata": { 718 | "id": "3xh49OwDisal" 719 | }, 720 | "source": [ 721 | "Here we import all the libraries we need to build and then train our model." 722 | ] 723 | }, 724 | { 725 | "cell_type": "code", 726 | "metadata": { 727 | "id": "FGbQCrqhDVrO", 728 | "outputId": "d1b90c04-1ab6-48d0-cccb-73c95f7e342b", 729 | "colab": { 730 | "base_uri": "https://localhost:8080/", 731 | "height": 102 732 | } 733 | }, 734 | "source": [ 735 | "import re\n", 736 | "import string\n", 737 | "import numpy as np\n", 738 | "\n", 739 | "from nltk.corpus import stopwords\n", 740 | "from nltk.tokenize import word_tokenize\n", 741 | "from sklearn.model_selection import train_test_split\n", 742 | "\n", 743 | "import tensorflow as tf\n", 744 | "import tensorflow_datasets as tfds\n", 745 | "from tensorflow.keras.models import Sequential\n", 746 | "from tensorflow.keras.layers import Conv1D, MaxPool1D, Dropout, Dense, GlobalMaxPool1D, Embedding, Activation\n", 747 | "from keras.utils import to_categorical\n", 748 | "from keras.preprocessing.text import Tokenizer\n", 749 | "from keras.preprocessing.sequence import pad_sequences\n", 750 | "from sklearn import preprocessing\n", 751 | "from sklearn.metrics import classification_report\n", 752 | "from sklearn.model_selection import train_test_split\n", 753 | "\n", 754 | "import nltk\n", 755 | "nltk.download('punkt')\n", 756 | "nltk.download('stopwords')" 757 | ], 758 | "execution_count": 8, 759 | "outputs": [ 760 | { 761 | "output_type": "stream", 762 | "text": [ 763 | "[nltk_data] Downloading package punkt to /root/nltk_data...\n", 764 | "[nltk_data] Package punkt is already up-to-date!\n", 765 | "[nltk_data] Downloading package stopwords to /root/nltk_data...\n", 766 | "[nltk_data] Package stopwords is already up-to-date!\n" 767 | ], 768 | "name": "stdout" 769 | }, 770 | { 771 | "output_type": "execute_result", 772 | "data": { 773 | "text/plain": [ 774 | "True" 775 | ] 776 | }, 777 | "metadata": { 778 | "tags": [] 779 | }, 780 | "execution_count": 8 781 | } 782 | ] 783 | }, 784 | { 785 | "cell_type": "markdown", 786 | "metadata": { 787 | "id": "Y6qJCWp840xY" 788 | }, 789 | "source": [ 790 | "## Data Preprocessing\n", 791 | "\n", 792 | "Here we have to prepare out data, with some text preprocessing, so add special tokens, removing punctuation and stopwords if necessary, and so on." 793 | ] 794 | }, 795 | { 796 | "cell_type": "markdown", 797 | "metadata": { 798 | "id": "O9ZwoM5nkOSt" 799 | }, 800 | "source": [ 801 | "### Rename columns" 802 | ] 803 | }, 804 | { 805 | "cell_type": "code", 806 | "metadata": { 807 | "id": "QXAkExDMCva6" 808 | }, 809 | "source": [ 810 | "# rename labels\n", 811 | "\n", 812 | "labels = {1:'World News', 2:'Sports News', 3:'Business News', 4:'Science-Technology News'}\n", 813 | "\n", 814 | "train_data['label'] = train_data['Class Index'].map(labels)\n", 815 | "test_data['label'] = test_data['Class Index'].map(labels)\n", 816 | "\n", 817 | "train_data = train_data.drop(columns=['Class Index'])\n", 818 | "test_data = test_data.drop(columns=['Class Index'])" 819 | ], 820 | "execution_count": 9, 821 | "outputs": [] 822 | }, 823 | { 824 | "cell_type": "markdown", 825 | "metadata": { 826 | "id": "HSdZX6rrkTOK" 827 | }, 828 | "source": [ 829 | "### Remove punctuation" 830 | ] 831 | }, 832 | { 833 | "cell_type": "markdown", 834 | "metadata": { 835 | "id": "Fv1kHPdYiz2N" 836 | }, 837 | "source": [ 838 | "First of all, we define a function to remove punctuation." 839 | ] 840 | }, 841 | { 842 | "cell_type": "code", 843 | "metadata": { 844 | "id": "LTm81Vlm4xEr" 845 | }, 846 | "source": [ 847 | "# The old and loved remove punctuation function\n", 848 | "\n", 849 | "def remove_punc(text):\n", 850 | " text = re.sub('\\[.*?\\]', '', text)\n", 851 | " text = re.sub('https?://\\S+|www\\.\\S+', '', text)\n", 852 | " text = re.sub('<.*?>+', '', text)\n", 853 | " text = re.sub('[%s]' % re.escape(string.punctuation), '', text)\n", 854 | " text = re.sub('\\n', '', text)\n", 855 | " text = re.sub('\\w*\\d\\w*', '', text)\n", 856 | " return text" 857 | ], 858 | "execution_count": null, 859 | "outputs": [] 860 | }, 861 | { 862 | "cell_type": "code", 863 | "metadata": { 864 | "id": "YW-T3kbx5otD" 865 | }, 866 | "source": [ 867 | "train_data['Text'] = train_data['Description'].apply(lambda x: remove_punc(x))\n", 868 | "test_data['Text'] = test_data['Description'].apply(lambda x: remove_punc(x))" 869 | ], 870 | "execution_count": null, 871 | "outputs": [] 872 | }, 873 | { 874 | "cell_type": "code", 875 | "metadata": { 876 | "id": "p5aNMKEr7asa", 877 | "outputId": "0cbd8f20-dc6b-4495-8b24-1c7ae84163ed", 878 | "colab": { 879 | "base_uri": "https://localhost:8080/", 880 | "height": 204 881 | } 882 | }, 883 | "source": [ 884 | "train_data.head()" 885 | ], 886 | "execution_count": null, 887 | "outputs": [ 888 | { 889 | "output_type": "execute_result", 890 | "data": { 891 | "text/html": [ 892 | "
\n", 893 | "\n", 906 | "\n", 907 | " \n", 908 | " \n", 909 | " \n", 910 | " \n", 911 | " \n", 912 | " \n", 913 | " \n", 914 | " \n", 915 | " \n", 916 | " \n", 917 | " \n", 918 | " \n", 919 | " \n", 920 | " \n", 921 | " \n", 922 | " \n", 923 | " \n", 924 | " \n", 925 | " \n", 926 | " \n", 927 | " \n", 928 | " \n", 929 | " \n", 930 | " \n", 931 | " \n", 932 | " \n", 933 | " \n", 934 | " \n", 935 | " \n", 936 | " \n", 937 | " \n", 938 | " \n", 939 | " \n", 940 | " \n", 941 | " \n", 942 | " \n", 943 | " \n", 944 | " \n", 945 | " \n", 946 | " \n", 947 | " \n", 948 | " \n", 949 | " \n", 950 | " \n", 951 | " \n", 952 | " \n", 953 | "
Class IndexTitleDescriptionText
03Wall St. Bears Claw Back Into the Black (Reuters)Reuters - Short-sellers, Wall Street's dwindli...Reuters Shortsellers Wall Streets dwindlingba...
13Carlyle Looks Toward Commercial Aerospace (Reu...Reuters - Private investment firm Carlyle Grou...Reuters Private investment firm Carlyle Group...
23Oil and Economy Cloud Stocks' Outlook (Reuters)Reuters - Soaring crude prices plus worries\\ab...Reuters Soaring crude prices plus worriesabou...
33Iraq Halts Oil Exports from Main Southern Pipe...Reuters - Authorities have halted oil export\\f...Reuters Authorities have halted oil exportflo...
43Oil prices soar to all-time record, posing new...AFP - Tearaway world oil prices, toppling reco...AFP Tearaway world oil prices toppling record...
\n", 954 | "
" 955 | ], 956 | "text/plain": [ 957 | " Class Index ... Text\n", 958 | "0 3 ... Reuters Shortsellers Wall Streets dwindlingba...\n", 959 | "1 3 ... Reuters Private investment firm Carlyle Group...\n", 960 | "2 3 ... Reuters Soaring crude prices plus worriesabou...\n", 961 | "3 3 ... Reuters Authorities have halted oil exportflo...\n", 962 | "4 3 ... AFP Tearaway world oil prices toppling record...\n", 963 | "\n", 964 | "[5 rows x 4 columns]" 965 | ] 966 | }, 967 | "metadata": { 968 | "tags": [] 969 | }, 970 | "execution_count": 12 971 | } 972 | ] 973 | }, 974 | { 975 | "cell_type": "markdown", 976 | "metadata": { 977 | "id": "ylOdDFAjkY7G" 978 | }, 979 | "source": [ 980 | "### Clean text" 981 | ] 982 | }, 983 | { 984 | "cell_type": "markdown", 985 | "metadata": { 986 | "id": "tZBFx44Fi6ua" 987 | }, 988 | "source": [ 989 | "Hence, making use of nltk tokeniser, we clean our text:\n", 990 | "\n", 991 | "1. Lowercase our texts.\n", 992 | "\n", 993 | "2. Remove stopwords." 994 | ] 995 | }, 996 | { 997 | "cell_type": "code", 998 | "metadata": { 999 | "id": "JmZscfdsDpBH" 1000 | }, 1001 | "source": [ 1002 | "# data cleaning and remove stopwords\n", 1003 | "\n", 1004 | "def data_cleaner(text): \n", 1005 | " lower_case = text.lower()\n", 1006 | " tokens=word_tokenize(lower_case)\n", 1007 | " return (\" \".join(tokens)).strip()\n", 1008 | "\n", 1009 | "def remove_stopwords (text): \n", 1010 | " list1=[word for word in text.split() if word not in stopwords.words('english')]\n", 1011 | " return \" \".join(list1)\n", 1012 | "\n", 1013 | "train_data['Text'] = train_data['Text'].apply(lambda x: data_cleaner(x))\n", 1014 | "test_data['Text'] = test_data['Text'].apply(lambda x: data_cleaner(x))\n", 1015 | "\n", 1016 | "train_data['Text'] = train_data['Text'].apply(lambda x: remove_stopwords(x))\n", 1017 | "test_data['Text'] = test_data['Text'].apply(lambda x: remove_stopwords(x))" 1018 | ], 1019 | "execution_count": null, 1020 | "outputs": [] 1021 | }, 1022 | { 1023 | "cell_type": "code", 1024 | "metadata": { 1025 | "id": "W1k23Ui9fTYS" 1026 | }, 1027 | "source": [ 1028 | "train_data['Text'] = train_data['Description']\n", 1029 | "test_data['Text'] = test_data['Description']" 1030 | ], 1031 | "execution_count": 10, 1032 | "outputs": [] 1033 | }, 1034 | { 1035 | "cell_type": "markdown", 1036 | "metadata": { 1037 | "id": "SuXZH2ZqjwhZ" 1038 | }, 1039 | "source": [ 1040 | "### Tokenise" 1041 | ] 1042 | }, 1043 | { 1044 | "cell_type": "markdown", 1045 | "metadata": { 1046 | "id": "NEDdAmdakhvN" 1047 | }, 1048 | "source": [ 1049 | "We make use of Keras tokeniser to assign to each word a number." 1050 | ] 1051 | }, 1052 | { 1053 | "cell_type": "code", 1054 | "metadata": { 1055 | "id": "vlxY52a3dGNx" 1056 | }, 1057 | "source": [ 1058 | "#@title Tokeniser configuration\n", 1059 | "\n", 1060 | "max_len = 75#@param {type:\"integer\"}" 1061 | ], 1062 | "execution_count": 11, 1063 | "outputs": [] 1064 | }, 1065 | { 1066 | "cell_type": "code", 1067 | "metadata": { 1068 | "id": "aO03dJCrGTP8" 1069 | }, 1070 | "source": [ 1071 | "tokeniser = Tokenizer()\n", 1072 | "tokeniser.fit_on_texts(train_data['Text'])\n", 1073 | "\n", 1074 | "tokenised_text = tokeniser.texts_to_sequences(train_data['Text'])\n", 1075 | "tokenised_text = pad_sequences(tokenised_text, maxlen=max_len)" 1076 | ], 1077 | "execution_count": 12, 1078 | "outputs": [] 1079 | }, 1080 | { 1081 | "cell_type": "code", 1082 | "metadata": { 1083 | "id": "Tx-UJnaiGm8l" 1084 | }, 1085 | "source": [ 1086 | "encoded_labels = preprocessing.LabelEncoder()\n", 1087 | "y = encoded_labels.fit_transform(train_data['label'])\n", 1088 | "y = to_categorical(y)" 1089 | ], 1090 | "execution_count": 13, 1091 | "outputs": [] 1092 | }, 1093 | { 1094 | "cell_type": "code", 1095 | "metadata": { 1096 | "id": "z0HUzddeG_Ri" 1097 | }, 1098 | "source": [ 1099 | "tokenised_text_test = tokeniser.texts_to_sequences(test_data['Text'])\n", 1100 | "tokenised_text_test = pad_sequences(tokenised_text_test, maxlen=max_len)" 1101 | ], 1102 | "execution_count": 14, 1103 | "outputs": [] 1104 | }, 1105 | { 1106 | "cell_type": "code", 1107 | "metadata": { 1108 | "id": "8LfTxo-rHgzn" 1109 | }, 1110 | "source": [ 1111 | "y_test = encoded_labels.transform(test_data['label'])\n", 1112 | "y_test = to_categorical(y_test)" 1113 | ], 1114 | "execution_count": 15, 1115 | "outputs": [] 1116 | }, 1117 | { 1118 | "cell_type": "code", 1119 | "metadata": { 1120 | "id": "F7QPvHrVKycK" 1121 | }, 1122 | "source": [ 1123 | "vocab_size = len(tokeniser.word_index) + 1" 1124 | ], 1125 | "execution_count": 16, 1126 | "outputs": [] 1127 | }, 1128 | { 1129 | "cell_type": "markdown", 1130 | "metadata": { 1131 | "id": "uWDqS0OJkp5x" 1132 | }, 1133 | "source": [ 1134 | "We also export the dictionary word-to-index to a `json` file, this will be needed in order to convert a text to-be-classified in a format that the model can digest." 1135 | ] 1136 | }, 1137 | { 1138 | "cell_type": "code", 1139 | "metadata": { 1140 | "id": "q4NdZrIiaKIu" 1141 | }, 1142 | "source": [ 1143 | "# Export the ditionary word-to-index to a json file\n", 1144 | "import json \n", 1145 | "with open( 'word_dict.json' , 'w' ) as file: \n", 1146 | " json.dump(tokeniser.word_index , file )" 1147 | ], 1148 | "execution_count": 17, 1149 | "outputs": [] 1150 | }, 1151 | { 1152 | "cell_type": "markdown", 1153 | "metadata": { 1154 | "id": "e2Esa71rIV7c" 1155 | }, 1156 | "source": [ 1157 | "### Convert data to TensorFlow datasets" 1158 | ] 1159 | }, 1160 | { 1161 | "cell_type": "markdown", 1162 | "metadata": { 1163 | "id": "NCH1Q6f9k56Z" 1164 | }, 1165 | "source": [ 1166 | "We convert data to Tensorflow dataset, in order to feed the Keras model." 1167 | ] 1168 | }, 1169 | { 1170 | "cell_type": "code", 1171 | "metadata": { 1172 | "id": "s0olDSVjHXuB" 1173 | }, 1174 | "source": [ 1175 | "train_dataset = tf.data.Dataset.from_tensor_slices((tokenised_text, y))\n", 1176 | "test_dataset = tf.data.Dataset.from_tensor_slices((tokenised_text_test, y_test))" 1177 | ], 1178 | "execution_count": 18, 1179 | "outputs": [] 1180 | }, 1181 | { 1182 | "cell_type": "markdown", 1183 | "metadata": { 1184 | "id": "chDp-zhlIdE6" 1185 | }, 1186 | "source": [ 1187 | "# Building the model" 1188 | ] 1189 | }, 1190 | { 1191 | "cell_type": "code", 1192 | "metadata": { 1193 | "id": "7iRIDaBKbfQP" 1194 | }, 1195 | "source": [ 1196 | "#@title Model Parameters\n", 1197 | "#@markdown Here we give a minimal set of parameters for model configuration.\n", 1198 | "\n", 1199 | "emb_dim = 64 #@param {type:\"integer\"}\n", 1200 | "dropout_rate = 0.3#@param {type: \"number\"}\n", 1201 | "n_labels = len(labels)\n", 1202 | "\n", 1203 | "learning_rate = 0.0006#@param {type: \"number\"}\n", 1204 | "\n", 1205 | "loss = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n", 1206 | "metric = tf.keras.metrics.CategoricalAccuracy('accuracy')\n", 1207 | "opt = tf.keras.optimizers.Adam(learning_rate = learning_rate)" 1208 | ], 1209 | "execution_count": 22, 1210 | "outputs": [] 1211 | }, 1212 | { 1213 | "cell_type": "markdown", 1214 | "metadata": { 1215 | "id": "zQuGa5eNlAvC" 1216 | }, 1217 | "source": [ 1218 | "We are now ready to build our model, making use of Keras `Sequential` object." 1219 | ] 1220 | }, 1221 | { 1222 | "cell_type": "code", 1223 | "metadata": { 1224 | "id": "CpEGQMkZHyAf", 1225 | "outputId": "17b30522-856a-4961-b3c1-46f9ebd5fbbf", 1226 | "colab": { 1227 | "base_uri": "https://localhost:8080/", 1228 | "height": 697 1229 | } 1230 | }, 1231 | "source": [ 1232 | "# build the model\n", 1233 | "keras_model = Sequential()\n", 1234 | "keras_model.add(Embedding(vocab_size, output_dim = emb_dim, input_length=max_len))\n", 1235 | "keras_model.add(Dropout(dropout_rate))\n", 1236 | "keras_model.add(Conv1D(50, 3, activation='relu', padding='same', strides=1))\n", 1237 | "keras_model.add(MaxPool1D())\n", 1238 | "keras_model.add(Dropout(dropout_rate))\n", 1239 | "keras_model.add(Conv1D(100, 3, activation='relu', padding='same', strides=1))\n", 1240 | "keras_model.add(MaxPool1D())\n", 1241 | "keras_model.add(Dropout(dropout_rate))\n", 1242 | "keras_model.add(Conv1D(200, 3, activation='relu', padding='same', strides=1))\n", 1243 | "keras_model.add(GlobalMaxPool1D())\n", 1244 | "keras_model.add(Dropout(dropout_rate))\n", 1245 | "keras_model.add(Dense(100))\n", 1246 | "keras_model.add(Activation('relu'))\n", 1247 | "keras_model.add(Dropout(dropout_rate))\n", 1248 | "keras_model.add(Dense(n_labels))\n", 1249 | "keras_model.add(Activation('softmax'))\n", 1250 | "keras_model.compile(loss=loss, metrics=[metric], optimizer=opt)\n", 1251 | "keras_model.summary()" 1252 | ], 1253 | "execution_count": 23, 1254 | "outputs": [ 1255 | { 1256 | "output_type": "stream", 1257 | "text": [ 1258 | "Model: \"sequential_1\"\n", 1259 | "_________________________________________________________________\n", 1260 | "Layer (type) Output Shape Param # \n", 1261 | "=================================================================\n", 1262 | "embedding_1 (Embedding) (None, 75, 64) 4079296 \n", 1263 | "_________________________________________________________________\n", 1264 | "dropout_5 (Dropout) (None, 75, 64) 0 \n", 1265 | "_________________________________________________________________\n", 1266 | "conv1d_3 (Conv1D) (None, 75, 50) 9650 \n", 1267 | "_________________________________________________________________\n", 1268 | "max_pooling1d_2 (MaxPooling1 (None, 37, 50) 0 \n", 1269 | "_________________________________________________________________\n", 1270 | "dropout_6 (Dropout) (None, 37, 50) 0 \n", 1271 | "_________________________________________________________________\n", 1272 | "conv1d_4 (Conv1D) (None, 37, 100) 15100 \n", 1273 | "_________________________________________________________________\n", 1274 | "max_pooling1d_3 (MaxPooling1 (None, 18, 100) 0 \n", 1275 | "_________________________________________________________________\n", 1276 | "dropout_7 (Dropout) (None, 18, 100) 0 \n", 1277 | "_________________________________________________________________\n", 1278 | "conv1d_5 (Conv1D) (None, 18, 200) 60200 \n", 1279 | "_________________________________________________________________\n", 1280 | "global_max_pooling1d_1 (Glob (None, 200) 0 \n", 1281 | "_________________________________________________________________\n", 1282 | "dropout_8 (Dropout) (None, 200) 0 \n", 1283 | "_________________________________________________________________\n", 1284 | "dense_2 (Dense) (None, 100) 20100 \n", 1285 | "_________________________________________________________________\n", 1286 | "activation_2 (Activation) (None, 100) 0 \n", 1287 | "_________________________________________________________________\n", 1288 | "dropout_9 (Dropout) (None, 100) 0 \n", 1289 | "_________________________________________________________________\n", 1290 | "dense_3 (Dense) (None, 4) 404 \n", 1291 | "_________________________________________________________________\n", 1292 | "activation_3 (Activation) (None, 4) 0 \n", 1293 | "=================================================================\n", 1294 | "Total params: 4,184,750\n", 1295 | "Trainable params: 4,184,750\n", 1296 | "Non-trainable params: 0\n", 1297 | "_________________________________________________________________\n" 1298 | ], 1299 | "name": "stdout" 1300 | } 1301 | ] 1302 | }, 1303 | { 1304 | "cell_type": "markdown", 1305 | "metadata": { 1306 | "id": "j2aNBmVAlLXk" 1307 | }, 1308 | "source": [ 1309 | "# Training" 1310 | ] 1311 | }, 1312 | { 1313 | "cell_type": "markdown", 1314 | "metadata": { 1315 | "id": "YiE1kwqflSPI" 1316 | }, 1317 | "source": [ 1318 | "We are now ready to launch the training, though the `fit` method, we set the numebr of epochs and launch the model." 1319 | ] 1320 | }, 1321 | { 1322 | "cell_type": "code", 1323 | "metadata": { 1324 | "id": "gW4Mynh4LBOa", 1325 | "outputId": "d7e184d8-e40a-4f01-c999-0599b4b31c89", 1326 | "colab": { 1327 | "base_uri": "https://localhost:8080/", 1328 | "height": 272 1329 | } 1330 | }, 1331 | "source": [ 1332 | "#@title Model Training\n", 1333 | "#@markdown We can move the slider to set number of epochs \n", 1334 | "#@markdown and give a different batch size.\n", 1335 | "\n", 1336 | "number_of_epochs = 7 #@param {type: \"slider\", min: 1, max: 12}\n", 1337 | "batch_size = 64 #@param [\"2\", \"8\", \"16\", \"32\", \"64\", \"128\", \"256\", \"512\"] {type:\"raw\", allow-input: true}\n", 1338 | "\n", 1339 | "# train dataset\n", 1340 | "ds_train_encoded = train_dataset.shuffle(10000).batch(batch_size)\n", 1341 | "\n", 1342 | "# test dataset\n", 1343 | "ds_test_encoded = test_dataset.batch(batch_size)\n", 1344 | "\n", 1345 | "keras_model.fit(ds_train_encoded, epochs=number_of_epochs, validation_data=ds_test_encoded)" 1346 | ], 1347 | "execution_count": 24, 1348 | "outputs": [ 1349 | { 1350 | "output_type": "stream", 1351 | "text": [ 1352 | "Epoch 1/7\n", 1353 | "1875/1875 [==============================] - 73s 39ms/step - loss: 0.9571 - accuracy: 0.7741 - val_loss: 0.8554 - val_accuracy: 0.8867\n", 1354 | "Epoch 2/7\n", 1355 | "1875/1875 [==============================] - 72s 38ms/step - loss: 0.8462 - accuracy: 0.8962 - val_loss: 0.8482 - val_accuracy: 0.8943\n", 1356 | "Epoch 3/7\n", 1357 | "1875/1875 [==============================] - 72s 39ms/step - loss: 0.8337 - accuracy: 0.9089 - val_loss: 0.8438 - val_accuracy: 0.8986\n", 1358 | "Epoch 4/7\n", 1359 | "1875/1875 [==============================] - 72s 38ms/step - loss: 0.8272 - accuracy: 0.9157 - val_loss: 0.8450 - val_accuracy: 0.8980\n", 1360 | "Epoch 5/7\n", 1361 | "1875/1875 [==============================] - 72s 38ms/step - loss: 0.8225 - accuracy: 0.9205 - val_loss: 0.8434 - val_accuracy: 0.8988\n", 1362 | "Epoch 6/7\n", 1363 | "1875/1875 [==============================] - 72s 38ms/step - loss: 0.8207 - accuracy: 0.9225 - val_loss: 0.8434 - val_accuracy: 0.8993\n", 1364 | "Epoch 7/7\n", 1365 | "1875/1875 [==============================] - 72s 38ms/step - loss: 0.8187 - accuracy: 0.9245 - val_loss: 0.8388 - val_accuracy: 0.9042\n" 1366 | ], 1367 | "name": "stdout" 1368 | }, 1369 | { 1370 | "output_type": "execute_result", 1371 | "data": { 1372 | "text/plain": [ 1373 | "" 1374 | ] 1375 | }, 1376 | "metadata": { 1377 | "tags": [] 1378 | }, 1379 | "execution_count": 24 1380 | } 1381 | ] 1382 | }, 1383 | { 1384 | "cell_type": "markdown", 1385 | "metadata": { 1386 | "id": "YTAkbxmAkzXw" 1387 | }, 1388 | "source": [ 1389 | "## Evaluation" 1390 | ] 1391 | }, 1392 | { 1393 | "cell_type": "code", 1394 | "metadata": { 1395 | "id": "Ur72xoP8k2cy", 1396 | "outputId": "281b88cb-a1a3-45ea-ba91-b28436de1cbe", 1397 | "colab": { 1398 | "base_uri": "https://localhost:8080/", 1399 | "height": 221 1400 | } 1401 | }, 1402 | "source": [ 1403 | "y_pred = to_categorical(np.argmax(keras_model.predict(tokenised_text_test), axis=1))\n", 1404 | "\n", 1405 | "print(classification_report(y_test, y_pred, target_names=labels.values(), digits=4))" 1406 | ], 1407 | "execution_count": 25, 1408 | "outputs": [ 1409 | { 1410 | "output_type": "stream", 1411 | "text": [ 1412 | " precision recall f1-score support\n", 1413 | "\n", 1414 | " World News 0.8657 0.8616 0.8636 1900\n", 1415 | " Sports News 0.8713 0.8905 0.8808 1900\n", 1416 | " Business News 0.9518 0.9763 0.9639 1900\n", 1417 | "Science-Technology News 0.9285 0.8884 0.9080 1900\n", 1418 | "\n", 1419 | " micro avg 0.9042 0.9042 0.9042 7600\n", 1420 | " macro avg 0.9043 0.9042 0.9041 7600\n", 1421 | " weighted avg 0.9043 0.9042 0.9041 7600\n", 1422 | " samples avg 0.9042 0.9042 0.9042 7600\n", 1423 | "\n" 1424 | ], 1425 | "name": "stdout" 1426 | } 1427 | ] 1428 | }, 1429 | { 1430 | "cell_type": "markdown", 1431 | "metadata": { 1432 | "id": "TffY8C8amVJR" 1433 | }, 1434 | "source": [ 1435 | "# Predictions" 1436 | ] 1437 | }, 1438 | { 1439 | "cell_type": "markdown", 1440 | "metadata": { 1441 | "id": "aNaGZtuMmZKQ" 1442 | }, 1443 | "source": [ 1444 | "Finally, we can now try to make predictions with our model.\n", 1445 | "\n", 1446 | "The function `encode` below takes a text stream and returns the sequence of word indices. \n", 1447 | "\n", 1448 | "The encoded text is the input of the `predict` method of our model." 1449 | ] 1450 | }, 1451 | { 1452 | "cell_type": "code", 1453 | "metadata": { 1454 | "id": "EBRsoV-_Ykh5" 1455 | }, 1456 | "source": [ 1457 | "def encode(text):\n", 1458 | " text = tokeniser.texts_to_sequences(text)\n", 1459 | " return pad_sequences(text, maxlen=max_len)" 1460 | ], 1461 | "execution_count": 26, 1462 | "outputs": [] 1463 | }, 1464 | { 1465 | "cell_type": "markdown", 1466 | "metadata": { 1467 | "id": "DIhV0Wjqmxx3" 1468 | }, 1469 | "source": [ 1470 | "Here some examples. \n", 1471 | "Feel free to add as many other sentences as you like." 1472 | ] 1473 | }, 1474 | { 1475 | "cell_type": "code", 1476 | "metadata": { 1477 | "id": "s_yai4MLZRfu" 1478 | }, 1479 | "source": [ 1480 | "additional_sentence = \"Apple iphone 12 is out!\" #@param {type:\"string\"}\n", 1481 | "\n", 1482 | "my_sentences = ['President Bush wants the war in Iraq, again', \n", 1483 | " \"LeBron James wins the NBA championship with Los Angeles Lakers\", \n", 1484 | " \"Eni stock action value rise up to 14$\",\n", 1485 | " \"Futures in New York held near $41 a barrel after Saudi Oil Minister Prince Abdulaziz Bin Salman called on the OPEC+ alliance to be proactive in the face of uncertain demand. Yet a draft statement from the meeting made no mention of any changes to the current deal, which calls for production cuts to be eased from January. The market is also looking out for any signs that a stimulus deal can still be agreed in Washington ahead of the election while a resurgence in the pandemic threatens any recovery.\",\n", 1486 | " additional_sentence\n", 1487 | " ]\n", 1488 | "\n", 1489 | "encode(my_sentences);" 1490 | ], 1491 | "execution_count": 27, 1492 | "outputs": [] 1493 | }, 1494 | { 1495 | "cell_type": "markdown", 1496 | "metadata": { 1497 | "id": "GClE9Y94nUAo" 1498 | }, 1499 | "source": [ 1500 | "`predict` method returns a vector of probablities." 1501 | ] 1502 | }, 1503 | { 1504 | "cell_type": "code", 1505 | "metadata": { 1506 | "id": "t9fUlVDJZcik", 1507 | "outputId": "64dcf7b3-58ec-42e2-af68-26cd5800d951", 1508 | "colab": { 1509 | "base_uri": "https://localhost:8080/", 1510 | "height": 119 1511 | } 1512 | }, 1513 | "source": [ 1514 | "keras_model.predict(encode(my_sentences))" 1515 | ], 1516 | "execution_count": 28, 1517 | "outputs": [ 1518 | { 1519 | "output_type": "execute_result", 1520 | "data": { 1521 | "text/plain": [ 1522 | "array([[2.4516769e-34, 2.4753018e-34, 9.8879884e-30, 1.0000000e+00],\n", 1523 | " [0.0000000e+00, 0.0000000e+00, 1.0000000e+00, 0.0000000e+00],\n", 1524 | " [1.0000000e+00, 5.2323827e-27, 1.5954859e-30, 6.1629427e-29],\n", 1525 | " [1.0000000e+00, 1.8224776e-11, 7.9000709e-11, 3.5611195e-11],\n", 1526 | " [0.0000000e+00, 1.0000000e+00, 0.0000000e+00, 0.0000000e+00]],\n", 1527 | " dtype=float32)" 1528 | ] 1529 | }, 1530 | "metadata": { 1531 | "tags": [] 1532 | }, 1533 | "execution_count": 28 1534 | } 1535 | ] 1536 | }, 1537 | { 1538 | "cell_type": "markdown", 1539 | "metadata": { 1540 | "id": "2vYthelGnbms" 1541 | }, 1542 | "source": [ 1543 | "In order to get the predicted class, one can call the `argmax` function." 1544 | ] 1545 | }, 1546 | { 1547 | "cell_type": "code", 1548 | "metadata": { 1549 | "id": "UAaREXccaZD6", 1550 | "outputId": "4ac1f1d4-6f1e-4cb6-9aad-1bfa2dd83b8c", 1551 | "colab": { 1552 | "base_uri": "https://localhost:8080/", 1553 | "height": 207 1554 | } 1555 | }, 1556 | "source": [ 1557 | "for i, sen in enumerate(my_sentences):\n", 1558 | " print(i, sen)\n", 1559 | " print(encoded_labels.classes_[np.argmax(keras_model.predict(encode(my_sentences))[i])])" 1560 | ], 1561 | "execution_count": 29, 1562 | "outputs": [ 1563 | { 1564 | "output_type": "stream", 1565 | "text": [ 1566 | "0 President Bush wants the war in Iraq, again\n", 1567 | "World News\n", 1568 | "1 LeBron James wins the NBA championship with Los Angeles Lakers\n", 1569 | "Sports News\n", 1570 | "2 Eni stock action value rise up to 14$\n", 1571 | "Business News\n", 1572 | "3 Futures in New York held near $41 a barrel after Saudi Oil Minister Prince Abdulaziz Bin Salman called on the OPEC+ alliance to be proactive in the face of uncertain demand. Yet a draft statement from the meeting made no mention of any changes to the current deal, which calls for production cuts to be eased from January. The market is also looking out for any signs that a stimulus deal can still be agreed in Washington ahead of the election while a resurgence in the pandemic threatens any recovery.\n", 1573 | "Business News\n", 1574 | "4 Apple iphone 12 is out!\n", 1575 | "Science-Technology News\n" 1576 | ], 1577 | "name": "stdout" 1578 | } 1579 | ] 1580 | }, 1581 | { 1582 | "cell_type": "markdown", 1583 | "metadata": { 1584 | "id": "dSStIitN7_bK" 1585 | }, 1586 | "source": [ 1587 | "# Save model and export in JavaScript" 1588 | ] 1589 | }, 1590 | { 1591 | "cell_type": "markdown", 1592 | "metadata": { 1593 | "id": "zXFZuCMOnk6i" 1594 | }, 1595 | "source": [ 1596 | "In order to convert our model using Tensorflow.js, we have to save the trained model." 1597 | ] 1598 | }, 1599 | { 1600 | "cell_type": "code", 1601 | "metadata": { 1602 | "id": "PLhmQHok7-sW" 1603 | }, 1604 | "source": [ 1605 | "#save Keras model\n", 1606 | "saved_model_path = \"modelCNN.h5\"\n", 1607 | "\n", 1608 | "keras_model.save(saved_model_path)" 1609 | ], 1610 | "execution_count": 30, 1611 | "outputs": [] 1612 | }, 1613 | { 1614 | "cell_type": "markdown", 1615 | "metadata": { 1616 | "id": "ll0V2AVtnwho" 1617 | }, 1618 | "source": [ 1619 | "Hence, we are ready to convert the saved model." 1620 | ] 1621 | }, 1622 | { 1623 | "cell_type": "code", 1624 | "metadata": { 1625 | "id": "Ux3IC9uq8Qeh", 1626 | "outputId": "47642b3b-3c04-4400-80c5-d605751faa79", 1627 | "colab": { 1628 | "base_uri": "https://localhost:8080/", 1629 | "height": 34 1630 | } 1631 | }, 1632 | "source": [ 1633 | "%%bash\n", 1634 | "tensorflowjs_converter --input_format=keras modelCNN.h5 ./model/" 1635 | ], 1636 | "execution_count": 31, 1637 | "outputs": [ 1638 | { 1639 | "output_type": "stream", 1640 | "text": [ 1641 | "2020-10-26 11:53:42.024115: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1\n" 1642 | ], 1643 | "name": "stderr" 1644 | } 1645 | ] 1646 | }, 1647 | { 1648 | "cell_type": "markdown", 1649 | "metadata": { 1650 | "id": "PCV2uTkGn045" 1651 | }, 1652 | "source": [ 1653 | "Since we have not only the model, but also weights files, we zip everything to make it ready to download." 1654 | ] 1655 | }, 1656 | { 1657 | "cell_type": "code", 1658 | "metadata": { 1659 | "id": "6DTmN8L6_05O", 1660 | "outputId": "9bee57e2-1d59-4be1-b28c-6f2b5fd48c5b", 1661 | "colab": { 1662 | "base_uri": "https://localhost:8080/", 1663 | "height": 119 1664 | } 1665 | }, 1666 | "source": [ 1667 | "%%bash\n", 1668 | "zip -r model.zip ./model" 1669 | ], 1670 | "execution_count": 32, 1671 | "outputs": [ 1672 | { 1673 | "output_type": "stream", 1674 | "text": [ 1675 | " adding: model/ (stored 0%)\n", 1676 | " adding: model/group1-shard4of4.bin (deflated 8%)\n", 1677 | " adding: model/group1-shard2of4.bin (deflated 7%)\n", 1678 | " adding: model/model.json (deflated 82%)\n", 1679 | " adding: model/group1-shard1of4.bin (deflated 7%)\n", 1680 | " adding: model/group1-shard3of4.bin (deflated 7%)\n" 1681 | ], 1682 | "name": "stdout" 1683 | } 1684 | ] 1685 | }, 1686 | { 1687 | "cell_type": "code", 1688 | "metadata": { 1689 | "id": "ATP6pE1NwddB" 1690 | }, 1691 | "source": [ 1692 | "" 1693 | ], 1694 | "execution_count": null, 1695 | "outputs": [] 1696 | } 1697 | ] 1698 | } --------------------------------------------------------------------------------