|
| 1 | +# Copyright (c) 2018 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 | +from __future__ import print_function |
| 16 | + |
| 17 | +import paddle |
| 18 | +import paddle.fluid as fluid |
| 19 | +from functools import partial |
| 20 | + |
| 21 | +CLASS_DIM = 2 |
| 22 | +EMB_DIM = 128 |
| 23 | +HID_DIM = 512 |
| 24 | +STACKED_NUM = 3 |
| 25 | + |
| 26 | + |
| 27 | +def stacked_lstm_net(data, input_dim, class_dim, emb_dim, hid_dim, stacked_num): |
| 28 | + assert stacked_num % 2 == 1 |
| 29 | + |
| 30 | + emb = fluid.layers.embedding( |
| 31 | + input=data, size=[input_dim, emb_dim], is_sparse=True) |
| 32 | + |
| 33 | + fc1 = fluid.layers.fc(input=emb, size=hid_dim) |
| 34 | + lstm1, cell1 = fluid.layers.dynamic_lstm(input=fc1, size=hid_dim) |
| 35 | + |
| 36 | + inputs = [fc1, lstm1] |
| 37 | + |
| 38 | + for i in range(2, stacked_num + 1): |
| 39 | + fc = fluid.layers.fc(input=inputs, size=hid_dim) |
| 40 | + lstm, cell = fluid.layers.dynamic_lstm( |
| 41 | + input=fc, size=hid_dim, is_reverse=(i % 2) == 0) |
| 42 | + inputs = [fc, lstm] |
| 43 | + |
| 44 | + fc_last = fluid.layers.sequence_pool(input=inputs[0], pool_type='max') |
| 45 | + lstm_last = fluid.layers.sequence_pool(input=inputs[1], pool_type='max') |
| 46 | + |
| 47 | + prediction = fluid.layers.fc(input=[fc_last, lstm_last], |
| 48 | + size=class_dim, |
| 49 | + act='softmax') |
| 50 | + return prediction |
| 51 | + |
| 52 | + |
| 53 | +def inference_network(word_dict): |
| 54 | + data = fluid.layers.data( |
| 55 | + name="words", shape=[1], dtype="int64", lod_level=1) |
| 56 | + |
| 57 | + dict_dim = len(word_dict) |
| 58 | + net = stacked_lstm_net(data, dict_dim, CLASS_DIM, EMB_DIM, HID_DIM, |
| 59 | + STACKED_NUM) |
| 60 | + return net |
| 61 | + |
| 62 | + |
| 63 | +def train_network(word_dict): |
| 64 | + prediction = inference_network(word_dict) |
| 65 | + label = fluid.layers.data(name="label", shape=[1], dtype="int64") |
| 66 | + cost = fluid.layers.cross_entropy(input=prediction, label=label) |
| 67 | + avg_cost = fluid.layers.mean(cost) |
| 68 | + accuracy = fluid.layers.accuracy(input=prediction, label=label) |
| 69 | + return avg_cost, accuracy |
| 70 | + |
| 71 | + |
| 72 | +def train(use_cuda, save_path): |
| 73 | + BATCH_SIZE = 128 |
| 74 | + EPOCH_NUM = 5 |
| 75 | + |
| 76 | + word_dict = paddle.dataset.imdb.word_dict() |
| 77 | + |
| 78 | + train_data = paddle.batch( |
| 79 | + paddle.reader.shuffle( |
| 80 | + paddle.dataset.imdb.train(word_dict), buf_size=1000), |
| 81 | + batch_size=BATCH_SIZE) |
| 82 | + |
| 83 | + test_data = paddle.batch( |
| 84 | + paddle.dataset.imdb.test(word_dict), batch_size=BATCH_SIZE) |
| 85 | + |
| 86 | + def event_handler(event): |
| 87 | + if isinstance(event, fluid.EndIteration): |
| 88 | + if (event.batch_id % 10) == 0: |
| 89 | + avg_cost, accuracy = trainer.test(reader=test_data) |
| 90 | + |
| 91 | + print('BatchID {1:04}, Loss {2:2.2}, Acc {3:2.2}'.format( |
| 92 | + event.batch_id + 1, avg_cost, accuracy)) |
| 93 | + |
| 94 | + if accuracy > 0.01: # Low threshold for speeding up CI |
| 95 | + trainer.params.save(save_path) |
| 96 | + return |
| 97 | + |
| 98 | + place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() |
| 99 | + trainer = fluid.Trainer( |
| 100 | + partial(train_network, word_dict), |
| 101 | + optimizer=fluid.optimizer.Adagrad(learning_rate=0.002), |
| 102 | + place=place, |
| 103 | + event_handler=event_handler) |
| 104 | + |
| 105 | + trainer.train(train_data, EPOCH_NUM, event_handler=event_handler) |
| 106 | + |
| 107 | + |
| 108 | +def infer(use_cuda, save_path): |
| 109 | + params = fluid.Params(save_path) |
| 110 | + place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() |
| 111 | + word_dict = paddle.dataset.imdb.word_dict() |
| 112 | + inferencer = fluid.Inferencer( |
| 113 | + partial(inference_network, word_dict), params, place=place) |
| 114 | + |
| 115 | + def create_random_lodtensor(lod, place, low, high): |
| 116 | + data = np.random.random_integers(low, high, |
| 117 | + [lod[-1], 1]).astype("int64") |
| 118 | + res = fluid.LoDTensor() |
| 119 | + res.set(data, place) |
| 120 | + res.set_lod([lod]) |
| 121 | + return res |
| 122 | + |
| 123 | + lod = [0, 4, 10] |
| 124 | + tensor_words = create_random_lodtensor( |
| 125 | + lod, place, low=0, high=len(word_dict) - 1) |
| 126 | + results = inferencer.infer({'words': tensor_words}) |
| 127 | + print("infer results: ", results) |
| 128 | + |
| 129 | + |
| 130 | +def main(use_cuda): |
| 131 | + if use_cuda and not fluid.core.is_compiled_with_cuda(): |
| 132 | + return |
| 133 | + save_path = "understand_sentiment_stacked_lstm.inference.model" |
| 134 | + train(use_cuda, save_path) |
| 135 | + infer(use_cuda, save_path) |
| 136 | + |
| 137 | + |
| 138 | +if __name__ == '__main__': |
| 139 | + for use_cuda in (False, True): |
| 140 | + main(use_cuda=use_cuda) |
0 commit comments