|
| 1 | +# ****************************************************************************** |
| 2 | +# Copyright 2017-2018 Intel Corporation |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# ****************************************************************************** |
| 16 | + |
| 17 | +""" |
| 18 | +This example uses the Amazon reviews though additional datasets can easily be substituted. |
| 19 | +It only requires text and a sentiment label |
| 20 | +It then takes the dataset and trains two models (again can be expanded) |
| 21 | +The labels for the test data is then predicted. |
| 22 | +The same train and test data is used for both models |
| 23 | +
|
| 24 | +The ensembler takes the two prediction matrixes and weights (as defined by model accuracy) |
| 25 | +and determines the final prediction matrix. |
| 26 | +
|
| 27 | +Finally, the full classification report is displayed. |
| 28 | +
|
| 29 | +A similar pipeline could be utilized to train models on a dataset, predict on a second dataset |
| 30 | +and aquire a list of final predictions |
| 31 | +""" |
| 32 | + |
| 33 | +import numpy as np |
| 34 | +import argparse |
| 35 | +from keras.preprocessing.sequence import pad_sequences |
| 36 | +from keras.preprocessing.text import Tokenizer |
| 37 | +from sklearn.model_selection import train_test_split |
| 38 | +from sklearn.metrics import classification_report |
| 39 | + |
| 40 | +from nlp_architect.data.amazon_reviews import Amazon_Reviews |
| 41 | +from nlp_architect.utils.generic import to_one_hot |
| 42 | +from nlp_architect.models.supervised_sentiment import simple_lstm, one_hot_cnn |
| 43 | +from nlp_architect.utils.ensembler import simple_ensembler |
| 44 | +from nlp_architect.utils.io import validate_existing_filepath, check_size |
| 45 | + |
| 46 | +max_fatures = 2000 |
| 47 | +max_len = 300 |
| 48 | +batch_size = 32 |
| 49 | +embed_dim = 256 |
| 50 | +lstm_out = 140 |
| 51 | + |
| 52 | + |
| 53 | +def ensemble_models(data, args): |
| 54 | + # split, train, test |
| 55 | + data.process() |
| 56 | + dense_out = len(data.labels[0]) |
| 57 | + # split for all models |
| 58 | + X_train_, X_test_, Y_train, Y_test = train_test_split(data.text, data.labels, |
| 59 | + test_size=0.20, random_state=42) |
| 60 | + |
| 61 | + # Prep data for the LSTM model |
| 62 | + tokenizer = Tokenizer(num_words=max_fatures, split=' ') |
| 63 | + tokenizer.fit_on_texts(X_train_) |
| 64 | + X_train = tokenizer.texts_to_sequences(X_train_) |
| 65 | + X_train = pad_sequences(X_train, maxlen=max_len) |
| 66 | + X_test = tokenizer.texts_to_sequences(X_test_) |
| 67 | + X_test = pad_sequences(X_test, maxlen=max_len) |
| 68 | + |
| 69 | + # Train the LSTM model |
| 70 | + lstm_model = simple_lstm(max_fatures, dense_out, X_train.shape[1], embed_dim, lstm_out) |
| 71 | + model_hist = lstm_model.fit(X_train, Y_train, epochs=args.epochs, batch_size=batch_size, |
| 72 | + verbose=1, validation_data=(X_test, Y_test)) |
| 73 | + lstm_acc = model_hist.history['acc'][-1] |
| 74 | + print("LSTM model accuracy ", lstm_acc) |
| 75 | + |
| 76 | + # And make predictions using the LSTM model |
| 77 | + lstm_predictions = lstm_model.predict(X_test) |
| 78 | + |
| 79 | + # Now prep data for the one-hot CNN model |
| 80 | + X_train_cnn = np.asarray([to_one_hot(x) for x in X_train_]) |
| 81 | + X_test_cnn = np.asarray([to_one_hot(x) for x in X_test_]) |
| 82 | + |
| 83 | + # And train the one-hot CNN classifier |
| 84 | + model_cnn = one_hot_cnn(dense_out, max_len) |
| 85 | + model_hist_cnn = model_cnn.fit(X_train_cnn, Y_train, batch_size=batch_size, epochs=args.epochs, |
| 86 | + verbose=1, validation_data=(X_test_cnn, Y_test)) |
| 87 | + cnn_acc = model_hist_cnn.history['acc'][-1] |
| 88 | + print("CNN model accuracy: ", cnn_acc) |
| 89 | + |
| 90 | + # And make predictions |
| 91 | + one_hot_cnn_predictions = model_cnn.predict(X_test_cnn) |
| 92 | + |
| 93 | + # Using the accuracies create an ensemble |
| 94 | + accuracies = [lstm_acc, cnn_acc] |
| 95 | + norm_accuracies = [a / sum(accuracies) for a in accuracies] |
| 96 | + |
| 97 | + print("Ensembling with weights: ") |
| 98 | + for na in norm_accuracies: |
| 99 | + print(na) |
| 100 | + ensembled_predictions = simple_ensembler([lstm_predictions, one_hot_cnn_predictions], |
| 101 | + norm_accuracies) |
| 102 | + final_preds = np.argmax(ensembled_predictions, axis=1) |
| 103 | + |
| 104 | + # Get the final accuracy |
| 105 | + print(classification_report(np.argmax(Y_test, axis=1), final_preds, |
| 106 | + target_names=data.labels_0.columns.values)) |
| 107 | + |
| 108 | + |
| 109 | +if __name__ == '__main__': |
| 110 | + parser = argparse.ArgumentParser() |
| 111 | + parser.add_argument('--file_path', type=str, default='./', |
| 112 | + help='file_path where the files to parse are located') |
| 113 | + parser.add_argument('--data_type', type=str, default='amazon', |
| 114 | + choices=['amazon'], |
| 115 | + help='dataset source') |
| 116 | + parser.add_argument('--epochs', type=int, default=10, |
| 117 | + help='Number of epochs for both models', action=check_size(1, 20000)) |
| 118 | + args_in = parser.parse_args() |
| 119 | + |
| 120 | + # Check file path |
| 121 | + if args_in.file_path: |
| 122 | + validate_existing_filepath(args_in.file_path) |
| 123 | + |
| 124 | + if args_in.data_type == 'amazon': |
| 125 | + data_in = Amazon_Reviews(args_in.file_path) |
| 126 | + ensemble_models(data_in, args_in) |
0 commit comments