|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | +import tensorflow as tf |
| 4 | +import transformers |
| 5 | + |
| 6 | + |
| 7 | +labels = ["contradiction", "entailment", "neutral"] |
| 8 | + |
| 9 | +x_train = pd.read_csv("./SNLI_Corpus/snli_1.0_train.csv", nrows=100000) |
| 10 | +x_val = pd.read_csv("./SNLI_Corpus/snli_1.0_dev.csv") |
| 11 | +x_test = pd.read_csv("./SNLI_Corpus/snli_1.0_test.csv") |
| 12 | +x_train.dropna(axis=0, inplace=True) |
| 13 | + |
| 14 | +x_train = ( |
| 15 | + x_train[x_train.similarity != "-"] |
| 16 | + .sample(frac=1.0, random_state=42) |
| 17 | + .reset_index(drop=True) |
| 18 | +) |
| 19 | +x_val = ( |
| 20 | + x_val[x_val.similarity != "-"] |
| 21 | + .sample(frac=1.0, random_state=42) |
| 22 | + .reset_index(drop=True) |
| 23 | +) |
| 24 | + |
| 25 | +# print(f"Total train samples : {x_train.shape[0]}") |
| 26 | +# print(f"Total validation samples: {x_val.shape[0]}") |
| 27 | +# print(f"Total test samples: {x_val.shape[0]}") |
| 28 | +# print(x_train.similarity.value_counts()) |
| 29 | + |
| 30 | +x_train["label"] = x_train["similarity"].apply(lambda x: 0 if x == "contradiction" else 1 if x == "entailment" else 2) |
| 31 | +x_val["label"] = x_val["similarity"].apply(lambda x: 0 if x == "contradiction" else 1 if x == "entailment" else 2) |
| 32 | +x_test["label"] = x_test["similarity"].apply(lambda x: 0 if x == "contradiction" else 1 if x == "entailment" else 2) |
| 33 | + |
| 34 | +y_train = tf.keras.utils.to_categorical(x_train.label, num_classes=3) |
| 35 | +y_val = tf.keras.utils.to_categorical(x_val.label, num_classes=3) |
| 36 | +y_test = tf.keras.utils.to_categorical(x_test.label, num_classes=3) |
| 37 | + |
| 38 | + |
| 39 | +max_length = 128 |
| 40 | +batch_size = 32 |
| 41 | +epochs = 2 |
| 42 | + |
| 43 | +class DataLoader(tf.keras.utils.Sequence): |
| 44 | + """Generates batches of data. |
| 45 | +
|
| 46 | + Args: |
| 47 | + sentences: Array of premise and hypothesis input sentences. |
| 48 | + labels: Array of labels. |
| 49 | + batch_size: Integer batch size. |
| 50 | + shuffle: boolean, whether to shuffle the data. |
| 51 | + include_labels: boolean, whether to incude the labels. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + Tuples `([input_ids, attention_mask, `token_type_ids], labels)` |
| 55 | + (or just `[input_ids, attention_mask, `token_type_ids]` |
| 56 | + if `include_labels=False`) |
| 57 | + """ |
| 58 | + |
| 59 | + def __init__( |
| 60 | + self, |
| 61 | + sentences, |
| 62 | + labels, |
| 63 | + batch_size=batch_size, |
| 64 | + shuffle=True, |
| 65 | + include_labels=True, |
| 66 | + ): |
| 67 | + self.sentences = sentences |
| 68 | + self.labels = labels |
| 69 | + self.shuffle = shuffle |
| 70 | + self.batch_size = batch_size |
| 71 | + self.include_labels = include_labels |
| 72 | + self.tokenizer = transformers.BertTokenizer.from_pretrained("bert-base-uncased", do_lower_case=True) |
| 73 | + self.indexes = np.arange(len(self.sentences)) |
| 74 | + self.shuffle_data() |
| 75 | + |
| 76 | + def __len__(self): |
| 77 | + return len(self.sentences) // self.batch_size |
| 78 | + |
| 79 | + def __getitem__(self, idx): |
| 80 | + indexes = self.indexes[idx * self.batch_size : (idx + 1) * self.batch_size] |
| 81 | + sentences = self.sentences[indexes] |
| 82 | + encoded = self.tokenizer.batch_encode_plus( |
| 83 | + sentences.tolist(), |
| 84 | + add_special_tokens=True, |
| 85 | + max_length=max_length, |
| 86 | + return_attention_mask=True, |
| 87 | + return_token_type_ids=True, |
| 88 | + pad_to_max_length=True, |
| 89 | + return_tensors="tf", |
| 90 | + ) |
| 91 | + |
| 92 | + sentence_inputs = np.array(encoded["input_ids"], dtype="int32") |
| 93 | + attention_masks = np.array(encoded["attention_mask"], dtype="int32") |
| 94 | + token_type_ids = np.array(encoded["token_type_ids"], dtype="int32") |
| 95 | + |
| 96 | + if self.include_labels: |
| 97 | + labels = np.array(self.labels[indexes], dtype="int32") |
| 98 | + return [sentence_inputs, attention_masks, token_type_ids], labels |
| 99 | + else: |
| 100 | + return [sentence_inputs, attention_masks, token_type_ids] |
| 101 | + |
| 102 | + def shuffle_data(self): |
| 103 | + if self.shuffle: |
| 104 | + np.random.RandomState(50).shuffle(self.indexes) |
| 105 | + |
| 106 | + |
| 107 | +sentence_inputs = tf.keras.layers.Input(shape=(max_length,), dtype=tf.int32, name="input_ids") |
| 108 | +attention_masks = tf.keras.layers.Input(shape=(max_length,), dtype=tf.int32, name="attention_masks") |
| 109 | +token_type_ids = tf.keras.layers.Input(shape=(max_length,), dtype=tf.int32, name="token_type_ids") |
| 110 | + |
| 111 | +bert_model = transformers.TFBertModel.from_pretrained("bert-base-uncased") |
| 112 | +bert_model.trainable = True |
| 113 | +bert_output = bert_model.bert(sentence_inputs, attention_mask=attention_masks, token_type_ids=token_type_ids) |
| 114 | +sequence_output = bert_output.last_hidden_state |
| 115 | + |
| 116 | +# pooled_output = bert_output.pooler_output |
| 117 | +lstm = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True))(sequence_output) |
| 118 | +avg_pool = tf.keras.layers.GlobalAveragePooling1D()(lstm) |
| 119 | +max_pool = tf.keras.layers.GlobalMaxPooling1D()(lstm) |
| 120 | +x = tf.keras.layers.concatenate([avg_pool, max_pool]) |
| 121 | +x = tf.keras.layers.Dropout(0.3)(x) |
| 122 | +out = tf.keras.layers.Dense(3, activation="softmax")(x) |
| 123 | +model = tf.keras.models.Model(inputs=[sentence_inputs, attention_masks, token_type_ids], outputs=out) |
| 124 | + |
| 125 | +# model.summary() |
| 126 | + |
| 127 | +train_data = DataLoader( |
| 128 | + x_train[["sentence1", "sentence2"]].values.astype("str"), |
| 129 | + y_train, |
| 130 | + batch_size=batch_size, |
| 131 | + shuffle=True, |
| 132 | +) |
| 133 | +valid_data = DataLoader( |
| 134 | + x_val[["sentence1", "sentence2"]].values.astype("str"), |
| 135 | + y_val, |
| 136 | + batch_size=batch_size, |
| 137 | + shuffle=False, |
| 138 | +) |
| 139 | +test_data = DataLoader( |
| 140 | + x_test[["sentence1", "sentence2"]].values.astype("str"), |
| 141 | + y_test, |
| 142 | + batch_size=batch_size, |
| 143 | + shuffle=False, |
| 144 | +) |
| 145 | + |
0 commit comments