|
| 1 | +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License" |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import os |
| 16 | +from typing import List |
| 17 | + |
| 18 | +import paddle |
| 19 | +import paddle.nn as nn |
| 20 | +import paddle.nn.functional as F |
| 21 | + |
| 22 | +import paddlenlp as nlp |
| 23 | +from paddlenlp.embeddings import TokenEmbedding |
| 24 | +from paddlenlp.data import JiebaTokenizer |
| 25 | + |
| 26 | +from paddlehub.utils.log import logger |
| 27 | +from paddlehub.utils.utils import pad_sequence, trunc_sequence |
| 28 | + |
| 29 | + |
| 30 | +class BoWModel(nn.Layer): |
| 31 | + """ |
| 32 | + This class implements the Bag of Words Classification Network model to classify texts. |
| 33 | + At a high level, the model starts by embedding the tokens and running them through |
| 34 | + a word embedding. Then, we encode these epresentations with a `BoWEncoder`. |
| 35 | + Lastly, we take the output of the encoder to create a final representation, |
| 36 | + which is passed through some feed-forward layers to output a logits (`output_layer`). |
| 37 | + Args: |
| 38 | + vocab_size (obj:`int`): The vocabulary size. |
| 39 | + emb_dim (obj:`int`, optional, defaults to 300): The embedding dimension. |
| 40 | + hidden_size (obj:`int`, optional, defaults to 128): The first full-connected layer hidden size. |
| 41 | + fc_hidden_size (obj:`int`, optional, defaults to 96): The second full-connected layer hidden size. |
| 42 | + num_classes (obj:`int`): All the labels that the data has. |
| 43 | + """ |
| 44 | + |
| 45 | + def __init__(self, |
| 46 | + num_classes: int = 2, |
| 47 | + embedder: TokenEmbedding = None, |
| 48 | + tokenizer: JiebaTokenizer = None, |
| 49 | + hidden_size: int = 128, |
| 50 | + fc_hidden_size: int = 96, |
| 51 | + load_checkpoint: str = None, |
| 52 | + label_map: dict = None): |
| 53 | + super().__init__() |
| 54 | + self.embedder = embedder |
| 55 | + self.tokenizer = tokenizer |
| 56 | + self.label_map = label_map |
| 57 | + |
| 58 | + emb_dim = self.embedder.embedding_dim |
| 59 | + self.bow_encoder = nlp.seq2vec.BoWEncoder(emb_dim) |
| 60 | + self.fc1 = nn.Linear(self.bow_encoder.get_output_dim(), hidden_size) |
| 61 | + self.fc2 = nn.Linear(hidden_size, fc_hidden_size) |
| 62 | + self.dropout = nn.Dropout(p=0.3, axis=1) |
| 63 | + self.output_layer = nn.Linear(fc_hidden_size, num_classes) |
| 64 | + self.criterion = nn.loss.CrossEntropyLoss() |
| 65 | + self.metric = paddle.metric.Accuracy() |
| 66 | + |
| 67 | + if load_checkpoint is not None and os.path.isfile(load_checkpoint): |
| 68 | + state_dict = paddle.load(load_checkpoint) |
| 69 | + self.set_state_dict(state_dict) |
| 70 | + logger.info('Loaded parameters from %s' % os.path.abspath(load_checkpoint)) |
| 71 | + |
| 72 | + def training_step(self, batch: List[paddle.Tensor], batch_idx: int): |
| 73 | + """ |
| 74 | + One step for training, which should be called as forward computation. |
| 75 | + Args: |
| 76 | + batch(:obj:List[paddle.Tensor]): The one batch data, which contains the model needed, |
| 77 | + such as input_ids, sent_ids, pos_ids, input_mask and labels. |
| 78 | + batch_idx(int): The index of batch. |
| 79 | + Returns: |
| 80 | + results(:obj: Dict) : The model outputs, such as loss and metrics. |
| 81 | + """ |
| 82 | + _, avg_loss, metric = self(ids=batch[0], labels=batch[1]) |
| 83 | + self.metric.reset() |
| 84 | + return {'loss': avg_loss, 'metrics': metric} |
| 85 | + |
| 86 | + def validation_step(self, batch: List[paddle.Tensor], batch_idx: int): |
| 87 | + """ |
| 88 | + One step for validation, which should be called as forward computation. |
| 89 | + Args: |
| 90 | + batch(:obj:List[paddle.Tensor]): The one batch data, which contains the model needed, |
| 91 | + such as input_ids, sent_ids, pos_ids, input_mask and labels. |
| 92 | + batch_idx(int): The index of batch. |
| 93 | + Returns: |
| 94 | + results(:obj: Dict) : The model outputs, such as metrics. |
| 95 | + """ |
| 96 | + _, _, metric = self(ids=batch[0], labels=batch[1]) |
| 97 | + self.metric.reset() |
| 98 | + return {'metrics': metric} |
| 99 | + |
| 100 | + def forward(self, ids: paddle.Tensor, labels: paddle.Tensor = None): |
| 101 | + |
| 102 | + # Shape: (batch_size, num_tokens, embedding_dim) |
| 103 | + embedded_text = self.embedder(ids) |
| 104 | + |
| 105 | + # Shape: (batch_size, embedding_dim) |
| 106 | + summed = self.bow_encoder(embedded_text) |
| 107 | + summed = self.dropout(summed) |
| 108 | + encoded_text = paddle.tanh(summed) |
| 109 | + |
| 110 | + # Shape: (batch_size, hidden_size) |
| 111 | + fc1_out = paddle.tanh(self.fc1(encoded_text)) |
| 112 | + # Shape: (batch_size, fc_hidden_size) |
| 113 | + fc2_out = paddle.tanh(self.fc2(fc1_out)) |
| 114 | + # Shape: (batch_size, num_classes) |
| 115 | + logits = self.output_layer(fc2_out) |
| 116 | + |
| 117 | + probs = F.softmax(logits, axis=1) |
| 118 | + if labels is not None: |
| 119 | + loss = self.criterion(logits, labels) |
| 120 | + correct = self.metric.compute(probs, labels) |
| 121 | + acc = self.metric.update(correct) |
| 122 | + return probs, loss, {'acc': acc} |
| 123 | + else: |
| 124 | + return probs |
| 125 | + |
| 126 | + def _batchify(self, data: List[List[str]], max_seq_len: int, batch_size: int): |
| 127 | + examples = [] |
| 128 | + for item in data: |
| 129 | + ids = self.tokenizer.encode(sentence=item[0]) |
| 130 | + |
| 131 | + if len(ids) > max_seq_len: |
| 132 | + ids = trunc_sequence(ids, max_seq_len) |
| 133 | + else: |
| 134 | + pad_token = self.tokenizer.vocab.pad_token |
| 135 | + pad_token_id = self.tokenizer.vocab.to_indices(pad_token) |
| 136 | + ids = pad_sequence(ids, max_seq_len, pad_token_id) |
| 137 | + examples.append(ids) |
| 138 | + |
| 139 | + # Seperates data into some batches. |
| 140 | + one_batch = [] |
| 141 | + for example in examples: |
| 142 | + one_batch.append(example) |
| 143 | + if len(one_batch) == batch_size: |
| 144 | + yield one_batch |
| 145 | + one_batch = [] |
| 146 | + if one_batch: |
| 147 | + # The last batch whose size is less than the config batch_size setting. |
| 148 | + yield one_batch |
| 149 | + |
| 150 | + def predict( |
| 151 | + self, |
| 152 | + data: List[List[str]], |
| 153 | + max_seq_len: int = 128, |
| 154 | + batch_size: int = 1, |
| 155 | + use_gpu: bool = False, |
| 156 | + return_result: bool = True, |
| 157 | + ): |
| 158 | + paddle.set_device('gpu') if use_gpu else paddle.set_device('cpu') |
| 159 | + |
| 160 | + batches = self._batchify(data, max_seq_len, batch_size) |
| 161 | + results = [] |
| 162 | + self.eval() |
| 163 | + for batch in batches: |
| 164 | + ids = paddle.to_tensor(batch) |
| 165 | + probs = self(ids) |
| 166 | + idx = paddle.argmax(probs, axis=1).numpy() |
| 167 | + |
| 168 | + if return_result: |
| 169 | + idx = idx.tolist() |
| 170 | + labels = [self.label_map[i] for i in idx] |
| 171 | + results.extend(labels) |
| 172 | + else: |
| 173 | + results.extend(probs.numpy()) |
| 174 | + |
| 175 | + return results |
0 commit comments