{"cells":[{"metadata":{"_uuid":"97b92845b85f289ba795c8c8f7117526abe073d0"},"cell_type":"markdown","source":"## IMPORTS "},{"metadata":{"_uuid":"abb7e3c30b8a412a50c6b451c49939e3cf4bc11b","scrolled":true,"trusted":true},"cell_type":"code","source":"import random\nimport copy\nimport time\nimport pandas as pd\nimport numpy as np\nimport gc\nimport re\nimport torch\n\n#import spacy\nfrom tqdm import tqdm_notebook, tnrange\nfrom tqdm.auto import tqdm\n\ntqdm.pandas(desc='Progress')\nfrom collections import Counter\n\nfrom nltk import word_tokenize\n\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nfrom torch.autograd import Variable\nfrom sklearn.metrics import f1_score\nimport os \n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n\n# cross validation and metrics\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import f1_score\nfrom torch.optim.optimizer import Optimizer\n\nfrom sklearn.preprocessing import StandardScaler\nfrom multiprocessing import  Pool\nfrom functools import partial\nimport numpy as np\nfrom sklearn.decomposition import PCA\nimport torch as t\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport matplotlib.pyplot as plt\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9a4ff5590a6f152dc1bec5aeca79aef10218f7de"},"cell_type":"markdown","source":"### Basic Parameters"},{"metadata":{"_uuid":"deee49df5ca1c4413f71677939e26aa1ff784e44","scrolled":true,"trusted":true},"cell_type":"code","source":"embed_size = 300 # how big is each word vector\nmax_features = 120000 # how many unique words to use (i.e num rows in embedding vector)\nmaxlen = 750 # max number of words in a question to use\nbatch_size = 512 # how many samples to process at once\nn_epochs = 5 # how many times to iterate over all samples\nn_splits = 5 # Number of K-fold Splits\nSEED = 10\ndebug = 0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data1 = pd.read_csv(\"../input/kuc-hackathon-winter-2018/drugsComTrain_raw.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data2 = pd.read_csv(\"../input/kuc-hackathon-winter-2018/drugsComTest_raw.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.concat([data1,data2])[['review','condition']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# remove NULL Values from data\ndata = data[pd.notnull(data['review'])]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Finding the maxlen"},{"metadata":{"trusted":true},"cell_type":"code","source":"data['len'] = data['review'].apply(lambda s : len(s))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['len'].plot.hist(bins=100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.len.quantile(0.9)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Preprocessing Y Column\nWe are only going to be classifying conditions for which the count of reviews are more than 3000."},{"metadata":{"trusted":true},"cell_type":"code","source":"count_df = data[['condition','review']].groupby('condition').aggregate({'review':'count'}).reset_index().sort_values('review',ascending=False)\ncount_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"target_conditions = count_df[count_df['review']>3000]['condition'].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def condition_parser(x):\n    if x in target_conditions:\n        return x\n    else:\n        return \"OTHER\"\n    \ndata['condition'] = data['condition'].apply(lambda x: condition_parser(x))  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = data[data['condition']!='OTHER']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import plotly.express as px","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"px.bar(count_df[count_df['review']>3000],x='condition',y='review')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"abeab4c80d6829cf2eae706bfa7929e2871af81f","scrolled":true,"trusted":true},"cell_type":"code","source":"import re\n\ndef clean_text(x):\n    pattern = r'[^a-zA-z0-9\\s]'\n    text = re.sub(pattern, '', x)\n    return x\n\ndef clean_numbers(x):\n    if bool(re.search(r'\\d', x)):\n        x = re.sub('[0-9]{5,}', '#####', x)\n        x = re.sub('[0-9]{4}', '####', x)\n        x = re.sub('[0-9]{3}', '###', x)\n        x = re.sub('[0-9]{2}', '##', x)\n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"contraction_dict = {\"ain't\": \"is not\", \"aren't\": \"are not\",\"can't\": \"cannot\", \"'cause\": \"because\", \"could've\": \"could have\", \"couldn't\": \"could not\", \"didn't\": \"did not\",  \"doesn't\": \"does not\", \"don't\": \"do not\", \"hadn't\": \"had not\", \"hasn't\": \"has not\", \"haven't\": \"have not\", \"he'd\": \"he would\",\"he'll\": \"he will\", \"he's\": \"he is\", \"how'd\": \"how did\", \"how'd'y\": \"how do you\", \"how'll\": \"how will\", \"how's\": \"how is\",  \"I'd\": \"I would\", \"I'd've\": \"I would have\", \"I'll\": \"I will\", \"I'll've\": \"I will have\",\"I'm\": \"I am\", \"I've\": \"I have\", \"i'd\": \"i would\", \"i'd've\": \"i would have\", \"i'll\": \"i will\",  \"i'll've\": \"i will have\",\"i'm\": \"i am\", \"i've\": \"i have\", \"isn't\": \"is not\", \"it'd\": \"it would\", \"it'd've\": \"it would have\", \"it'll\": \"it will\", \"it'll've\": \"it will have\",\"it's\": \"it is\", \"let's\": \"let us\", \"ma'am\": \"madam\", \"mayn't\": \"may not\", \"might've\": \"might have\",\"mightn't\": \"might not\",\"mightn't've\": \"might not have\", \"must've\": \"must have\", \"mustn't\": \"must not\", \"mustn't've\": \"must not have\", \"needn't\": \"need not\", \"needn't've\": \"need not have\",\"o'clock\": \"of the clock\", \"oughtn't\": \"ought not\", \"oughtn't've\": \"ought not have\", \"shan't\": \"shall not\", \"sha'n't\": \"shall not\", \"shan't've\": \"shall not have\", \"she'd\": \"she would\", \"she'd've\": \"she would have\", \"she'll\": \"she will\", \"she'll've\": \"she will have\", \"she's\": \"she is\", \"should've\": \"should have\", \"shouldn't\": \"should not\", \"shouldn't've\": \"should not have\", \"so've\": \"so have\",\"so's\": \"so as\", \"this's\": \"this is\",\"that'd\": \"that would\", \"that'd've\": \"that would have\", \"that's\": \"that is\", \"there'd\": \"there would\", \"there'd've\": \"there would have\", \"there's\": \"there is\", \"here's\": \"here is\",\"they'd\": \"they would\", \"they'd've\": \"they would have\", \"they'll\": \"they will\", \"they'll've\": \"they will have\", \"they're\": \"they are\", \"they've\": \"they have\", \"to've\": \"to have\", \"wasn't\": \"was not\", \"we'd\": \"we would\", \"we'd've\": \"we would have\", \"we'll\": \"we will\", \"we'll've\": \"we will have\", \"we're\": \"we are\", \"we've\": \"we have\", \"weren't\": \"were not\", \"what'll\": \"what will\", \"what'll've\": \"what will have\", \"what're\": \"what are\",  \"what's\": \"what is\", \"what've\": \"what have\", \"when's\": \"when is\", \"when've\": \"when have\", \"where'd\": \"where did\", \"where's\": \"where is\", \"where've\": \"where have\", \"who'll\": \"who will\", \"who'll've\": \"who will have\", \"who's\": \"who is\", \"who've\": \"who have\", \"why's\": \"why is\", \"why've\": \"why have\", \"will've\": \"will have\", \"won't\": \"will not\", \"won't've\": \"will not have\", \"would've\": \"would have\", \"wouldn't\": \"would not\", \"wouldn't've\": \"would not have\", \"y'all\": \"you all\", \"y'all'd\": \"you all would\",\"y'all'd've\": \"you all would have\",\"y'all're\": \"you all are\",\"y'all've\": \"you all have\",\"you'd\": \"you would\", \"you'd've\": \"you would have\", \"you'll\": \"you will\", \"you'll've\": \"you will have\", \"you're\": \"you are\", \"you've\": \"you have\"}\ndef _get_contractions(contraction_dict):\n    contraction_re = re.compile('(%s)' % '|'.join(contraction_dict.keys()))\n    return contraction_dict, contraction_re\ncontractions, contractions_re = _get_contractions(contraction_dict)\ndef replace_contractions(text):\n    def replace(match):\n        return contractions[match.group(0)]\n    return contractions_re.sub(replace, text)\n# Usage\nreplace_contractions(\"this's a text with contraction\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# lower the text\ndata[\"review\"] = data[\"review\"].apply(lambda x: x.lower())\n\n# Clean the text\ndata[\"review\"] = data[\"review\"].apply(lambda x: clean_text(x))\n\n# Clean numbers\ndata[\"review\"] = data[\"review\"].apply(lambda x: clean_numbers(x))\n\n# Clean Contractions\ndata[\"review\"] = data[\"review\"].apply(lambda x: replace_contractions(x))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['condition'].unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_X, test_X, train_y, test_y = train_test_split(data['review'], data['condition'],\n                                                    stratify=data['condition'], \n                                                    test_size=0.25)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"63cb21525251b060aeb309e7be4b48772f8720f5","scrolled":true,"trusted":true},"cell_type":"code","source":"print(\"Train shape : \",train_X.shape)\nprint(\"Test shape : \",test_X.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Tokenize the sentences\ntokenizer = Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(list(train_X))\ntrain_X = tokenizer.texts_to_sequences(train_X)\ntest_X = tokenizer.texts_to_sequences(test_X)\n\n## Pad the sentences \ntrain_X = pad_sequences(train_X, maxlen=maxlen)\ntest_X = pad_sequences(test_X, maxlen=maxlen)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\ntrain_y = le.fit_transform(train_y.values)\ntest_y = le.transform(test_y.values)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"le.classes_","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e5c51a8329d569d13b9f0369ebb98ca8e2e55440"},"cell_type":"markdown","source":"### Load Embeddings\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"## FUNCTIONS TAKEN FROM https://www.kaggle.com/gmhost/gru-capsule\n\ndef load_glove(word_index):\n    EMBEDDING_FILE = '../input/glove840b300dtxt/glove.840B.300d.txt'\n    def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')[:300]\n    embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE))\n    \n    all_embs = np.stack(embeddings_index.values())\n    emb_mean,emb_std = -0.005838499,0.48782197\n    embed_size = all_embs.shape[1]\n\n    nb_words = min(max_features, len(word_index)+1)\n    embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\n    for word, i in word_index.items():\n        if i >= max_features: continue\n        embedding_vector = embeddings_index.get(word)\n        if embedding_vector is not None: \n            embedding_matrix[i] = embedding_vector\n        else:\n            embedding_vector = embeddings_index.get(word.capitalize())\n            if embedding_vector is not None: \n                embedding_matrix[i] = embedding_vector\n    return embedding_matrix","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6a5f4502324d369ff6faa3692accee4f8a233005","scrolled":true,"trusted":true},"cell_type":"code","source":"# missing entries in the embedding are set using np.random.normal so we have to seed here too\n\nif debug:\n    embedding_matrix = np.random.randn(120000,300)\nelse:\n    embedding_matrix = load_glove(tokenizer.word_index)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"aa6a41607b804d76a2ddc530c912b5673bcd2423","trusted":true},"cell_type":"code","source":"np.shape(embedding_matrix)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0a78496e4d88d8fb351cdf26d02f1554821ed445"},"cell_type":"markdown","source":"## Pytorch Model - TextCNN"},{"metadata":{"trusted":true},"cell_type":"code","source":"class CNN_Text(nn.Module):\n    \n    def __init__(self):\n        super(CNN_Text, self).__init__()\n        filter_sizes = [1,2,3,5]\n        num_filters = 36\n        n_classes = len(le.classes_)\n        self.embedding = nn.Embedding(max_features, embed_size)\n        self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))\n        self.embedding.weight.requires_grad = False\n        self.convs1 = nn.ModuleList([nn.Conv2d(1, num_filters, (K, embed_size)) for K in filter_sizes])\n        self.dropout = nn.Dropout(0.1)\n        self.fc1 = nn.Linear(len(filter_sizes)*num_filters, n_classes)\n\n\n    def forward(self, x):\n        x = self.embedding(x)  \n        x = x.unsqueeze(1)  \n        x = [F.relu(conv(x)).squeeze(3) for conv in self.convs1] \n        x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x]  \n        x = torch.cat(x, 1)\n        x = self.dropout(x)  \n        logit = self.fc1(x) \n        return logit","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0da30e2afce23b753796f3045b44ce91a07e4303"},"cell_type":"markdown","source":"## Train TextCNN Model"},{"metadata":{"_uuid":"6a5afb54f70a29808af19946ba08ef971d194e46","trusted":true},"cell_type":"code","source":"n_epochs = 6\nmodel = CNN_Text()\nloss_fn = nn.CrossEntropyLoss(reduction='sum')\noptimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.001)\nmodel.cuda()\n\n# Load train and test in CUDA Memory\nx_train = torch.tensor(train_X, dtype=torch.long).cuda()\ny_train = torch.tensor(train_y, dtype=torch.long).cuda()\nx_cv = torch.tensor(test_X, dtype=torch.long).cuda()\ny_cv = torch.tensor(test_y, dtype=torch.long).cuda()\n\n# Create Torch datasets\ntrain = torch.utils.data.TensorDataset(x_train, y_train)\nvalid = torch.utils.data.TensorDataset(x_cv, y_cv)\n\n# Create Data Loaders\ntrain_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)\nvalid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)\n\ntrain_loss = []\nvalid_loss = []\n\nfor epoch in range(n_epochs):\n    start_time = time.time()\n    # Set model to train configuration\n    model.train()\n    avg_loss = 0.  \n    for i, (x_batch, y_batch) in enumerate(train_loader):\n        # Predict/Forward Pass\n        y_pred = model(x_batch)\n        # Compute loss\n        loss = loss_fn(y_pred, y_batch)\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        avg_loss += loss.item() / len(train_loader)\n    \n    # Set model to validation configuration -Doesn't get trained here\n    model.eval()        \n    avg_val_loss = 0.\n    val_preds = np.zeros((len(x_cv),len(le.classes_)))\n    \n    for i, (x_batch, y_batch) in enumerate(valid_loader):\n        y_pred = model(x_batch).detach()\n        avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader)\n        # keep/store predictions\n        val_preds[i * batch_size:(i+1) * batch_size] =F.softmax(y_pred).cpu().numpy()\n    \n    # Check Accuracy\n    val_accuracy = sum(val_preds.argmax(axis=1)==test_y)/len(test_y)\n    train_loss.append(avg_loss)\n    valid_loss.append(avg_val_loss)\n    elapsed_time = time.time() - start_time \n    print('Epoch {}/{} \\t loss={:.4f} \\t val_loss={:.4f}  \\t val_acc={:.4f}  \\t time={:.2f}s'.format(\n                epoch + 1, n_epochs, avg_loss, avg_val_loss, val_accuracy, elapsed_time))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"torch.save(model,'textcnn_model')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9d1b3fc0c8bc59f91a203adcf3dbd9d89759c8df","trusted":true},"cell_type":"code","source":"def plot_graph(epochs):\n    fig = plt.figure(figsize=(12,12))\n    plt.title(\"Train/Validation Loss\")\n    plt.plot(list(np.arange(epochs) + 1) , train_loss, label='train')\n    plt.plot(list(np.arange(epochs) + 1), valid_loss, label='validation')\n    plt.xlabel('num_epochs', fontsize=12)\n    plt.ylabel('loss', fontsize=12)\n    plt.legend(loc='best')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_graph(n_epochs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import scikitplot as skplt\ny_true = [le.classes_[x] for x in test_y]\ny_pred = [le.classes_[x] for x in val_preds.argmax(axis=1)]\nskplt.metrics.plot_confusion_matrix(\n    y_true, \n    y_pred,\n    figsize=(12,12),x_tick_rotation=90)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Pytorch Model - BiLSTM"},{"metadata":{"trusted":true},"cell_type":"code","source":"class BiLSTM(nn.Module):\n    \n    def __init__(self):\n        super(BiLSTM, self).__init__()\n        self.hidden_size = 64\n        drp = 0.1\n        n_classes = len(le.classes_)\n        self.embedding = nn.Embedding(max_features, embed_size)\n        self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))\n        self.embedding.weight.requires_grad = False\n        self.lstm = nn.LSTM(embed_size, self.hidden_size, bidirectional=True, batch_first=True)\n        self.linear = nn.Linear(self.hidden_size*4 , 64)\n        self.relu = nn.ReLU()\n        self.dropout = nn.Dropout(drp)\n        self.out = nn.Linear(64, n_classes)\n\n\n    def forward(self, x):\n        #rint(x.size())\n        h_embedding = self.embedding(x)\n        #_embedding = torch.squeeze(torch.unsqueeze(h_embedding, 0))\n        h_lstm, _ = self.lstm(h_embedding)\n        avg_pool = torch.mean(h_lstm, 1)\n        max_pool, _ = torch.max(h_lstm, 1)\n        conc = torch.cat(( avg_pool, max_pool), 1)\n        conc = self.relu(self.linear(conc))\n        conc = self.dropout(conc)\n        out = self.out(conc)\n        return out","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_epochs = 6\nmodel = BiLSTM()\nloss_fn = nn.CrossEntropyLoss(reduction='sum')\noptimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.001)\nmodel.cuda()\n\n# Load train and test in CUDA Memory\nx_train = torch.tensor(train_X, dtype=torch.long).cuda()\ny_train = torch.tensor(train_y, dtype=torch.long).cuda()\nx_cv = torch.tensor(test_X, dtype=torch.long).cuda()\ny_cv = torch.tensor(test_y, dtype=torch.long).cuda()\n\n# Create Torch datasets\ntrain = torch.utils.data.TensorDataset(x_train, y_train)\nvalid = torch.utils.data.TensorDataset(x_cv, y_cv)\n\n# Create Data Loaders\ntrain_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)\nvalid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)\n\ntrain_loss = []\nvalid_loss = []\n\nfor epoch in range(n_epochs):\n    start_time = time.time()\n    # Set model to train configuration\n    model.train()\n    avg_loss = 0.  \n    for i, (x_batch, y_batch) in enumerate(train_loader):\n        # Predict/Forward Pass\n        y_pred = model(x_batch)\n        # Compute loss\n        loss = loss_fn(y_pred, y_batch)\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        avg_loss += loss.item() / len(train_loader)\n    \n    # Set model to validation configuration -Doesn't get trained here\n    model.eval()        \n    avg_val_loss = 0.\n    val_preds = np.zeros((len(x_cv),len(le.classes_)))\n    \n    for i, (x_batch, y_batch) in enumerate(valid_loader):\n        y_pred = model(x_batch).detach()\n        avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader)\n        # keep/store predictions\n        val_preds[i * batch_size:(i+1) * batch_size] =F.softmax(y_pred).cpu().numpy()\n    \n    # Check Accuracy\n    val_accuracy = sum(val_preds.argmax(axis=1)==test_y)/len(test_y)\n    train_loss.append(avg_loss)\n    valid_loss.append(avg_val_loss)\n    elapsed_time = time.time() - start_time \n    print('Epoch {}/{} \\t loss={:.4f} \\t val_loss={:.4f}  \\t val_acc={:.4f}  \\t time={:.2f}s'.format(\n                epoch + 1, n_epochs, avg_loss, avg_val_loss, val_accuracy, elapsed_time))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_graph(n_epochs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"torch.save(model,'bilstm_model')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import scikitplot as skplt\ny_true = [le.classes_[x] for x in test_y]\ny_pred = [le.classes_[x] for x in val_preds.argmax(axis=1)]\nskplt.metrics.plot_confusion_matrix(\n    y_true, \n    y_pred,\n    figsize=(12,12),x_tick_rotation=90)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Deploy : Predict A Single Example"},{"metadata":{"trusted":true},"cell_type":"code","source":"def predict_single(x):    \n    # lower the text\n    x = x.lower()\n    # Clean the text\n    x =  clean_text(x)\n    # Clean numbers\n    x =  clean_numbers(x)\n    # Clean Contractions\n    x = replace_contractions(x)\n    # tokenize\n    x = tokenizer.texts_to_sequences([x])\n    # pad\n    x = pad_sequences(x, maxlen=maxlen)\n    # create dataset\n    x = torch.tensor(x, dtype=torch.long).cuda()\n\n    pred = model(x).detach()\n    pred = F.softmax(pred).cpu().numpy()\n\n    pred = pred.argmax(axis=1)\n\n    pred = le.classes_[pred]\n    return pred[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = data['review'].values[20]\nprint(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict_single(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python [conda env:pyt]","language":"python","name":"conda-env-pyt-py"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.6"}},"nbformat":4,"nbformat_minor":4}