|
| 1 | +from NBSVMpreprocessing import create_bow, build_vocab |
| 2 | +import numpy as np |
| 3 | +from sklearn.svm import LinearSVC |
| 4 | +import time |
| 5 | +""" |
| 6 | +Naive Bayes Support Vector Machine interpolation, NBSVM. |
| 7 | +""" |
| 8 | + |
| 9 | +## tuning_params: |
| 10 | +gram = 2 |
| 11 | +C = 100 |
| 12 | +beta = 0.25 |
| 13 | +alpha = 1 |
| 14 | + |
| 15 | + |
| 16 | +""" |
| 17 | +Trains the Multinomial Naive Bayes Model |
| 18 | +""" |
| 19 | +def train_nb(vocab_list, df): |
| 20 | + |
| 21 | + #find prior = total positive examples/total examples |
| 22 | + total_sents = len(df['label']) |
| 23 | + pos_sents = 0 |
| 24 | + neg_sents = 0 |
| 25 | + for i in range(len(df['label'])): |
| 26 | + if(df['label'][i] == 1): |
| 27 | + pos_sents += 1 |
| 28 | + neg_sents = total_sents - pos_sents |
| 29 | + |
| 30 | + #initiate counts for word appearance conditional on label == 1 and label == 0 |
| 31 | + #alpha is laplacian smoothing parameter |
| 32 | + pos_list = np.ones(len(vocab_list)) * alpha |
| 33 | + neg_list = np.ones(len(vocab_list)) * alpha |
| 34 | + |
| 35 | + for sentence, label in zip(df['sentence'], df['label']): |
| 36 | + bow = create_bow(sentence, vocab_list, gram) |
| 37 | + |
| 38 | + if label == 1: |
| 39 | + pos_list += bow |
| 40 | + else: |
| 41 | + neg_list += bow |
| 42 | + |
| 43 | + #Calculate log-count ratio |
| 44 | + x = (pos_list/abs(pos_list).sum()) |
| 45 | + y = (neg_list/abs(neg_list).sum()) |
| 46 | + r = np.log(x/y) |
| 47 | + b = np.log(pos_sents/neg_sents) |
| 48 | + |
| 49 | + return r, b |
| 50 | + |
| 51 | +""" |
| 52 | +Trains the (linear-kernel) SVM with L2 Regularization |
| 53 | +""" |
| 54 | +def train_svm(vocab_list, df_train, c, r): |
| 55 | +# clf = LinearSVC(C=c, class_weight=None, dual=False, fit_intercept=True, |
| 56 | +# loss='squared_hinge', max_iter=1000, |
| 57 | +# multi_class='ovr', penalty='l2', random_state=0, tol=0.0001, |
| 58 | +# verbose=0) |
| 59 | + print('creating SVM model') |
| 60 | + clf = LinearSVC(C=c) |
| 61 | + print('creating training matrix') |
| 62 | + M = np.array([]) |
| 63 | + X = np.zeros((len(df_train['sentence']), len(vocab_list))) |
| 64 | + bow = np.array([]) |
| 65 | + con = 0 |
| 66 | + for sentence in df_train['sentence']: |
| 67 | + print('iteration: {}'.format(con+1)) |
| 68 | + bow = create_bow(sentence, vocab_list, gram) |
| 69 | + M = r * bow |
| 70 | + for i in range(len(M)): |
| 71 | + X[con, i] = M[i] |
| 72 | +# X.append(M) |
| 73 | + con=con+1 |
| 74 | + #X = np.array([(r * create_bow(sentence, vocab_list, gram)) for sentence in df_train['sentence']]) |
| 75 | + y = df_train['label'] |
| 76 | + |
| 77 | + clf.fit(X, y) |
| 78 | + svm_coef = clf.coef_ |
| 79 | + svm_intercept = clf.intercept_ |
| 80 | + |
| 81 | + return svm_coef, svm_intercept, clf |
| 82 | + |
| 83 | +""" |
| 84 | +Predict classification with MNB |
| 85 | +""" |
| 86 | +def predict(df_test, w, b, vocab_list): |
| 87 | + total_sents = len(df_test['label']) |
| 88 | + total_score = 0 |
| 89 | + |
| 90 | + for sentence, label in zip(df_test['sentence'], df_test['label']): |
| 91 | + bow = create_bow(sentence, vocab_list, gram) |
| 92 | + |
| 93 | + result = np.sign(np.dot(bow, w.T) + b) |
| 94 | + if result == -1: |
| 95 | + result = 0 |
| 96 | + if result == label: |
| 97 | + total_score +=1 |
| 98 | + |
| 99 | + return total_score/total_sents |
| 100 | + |
| 101 | +""" |
| 102 | +Predict classification with NB-SVM |
| 103 | +""" |
| 104 | +def predict_nbsvm(df_test, svm_coef, svm_intercept, r, b, vocab_list): |
| 105 | + total_sents = len(df_test['label']) |
| 106 | + total_score = 0 |
| 107 | + |
| 108 | + for sentence, label in zip(df_test['sentence'], df_test['label']): |
| 109 | + bow = r * create_bow(sentence, vocab_list, gram) |
| 110 | + w_bar = (abs(svm_coef).sum())/len(vocab_list) |
| 111 | + w_prime = (1 - beta)*(w_bar) + (beta * svm_coef) |
| 112 | + result = np.sign(np.dot(bow, w_prime.T) + svm_intercept) |
| 113 | + if result == -1: |
| 114 | + result = 0 |
| 115 | + if result == label: |
| 116 | + total_score +=1 |
| 117 | + |
| 118 | + return total_score/total_sents |
| 119 | + |
| 120 | + |
| 121 | + |
| 122 | +if __name__ == "__main__": |
| 123 | + |
| 124 | + time_first = time.time() |
| 125 | + print("Building Dataset...") |
| 126 | + vocab_list, df_train, df_val, df_test = build_vocab(gram) |
| 127 | + |
| 128 | + |
| 129 | + print("Training Multinomial Naive Bayes...") |
| 130 | + r, b = train_nb(vocab_list, df_train) |
| 131 | + |
| 132 | + #Train SVM |
| 133 | + print("Training LinearSVM...") |
| 134 | + svm_coef, svm_intercept, clf = train_svm(vocab_list, df_train, C, r) |
| 135 | + |
| 136 | + |
| 137 | + #Test Models |
| 138 | + print("Test using NBSVM ({:.4f}-gram):".format(gram)) |
| 139 | + accuracy = predict_nbsvm(df_val, svm_coef, svm_intercept, r, b, vocab_list) |
| 140 | + print("Beta: {} Accuracy: {}".format(beta, accuracy)) |
| 141 | + |
| 142 | + print("Test using MNB ({:.4f}-gram):".format(gram)) |
| 143 | + mnb_acc = predict(df_val, r, b, vocab_list) |
| 144 | + print("Accuracy: {}".format(mnb_acc)) |
| 145 | + |
| 146 | + |
| 147 | + |
| 148 | + |
| 149 | + |
| 150 | + |
| 151 | + |
| 152 | + |
| 153 | + |
| 154 | + |
| 155 | + |
| 156 | + |
| 157 | + |
0 commit comments