|
| 1 | +import numpy as np |
| 2 | +import tensorflow as tf |
| 3 | +import spacy |
| 4 | +from sklearn.preprocessing import LabelBinarizer |
| 5 | +import os |
| 6 | +import cloudpickle |
| 7 | +import time |
| 8 | + |
| 9 | +class TfIntentClassifier(): |
| 10 | + |
| 11 | + def __init__(self): |
| 12 | + self.model = None |
| 13 | + self.nlp = spacy.load('en') |
| 14 | + self.label_encoder = LabelBinarizer() |
| 15 | + self.graph=None |
| 16 | + print("im executed") |
| 17 | + |
| 18 | + def train(self, X, y, models_dir=None, verbose=True): |
| 19 | + """ |
| 20 | + Train intent classifier for given training data |
| 21 | + :param X: |
| 22 | + :param y: |
| 23 | + :param outpath: |
| 24 | + :param verbose: |
| 25 | + :return: |
| 26 | + """ |
| 27 | + |
| 28 | + def create_model(): |
| 29 | + """ |
| 30 | + Define and return tensorflow model. |
| 31 | + """ |
| 32 | + model = tf.keras.Sequential() |
| 33 | + model.add(tf.keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(vocab_size,))) |
| 34 | + model.add(tf.keras.layers.Dense(num_labels, activation=tf.nn.relu)) |
| 35 | + model.add(tf.keras.layers.Dense(num_labels, activation=tf.nn.softmax)) |
| 36 | + |
| 37 | + model.compile(loss='categorical_crossentropy', |
| 38 | + optimizer='rmsprop', |
| 39 | + metrics=['accuracy']) |
| 40 | + |
| 41 | + model.summary() |
| 42 | + |
| 43 | + return model |
| 44 | + |
| 45 | + # spacy context vector size |
| 46 | + vocab_size = 384 |
| 47 | + |
| 48 | + # create spacy doc vector matrix |
| 49 | + x_train = np.array([list(self.nlp(x).vector) for x in X]) |
| 50 | + |
| 51 | + num_labels = len(set(y)) |
| 52 | + self.label_encoder.fit(y) |
| 53 | + y_train = self.label_encoder.transform(y) |
| 54 | + |
| 55 | + del self.model |
| 56 | + tf.keras.backend.clear_session() |
| 57 | + time.sleep(3) |
| 58 | + |
| 59 | + self.model = create_model() |
| 60 | + # start training |
| 61 | + self.model.fit(x_train, y_train, shuffle=True, epochs=50, verbose=1) |
| 62 | + |
| 63 | + if models_dir: |
| 64 | + tf.keras.models.save_model( |
| 65 | + self.model, |
| 66 | + os.path.join(models_dir, "tf_intent_model.hd5") |
| 67 | + |
| 68 | + ) |
| 69 | + if verbose: |
| 70 | + print("TF Model written out to {}".format(os.path.join(models_dir, "tf_intent_model.hd5"))) |
| 71 | + |
| 72 | + cloudpickle.dump(self.label_encoder, open(os.path.join(models_dir, "labels.pkl"), 'wb')) |
| 73 | + |
| 74 | + if verbose: |
| 75 | + print("Labels written out to {}".format(os.path.join(models_dir, "labels.pkl"))) |
| 76 | + |
| 77 | + |
| 78 | + def load(self, models_dir): |
| 79 | + try: |
| 80 | + del self.model |
| 81 | + tf.keras.backend.clear_session() |
| 82 | + self.model = tf.keras.models.load_model(os.path.join(models_dir, "tf_intent_model.hd5"),compile=True) |
| 83 | + self.graph = tf.get_default_graph() |
| 84 | + print("Tf model loaded") |
| 85 | + with open(os.path.join(models_dir, "labels.pkl"), 'rb') as f: |
| 86 | + self.label_encoder = cloudpickle.load(f) |
| 87 | + print("Labels model loaded") |
| 88 | + |
| 89 | + except IOError: |
| 90 | + return False |
| 91 | + |
| 92 | + def predict(self, text): |
| 93 | + """ |
| 94 | + Predict class label for given model |
| 95 | + :param text: |
| 96 | + :param PATH: |
| 97 | + :return: |
| 98 | + """ |
| 99 | + return self.process(text) |
| 100 | + |
| 101 | + def predict_proba(self, x): |
| 102 | + """Given a bow vector of an input text, predict most probable label. Returns only the most likely label. |
| 103 | +
|
| 104 | + :param x: raw input text |
| 105 | + :return: tuple of first, the most probable label and second, its probability""" |
| 106 | + |
| 107 | + x_predict = [self.nlp(x).vector] |
| 108 | + with self.graph.as_default(): |
| 109 | + pred_result = self.model.predict(np.array([x_predict[0]])) |
| 110 | + sorted_indices = np.fliplr(np.argsort(pred_result, axis=1)) |
| 111 | + return sorted_indices, pred_result[:, sorted_indices] |
| 112 | + |
| 113 | + def process(self, x, return_type="intent", INTENT_RANKING_LENGTH=5): |
| 114 | + """Returns the most likely intent and its probability for the input text.""" |
| 115 | + |
| 116 | + if not self.model: |
| 117 | + print("no class") |
| 118 | + intent = None |
| 119 | + intent_ranking = [] |
| 120 | + else: |
| 121 | + intents, probabilities = self.predict_proba(x) |
| 122 | + intents, probabilities = [self.label_encoder.classes_[intent] for intent in |
| 123 | + intents.flatten()], probabilities.flatten() |
| 124 | + |
| 125 | + if len(intents) > 0 and len(probabilities) > 0: |
| 126 | + ranking = list(zip(list(intents), list(probabilities)))[:INTENT_RANKING_LENGTH] |
| 127 | + |
| 128 | + intent = {"intent": intents[0], "confidence": float("%.2f"%probabilities[0])} |
| 129 | + intent_ranking = [{"intent": intent_name, "confidence": float("%.2f"%score)} for intent_name, score in ranking] |
| 130 | + else: |
| 131 | + intent = {"name": None, "confidence": 0.0} |
| 132 | + intent_ranking = [] |
| 133 | + if return_type == "intent": |
| 134 | + return intent |
| 135 | + else: |
| 136 | + return intent_ranking |
0 commit comments