|
| 1 | +__author__ = 'Federico' |
| 2 | +# Multiclass Naive-Bayes classifier for categorization of WoN e-mail dataset |
| 3 | +# It uses MultinomialNB classifier |
| 4 | + |
| 5 | +from numpy import * |
| 6 | +from tools.tensor_utils import read_input_tensor, SparseTensor |
| 7 | +from sklearn import metrics |
| 8 | +from sklearn.naive_bayes import MultinomialNB |
| 9 | +from sklearn.pipeline import Pipeline |
| 10 | +from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer |
| 11 | +from nltk.corpus import stopwords |
| 12 | + |
| 13 | +# Get the input from a folder in C: |
| 14 | +def get_example_data(): |
| 15 | + |
| 16 | + header_file = 'C:/Users/Federico/Desktop/test/evaluation/tensor_content_NEW/headers.txt' |
| 17 | + data_file_prefix = 'C:/Users/Federico/Desktop/test/evaluation/tensor_content_NEW' |
| 18 | + data_files = [data_file_prefix + "/connection.mtx", |
| 19 | + data_file_prefix + "/needtype.mtx", |
| 20 | + data_file_prefix + "/subject.mtx", |
| 21 | + data_file_prefix + "/content.mtx", |
| 22 | + data_file_prefix + "/category.mtx"] |
| 23 | + slices = [SparseTensor.CONNECTION_SLICE, SparseTensor.NEED_TYPE_SLICE, SparseTensor.ATTR_SUBJECT_SLICE, |
| 24 | + SparseTensor.ATTR_CONTENT_SLICE, SparseTensor.CATEGORY_SLICE] |
| 25 | + |
| 26 | + tensor = read_input_tensor(header_file, data_files, slices, False) |
| 27 | + |
| 28 | + data = [] |
| 29 | + target = [] |
| 30 | + |
| 31 | + # Store the chosen input into lists. |
| 32 | + # The "if" statement is meant to include only samples with a single category (No multilabel) |
| 33 | + for need_index in tensor.getNeedIndices(): |
| 34 | + content = "" |
| 35 | + categories = tensor.getAttributesForNeed(need_index, SparseTensor.CATEGORY_SLICE) |
| 36 | + numCategories = len(categories) |
| 37 | + if numCategories >= 1: |
| 38 | + category_index = tensor.getSliceMatrix(SparseTensor.CATEGORY_SLICE)[need_index,].nonzero()[1][0] |
| 39 | + target.append(category_index) |
| 40 | + for word in tensor.getAttributesForNeed(need_index, SparseTensor.ATTR_SUBJECT_SLICE): |
| 41 | + content += word + " " |
| 42 | + data.append(content) |
| 43 | + |
| 44 | + # Include only few of all the categories (e.g. with samples > n) |
| 45 | + newdata = [] |
| 46 | + newtarget = [] |
| 47 | + for i in range(len(target)): |
| 48 | + |
| 49 | + if target.count(target[i]) > 50: |
| 50 | + newtarget.append(target[i]) |
| 51 | + newdata.append(data[i]) |
| 52 | + |
| 53 | + data = newdata |
| 54 | + target = newtarget |
| 55 | + |
| 56 | + # Print out the input, just a check: |
| 57 | + target_names = tensor.getHeaders() |
| 58 | + print("test") |
| 59 | + print data |
| 60 | + print target_names |
| 61 | + print target |
| 62 | + |
| 63 | + return data, target, target_names |
| 64 | + |
| 65 | +# Call for the input |
| 66 | +my_data, my_target, my_targetname = get_example_data() |
| 67 | + |
| 68 | +# A little information about dimensions and format of the input: |
| 69 | +print type(my_data), type(my_target), # format of data and targets |
| 70 | +print len(my_data) # number of samples |
| 71 | +print len(my_target) |
| 72 | + |
| 73 | + |
| 74 | +# Let's build the training and testing datasets: |
| 75 | +SPLIT_PERC = 0.80 # 80% goes into training, 20% into test |
| 76 | +split_size = int(len(my_data)*SPLIT_PERC) |
| 77 | +X_train = my_data[:split_size] |
| 78 | +X_test = my_data[split_size:] |
| 79 | +y_train = my_target[:split_size] |
| 80 | +y_test = my_target[split_size:] |
| 81 | + |
| 82 | + |
| 83 | +# Training, prediction and evaluation of the classifier(s): |
| 84 | +def train_and_evaluate(clf, X_train, X_test, y_train, y_test, y_name): |
| 85 | + |
| 86 | + # Training |
| 87 | + clf.fit(X_train, y_train) |
| 88 | + # Prediction of testing sets |
| 89 | + y_pred = clf.predict(X_test) |
| 90 | + |
| 91 | + # Precision, recall and support (i.e. nr. of samples used for the testing) |
| 92 | + print "Classification Report:" |
| 93 | + print metrics.classification_report(y_test, y_pred) |
| 94 | + # Confusion Matrix |
| 95 | + print "Confusion Matrix:" |
| 96 | + print metrics.confusion_matrix(y_test, y_pred) |
| 97 | + |
| 98 | + # Visualization of Categories / Assigned / Data |
| 99 | + print "Tested data => assigned category, data:" |
| 100 | + for i in range(len(X_test)): |
| 101 | + print str(i) + ") Real category: " + str(y_name[y_test[i]]) + ", Assigned category: " + \ |
| 102 | + str(y_name[y_pred[i]]) + ", Data: " + str(X_test[i]) |
| 103 | + |
| 104 | + # Assign names to the categories (defined by numbers) |
| 105 | + print "\n Categories: \n" |
| 106 | + categories = set() |
| 107 | + for cat in y_pred: |
| 108 | + categories.add(cat) |
| 109 | + categories = sorted(categories) |
| 110 | + for cat in categories: |
| 111 | + print str(cat) + " " + y_name[cat] |
| 112 | + |
| 113 | +# Introducing stop words |
| 114 | +stopset = set(stopwords.words('english')) |
| 115 | + |
| 116 | +# Two different classifiers: Count and Tfidf vectors |
| 117 | +clf_count = Pipeline([ |
| 118 | + ('vect', CountVectorizer( |
| 119 | + stop_words=stopset, |
| 120 | + token_pattern=ur"\b[a-z0-9_\-\.]+[a-z][a-z0-9_\-\.]+\b", |
| 121 | + )), |
| 122 | + ('clf', MultinomialNB(alpha=1)), |
| 123 | + ]) |
| 124 | + |
| 125 | +clf_tfidf = Pipeline([ |
| 126 | + ('vect', TfidfVectorizer( |
| 127 | + stop_words=stopset, |
| 128 | + token_pattern=ur"\b[a-z0-9_\-\.]+[a-z][a-z0-9_\-\.]+\b", |
| 129 | + )), |
| 130 | + ('clf', MultinomialNB(alpha=1)), |
| 131 | + ]) |
| 132 | + |
| 133 | +# List of classifiers |
| 134 | +clfs = [clf_count, clf_tfidf] |
| 135 | + |
| 136 | +# Run the evaluation/classification |
| 137 | +for clf in clfs: |
| 138 | + train_and_evaluate(clf, X_train, X_test, y_train, y_test, my_targetname) |
0 commit comments