|
| 1 | + |
| 2 | +import config |
| 3 | +import sys |
| 4 | +import numpy as np |
| 5 | +import pandas as pd |
| 6 | +import pickle as pkl |
| 7 | + |
| 8 | +from keras.preprocessing.sequence import pad_sequences |
| 9 | + |
| 10 | +import utils |
| 11 | +from preprocessor import DataProcessor |
| 12 | +from model import SemanticMatchingModel |
| 13 | + |
| 14 | + |
| 15 | +def get_model_data(dataset, params): |
| 16 | + |
| 17 | + X = {} |
| 18 | + X['id'] = dataset['id'].values |
| 19 | + X["label"] = dataset['label'].values |
| 20 | + |
| 21 | + # word level |
| 22 | + X['seq_word_left'] = pad_sequences(dataset.seq_word_left, maxlen=params["max_sequence_length_word"], |
| 23 | + padding=params["pad_sequences_padding"], |
| 24 | + truncating=params["pad_sequences_truncating"]) |
| 25 | + X["sequence_length_word"] = params["max_sequence_length_word"] * np.ones(dataset.shape[0]) |
| 26 | + |
| 27 | + X['seq_word_right'] = pad_sequences(dataset.seq_word_right, maxlen=params["max_sequence_length_word"], |
| 28 | + padding=params["pad_sequences_padding"], |
| 29 | + truncating=params["pad_sequences_truncating"]) |
| 30 | + X["sequence_length_word"] = params["max_sequence_length_word"] * np.ones(dataset.shape[0]) |
| 31 | + |
| 32 | + # char level |
| 33 | + X['seq_char_left'] = pad_sequences(dataset.seq_char_left, maxlen=params["max_sequence_length_char"], |
| 34 | + padding=params["pad_sequences_padding"], |
| 35 | + truncating=params["pad_sequences_truncating"]) |
| 36 | + X["sequence_length_char"] = params["max_sequence_length_char"] * np.ones(dataset.shape[0]) |
| 37 | + |
| 38 | + X['seq_char_right'] = pad_sequences(dataset.seq_char_right, maxlen=params["max_sequence_length_char"], |
| 39 | + padding=params["pad_sequences_padding"], |
| 40 | + truncating=params["pad_sequences_truncating"]) |
| 41 | + X["sequence_length_char"] = params["max_sequence_length_char"] * np.ones(dataset.shape[0]) |
| 42 | + |
| 43 | + return X |
| 44 | + |
| 45 | +params = { |
| 46 | + "offline_model_dir": "./weights/semantic_matching", |
| 47 | + "batch_size": 32, |
| 48 | + "epoch": 5, |
| 49 | + "l2_lambda": 0.0001, |
| 50 | + |
| 51 | + "embedding_dropout": 0.2, |
| 52 | + "embedding_word_dim": 128, |
| 53 | + "embedding_char_dim": 128, |
| 54 | + "embedding_dim": 128, |
| 55 | + |
| 56 | + "max_num_words": 10000, |
| 57 | + "max_num_chars": 10000, |
| 58 | + |
| 59 | + "threshold": 0.217277, |
| 60 | + |
| 61 | + "max_sequence_length_word": 20, |
| 62 | + "max_sequence_length_char": 30, |
| 63 | + "pad_sequences_padding": "post", |
| 64 | + "pad_sequences_truncating": "post", |
| 65 | + |
| 66 | + "optimizer_type": "nadam", |
| 67 | + "init_lr": 0.001, |
| 68 | + "beta1": 0.975, |
| 69 | + "beta2": 0.999, |
| 70 | + "decay_steps": 500, |
| 71 | + "decay_rate": 0.95, |
| 72 | + "schedule_decay": 0.004, |
| 73 | + "random_seed": 2018, |
| 74 | + "eval_every_num_update": 100, |
| 75 | + |
| 76 | + "encode_method": "fasttext", |
| 77 | + "attend_method": "attention", |
| 78 | + |
| 79 | + "cnn_num_filters": 32, |
| 80 | + "cnn_filter_sizes": [1, 2, 3], |
| 81 | + "cnn_timedistributed": False, |
| 82 | + |
| 83 | + "rnn_num_units": 20, |
| 84 | + "rnn_cell_type": "gru", |
| 85 | + |
| 86 | + # fc block |
| 87 | + "fc_type": "fc", |
| 88 | + "fc_dim": 64, |
| 89 | + "fc_dropout": 0, |
| 90 | +} |
| 91 | + |
| 92 | +model_name = "semantic_matching" |
| 93 | + |
| 94 | +def train(): |
| 95 | + |
| 96 | + utils._makedirs("../logs") |
| 97 | + utils._makedirs("../output") |
| 98 | + logger = utils._get_logger("../logs", "tf-%s.log" % utils._timestamp()) |
| 99 | + |
| 100 | + |
| 101 | + dfTrain = pd.read_csv(config.TRAIN_FILE, header=None, sep="\t") |
| 102 | + dfTrain.columns = ["id", "left", "right", "label"] |
| 103 | + |
| 104 | + dfTrain.dropna(inplace=True) |
| 105 | + |
| 106 | + # shuffle training data |
| 107 | + dfTrain = dfTrain.sample(frac=1.0) |
| 108 | + |
| 109 | + dp = DataProcessor(max_num_words=params["max_num_words"], max_num_chars=params["max_num_chars"]) |
| 110 | + dfTrain = dp.fit_transform(dfTrain) |
| 111 | + |
| 112 | + N = dfTrain.shape[0] |
| 113 | + train_ratio = 0.6 |
| 114 | + train_num = int(N*train_ratio) |
| 115 | + X_train = get_model_data(dfTrain[:train_num], params) |
| 116 | + X_valid = get_model_data(dfTrain[train_num:], params) |
| 117 | + |
| 118 | + model = SemanticMatchingModel(model_name, params, logger=logger, threshold=0.2) |
| 119 | + model.fit(X_train, validation_data=X_valid, shuffle=False) |
| 120 | + |
| 121 | + # save model |
| 122 | + model.save_session() |
| 123 | + with open("dp.pkl", "wb") as f: |
| 124 | + pkl.dump((dp, model.threshold), f, protocol=2) |
| 125 | + |
| 126 | + |
| 127 | +def submit(input_file, output_file): |
| 128 | + |
| 129 | + print("read %s"%input_file) |
| 130 | + print("write %s"%output_file) |
| 131 | + |
| 132 | + # load model |
| 133 | + with open("dp.pkl", "rb") as f: |
| 134 | + dp, threshold = pkl.load(f) |
| 135 | + model = SemanticMatchingModel(model_name, params, logger=None, threshold=threshold, training=False) |
| 136 | + model.restore_session() |
| 137 | + |
| 138 | + dfTest = pd.read_csv(input_file, header=None, sep="\t") |
| 139 | + dfTest.columns = ["id", "left", "right"] |
| 140 | + dfTest["label"] = np.zeros(dfTest.shape[0]) |
| 141 | + |
| 142 | + dfTest = dp.transform(dfTest) |
| 143 | + X_test = get_model_data(dfTest, params) |
| 144 | + |
| 145 | + dfTest["label"] = model.predict(X_test) |
| 146 | + |
| 147 | + dfTest[["id", "label"]].to_csv(output_file, header=False, index=False, sep="\t") |
| 148 | + |
| 149 | + |
| 150 | +if __name__ == "__main__": |
| 151 | + if len(sys.argv) > 2: |
| 152 | + submit(sys.argv[1], sys.argv[2]) |
| 153 | + else: |
| 154 | + train() |
0 commit comments