|
| 1 | +import re |
| 2 | +import string |
| 3 | +from fastai.text import * # just for utilty functions pd, np, Path etc. |
| 4 | + |
| 5 | +from sklearn.linear_model import LogisticRegression |
| 6 | +from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer |
| 7 | + |
| 8 | +from ...helpers.training import set_seed |
| 9 | + |
| 10 | +def transform_df(df): |
| 11 | + df=df.replace(re.compile(r"(xxref|xxanchor)-[\w\d-]*"), "\\1 ") |
| 12 | + df=df.replace(re.compile(r"(^|[ ])\d+\.\d+\b"), " xxnum ") |
| 13 | + df=df.replace(re.compile(r"(^|[ ])\d\b"), " xxnum ") |
| 14 | + df=df.replace(re.compile(r"\bdata set\b"), " dataset ") |
| 15 | + df = df.drop_duplicates(["text", "cell_content", "cell_type"]).fillna("") |
| 16 | + return df |
| 17 | + |
| 18 | +def train_valid_split(df, seed=42, by="cell_content"): |
| 19 | + set_seed(seed, "val_split") |
| 20 | + contents = np.random.permutation(df[by].unique()) |
| 21 | + val_split = int(len(contents)*0.1) |
| 22 | + val_keys = contents[:val_split] |
| 23 | + split = df[by].isin(val_keys) |
| 24 | + valid_df = df[split] |
| 25 | + train_df = df[~split] |
| 26 | + len(train_df), len(valid_df) |
| 27 | + return train_df, valid_df |
| 28 | + |
| 29 | +def get_class_column(y, classIdx): |
| 30 | + if len(y.shape) == 1: |
| 31 | + return y == classIdx |
| 32 | + else: |
| 33 | + return y.iloc[:, classIdx] |
| 34 | + |
| 35 | +def get_number_of_classes(y): |
| 36 | + if len(y.shape) == 1: |
| 37 | + return len(np.unique(y)) |
| 38 | + else: |
| 39 | + return y.shape[1] |
| 40 | + |
| 41 | +class NBSVM: |
| 42 | + def __init__(self, solver='liblinear', dual=True): |
| 43 | + self.solver = solver # 'lbfgs' - large, liblinear for small datasets |
| 44 | + self.dual = dual |
| 45 | + pass |
| 46 | + |
| 47 | + re_tok = re.compile(f'([{string.punctuation}“”¨«»®´·º½¾¿¡§£₤‘’])') |
| 48 | + |
| 49 | + def tokenize(self, s): |
| 50 | + return self.re_tok.sub(r' \1 ', s).split() |
| 51 | + |
| 52 | + def pr(self, y_i, y): |
| 53 | + p = self.trn_term_doc[y == y_i].sum(0) |
| 54 | + return (p+1) / ((y == y_i).sum()+1) |
| 55 | + |
| 56 | + def get_mdl(self, y): |
| 57 | + y = y.values |
| 58 | + r = np.log(self.pr(1, y) / self.pr(0, y)) |
| 59 | + m = LogisticRegression(C=4, dual=self.dual, solver=self.solver, max_iter=1000) |
| 60 | + x_nb = self.trn_term_doc.multiply(r) |
| 61 | + return m.fit(x_nb, y), r |
| 62 | + |
| 63 | + def bow(self, X_train): |
| 64 | + self.n = X_train.shape[0] |
| 65 | + self.vec = TfidfVectorizer(ngram_range=(1, 2), tokenizer=self.tokenize, |
| 66 | + min_df=3, max_df=0.9, strip_accents='unicode', use_idf=1, |
| 67 | + smooth_idf=1, sublinear_tf=1) |
| 68 | + return self.vec.fit_transform(X_train) |
| 69 | + |
| 70 | + def train_models(self, y_train): |
| 71 | + self.models = [] |
| 72 | + for i in range(0, self.c): |
| 73 | + print('fit', i) |
| 74 | + m, r = self.get_mdl(get_class_column(y_train, i)) |
| 75 | + self.models.append((m, r)) |
| 76 | + |
| 77 | + def fit(self, X_train, y_train): |
| 78 | + self.trn_term_doc = self.bow(X_train) |
| 79 | + self.c = get_number_of_classes(y_train) |
| 80 | + self.train_models(y_train) |
| 81 | + |
| 82 | + def predict_proba(self, X_test): |
| 83 | + preds = np.zeros((len(X_test), self.c)) |
| 84 | + test_term_doc = self.vec.transform(X_test) |
| 85 | + for i in range(0, self.c): |
| 86 | + m, r = self.models[i] |
| 87 | + preds[:, i] = m.predict_proba(test_term_doc.multiply(r))[:, 1] |
| 88 | + return preds |
| 89 | + |
| 90 | + def validate(self, X_test, y_test): |
| 91 | + acc = (np.argmax(self.predict_proba(X_test), axis=1) == y_test).mean() |
| 92 | + return acc |
| 93 | + |
| 94 | +def metrics(preds, true_y): |
| 95 | + y = true_y |
| 96 | + p = preds |
| 97 | + acc = (p == y).mean() |
| 98 | + tp = ((y != 0) & (p == y)).sum() |
| 99 | + fp = ((p != 0) & (p != y)).sum() |
| 100 | + prec = tp / (fp + tp) |
| 101 | + return { |
| 102 | + "precision": prec, |
| 103 | + "accuracy": acc, |
| 104 | + "TP": tp, |
| 105 | + "FP": fp, |
| 106 | + } |
| 107 | + |
| 108 | + |
| 109 | +def preds_for_cell_content(test_df, probs, group_by=["cell_content"]): |
| 110 | + test_df = test_df.copy() |
| 111 | + test_df["pred"] = np.argmax(probs, axis=1) |
| 112 | + grouped_preds = test_df.groupby(group_by)["pred"].agg( |
| 113 | + lambda x: x.value_counts().index[0]) |
| 114 | + grouped_counts = test_df.groupby(group_by)["pred"].count() |
| 115 | + results = pd.DataFrame({'true': test_df.groupby(group_by)["label"].agg(lambda x: x.value_counts().index[0]), |
| 116 | + 'pred': grouped_preds, |
| 117 | + 'counts': grouped_counts}) |
| 118 | + return results |
| 119 | + |
| 120 | +def preds_for_cell_content_multi(test_df, probs, group_by=["cell_content"]): |
| 121 | + test_df = test_df.copy() |
| 122 | + probs_df = pd.DataFrame(probs, index=test_df.index) |
| 123 | + test_df = pd.concat([test_df, probs_df], axis=1) |
| 124 | + grouped_preds = np.argmax(test_df.groupby( |
| 125 | + group_by)[probs_df.columns].sum().values, axis=1) |
| 126 | + grouped_counts = test_df.groupby(group_by)["label"].count() |
| 127 | + results = pd.DataFrame({'true': test_df.groupby(group_by)["label"].agg(lambda x: x.value_counts().index[0]), |
| 128 | + 'pred': grouped_preds, |
| 129 | + 'counts': grouped_counts}) |
| 130 | + return results |
| 131 | + |
| 132 | +def test_model(model, tdf): |
| 133 | + probs = model(tdf["text"]) |
| 134 | + preds = np.argmax(probs, axis=1) |
| 135 | + print("Results of categorisation on text fagment level") |
| 136 | + print(metrics(preds, tdf.label)) |
| 137 | + |
| 138 | + print("Results per cell_content grouped using majority voting") |
| 139 | + results = preds_for_cell_content(tdf, probs) |
| 140 | + print(metrics(results["pred"], results["true"])) |
| 141 | + |
| 142 | + print("Results per cell_content grouped with multi category mean") |
| 143 | + results = preds_for_cell_content_multi(tdf, probs) |
| 144 | + print(metrics(results["pred"], results["true"])) |
| 145 | + |
| 146 | + print("Results per cell_content grouped with multi category mean - only on fragments from the same paper that the coresponding table") |
| 147 | + results = preds_for_cell_content_multi( |
| 148 | + tdf[tdf.this_paper], probs[tdf.this_paper]) |
| 149 | + print(metrics(results["pred"], results["true"])) |
0 commit comments