|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +import sys |
| 5 | +from sklearn import datasets |
| 6 | +from sklearn import svm |
| 7 | +from sklearn.feature_extraction.text import CountVectorizer |
| 8 | +from sklearn.feature_extraction.text import TfidfTransformer |
| 9 | +from sklearn.naive_bayes import MultinomialNB |
| 10 | +from sklearn.linear_model import SGDClassifier |
| 11 | +from sklearn.linear_model import LogisticRegression |
| 12 | +from sklearn.ensemble import RandomForestClassifier |
| 13 | +from sklearn.pipeline import Pipeline |
| 14 | +from sklearn import metrics |
| 15 | +from sklearn.externals import joblib |
| 16 | +from nltk.stem import * |
| 17 | +from nltk.stem.porter import * |
| 18 | + |
| 19 | + |
| 20 | +if __name__ == '__main__': |
| 21 | + |
| 22 | + #train_file = open(sys.argv[1], 'r') |
| 23 | + #test_file = open(sys.argv[2], 'r') |
| 24 | + |
| 25 | + sizes = [] |
| 26 | + f1_scores_nb = [] |
| 27 | + f1_scores_svm = [] |
| 28 | + f1_scores_lr = [] |
| 29 | + f1_scores_rf = [] |
| 30 | + |
| 31 | + train_data = datasets.load_files("Selected 20NewsGroup/Training",decode_error='ignore',encoding='utf-8',shuffle=True) |
| 32 | + test_data = datasets.load_files("Selected 20NewsGroup/Test",decode_error='ignore',encoding='utf-8') |
| 33 | + docs_test = test_data.data |
| 34 | + |
| 35 | + # Removing header |
| 36 | + for i in range(len(train_data.data)): |
| 37 | + train_data.data[i] = "\n".join(train_data.data[i].split("\n")[3:]) |
| 38 | + |
| 39 | + # Extracting features |
| 40 | + count_vect = CountVectorizer() |
| 41 | + X_train_counts = count_vect.fit_transform(train_data.data) |
| 42 | + |
| 43 | + tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts) |
| 44 | + X_train_tf = tf_transformer.transform(X_train_counts) |
| 45 | + tfidf_transformer = TfidfTransformer() |
| 46 | + X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) |
| 47 | + |
| 48 | + # Stemming data |
| 49 | + stemmer = PorterStemmer() |
| 50 | + words = [] |
| 51 | + st = [] |
| 52 | + for i in range(len(train_data.data)): |
| 53 | + words = train_data.data[i].split(" ") |
| 54 | + singles = [stemmer.stem(word) for word in words] |
| 55 | + st.append(' '.join(singles)) |
| 56 | + |
| 57 | + |
| 58 | + # Naive Bayes |
| 59 | + print("Naive Bayes") |
| 60 | + print("\n") |
| 61 | + text_clf_nb = Pipeline([('vect', CountVectorizer(stop_words='english')), |
| 62 | + ('tfidf', TfidfTransformer()), |
| 63 | + ('clf', MultinomialNB()), |
| 64 | + ]) |
| 65 | + text_clf_1 = text_clf_nb.fit(st, train_data.target) |
| 66 | + predicted1 = text_clf_1.predict(docs_test) |
| 67 | + print(metrics.classification_report(test_data.target, predicted1, target_names=test_data.target_names)) |
| 68 | + |
| 69 | + # SVM Classifier |
| 70 | + print("SVM Classifier") |
| 71 | + print("\n") |
| 72 | + text_clf_svm = Pipeline([('vect', CountVectorizer(stop_words='english')), |
| 73 | + ('tfidf', TfidfTransformer()), |
| 74 | + ('clf', SGDClassifier(loss='hinge',penalty='l2')) |
| 75 | + ]) |
| 76 | + text_clf_2 = text_clf_svm.fit(st, train_data.target) |
| 77 | + predicted2 = text_clf_2.predict(docs_test) |
| 78 | + #svm.SVC(kernel='rbf') |
| 79 | + print(metrics.classification_report(test_data.target, predicted2, target_names=test_data.target_names)) |
| 80 | + |
| 81 | + #Logistic Regression |
| 82 | + print("Logistic Regression") |
| 83 | + print("\n") |
| 84 | + text_clf_lr = Pipeline([('vect', CountVectorizer(stop_words='english')), |
| 85 | + ('tfidf', TfidfTransformer()), |
| 86 | + ('clf', LogisticRegression()), |
| 87 | + ]) |
| 88 | + text_clf_3 = text_clf_lr.fit(st, train_data.target) |
| 89 | + predicted3 = text_clf_3.predict(docs_test) |
| 90 | + print(metrics.classification_report(test_data.target, predicted3, target_names=test_data.target_names)) |
| 91 | + |
| 92 | + #Random Forest |
| 93 | + print("Random Forest") |
| 94 | + print("\n") |
| 95 | + text_clf_rf = Pipeline([('vect', CountVectorizer(stop_words='english')), |
| 96 | + ('tfidf', TfidfTransformer()), |
| 97 | + ('clf', RandomForestClassifier()), |
| 98 | + ]) |
| 99 | + text_clf_4 = text_clf_rf.fit(st, train_data.target) |
| 100 | + predicted4 = text_clf_4.predict(docs_test) |
| 101 | + print(metrics.classification_report(test_data.target, predicted4, target_names=test_data.target_names)) |
| 102 | + |
| 103 | + |
| 104 | + # Splitting Training size |
| 105 | + size1 = 0.2 * len(train_data.data) |
| 106 | + sizes.append(size1) |
| 107 | + |
| 108 | + size2 = 0.4 * len(train_data.data) |
| 109 | + sizes.append(size2) |
| 110 | + |
| 111 | + size3 = 0.6 * len(train_data.data) |
| 112 | + sizes.append(size3) |
| 113 | + |
| 114 | + size4 = 0.8 * len(train_data.data) |
| 115 | + sizes.append(size4) |
| 116 | + |
| 117 | + # Loop for different splits in training sets |
| 118 | + for s in sizes: |
| 119 | + |
| 120 | + train = train_data.data[0:int(s)] |
| 121 | + train_target = train_data.target[0:int(s)] |
| 122 | + #Naive Bayes |
| 123 | + text_clf_split_nb = text_clf_nb.fit(train, train_target) |
| 124 | + predicted_nb = text_clf_split_nb.predict(docs_test) |
| 125 | + f1_scores_nb.append(metrics.f1_score(test_data.target, predicted_nb, average='macro')) |
| 126 | + |
| 127 | + #SVM |
| 128 | + text_clf_split_svm = text_clf_svm.fit(train, train_target) |
| 129 | + predicted_svm = text_clf_split_svm.predict(docs_test) |
| 130 | + f1_scores_svm.append(metrics.f1_score(test_data.target, predicted_svm, average='macro')) |
| 131 | + |
| 132 | + #Logistic Regression |
| 133 | + text_clf_split_lr = text_clf_lr.fit(train, train_target) |
| 134 | + predicted_lr = text_clf_split_lr.predict(docs_test) |
| 135 | + f1_scores_lr.append(metrics.f1_score(test_data.target, predicted_lr, average='macro')) |
| 136 | + |
| 137 | + #Random Forest |
| 138 | + text_clf_split_rf = text_clf_rf.fit(train, train_target) |
| 139 | + predicted_rf = text_clf_split_rf.predict(docs_test) |
| 140 | + f1_scores_rf.append(metrics.f1_score(test_data.target, predicted_rf, average='macro')) |
| 141 | + |
| 142 | + #plt.title("Learning curve for Naive Bayes") |
| 143 | + plt.ylabel("F1-scores") |
| 144 | + plt.xlabel("Training Sizes") |
| 145 | + plt.plot(sizes, f1_scores_nb, label="Naive Bayes") |
| 146 | + |
| 147 | + #plt.title("Learning curve for SVM") |
| 148 | + plt.ylabel("F1-scores") |
| 149 | + plt.xlabel("Training Sizes") |
| 150 | + plt.plot(sizes, f1_scores_svm, label="SVM") |
| 151 | + |
| 152 | + #plt.title("Learning curve for Logistic Regression") |
| 153 | + plt.ylabel("F1-scores") |
| 154 | + plt.xlabel("Training Sizes") |
| 155 | + plt.plot(sizes, f1_scores_lr, label="Logistic Regression") |
| 156 | + |
| 157 | + #plt.title("Learning curve for Random Forest") |
| 158 | + plt.ylabel("F1-scores") |
| 159 | + plt.xlabel("Training Sizes") |
| 160 | + plt.plot(sizes, f1_scores_rf, label="Random Forest") |
| 161 | + |
| 162 | + plt.grid(True) |
| 163 | + plt.legend(loc='best') |
| 164 | + plt.title("Training Size vs F1-score") |
| 165 | + plt.savefig("Legend plots") |
| 166 | + plt.close() |
| 167 | + |
| 168 | + #Code to dump and load |
| 169 | + |
| 170 | + #joblib.dump(text_clf_2, 'classifier.pkl') |
| 171 | + #classifier = joblib.load('classifier.pkl') |
| 172 | + #predicted_temp = classifier.predict(docs_test) |
| 173 | + #print("Loading.........") |
| 174 | + #print(metrics.classification_report(test_data.target, predicted_temp, target_names=test_data.target_names)) |
| 175 | + |
| 176 | + |
| 177 | + |
| 178 | + |
| 179 | + |
| 180 | + |
| 181 | + |
| 182 | + |
| 183 | + |
0 commit comments