-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassical_model.py
More file actions
110 lines (91 loc) · 3.75 KB
/
Copy pathclassical_model.py
File metadata and controls
110 lines (91 loc) · 3.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import time
import matplotlib.pyplot as plt
from nltk.corpus import stopwords
from sklearn import feature_extraction, dummy
from sklearn.metrics import classification_report, ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn import svm
from sklearn import naive_bayes
from sklearn.ensemble import RandomForestClassifier
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
import get_data
def splitdata(df):
global start
start = time.time()
X, y = df.iloc[:, 0], df.iloc[:, 1]
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.2,
random_state=0) # Randomly splits data into training and testing set
createModel(X_train, X_test, y_train, y_test)
def createModel(X_train, X_test, y_train, y_test):
vectorizer = feature_extraction.text.TfidfVectorizer(ngram_range=(4, 4), analyzer='char',
stop_words=stopwords.words(
'german')) # Vectoriser with tf-idf statistic
"""
pipeline_NB = pipeline.Pipeline([
('vectorizer', vectorizer),
('clf', naive_bayes.MultinomialNB())
])
pipeline_SVM = pipeline.Pipeline([
('vectorizer', vectorizer),
('clf', svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto'))
])
pipeline_baseline = pipeline.Pipeline([
('vectorizer', vectorizer),
('clf', dummy.DummyClassifier(strategy="most_frequent"))
])
pipeline_RandomForest = pipeline.Pipeline([
('vectorizer', vectorizer),
('clf', RandomForestClassifier())
])
"""
pipeline_SVM = Pipeline([
('vectorizer', vectorizer),
('sampling', SMOTE(random_state=27)), # Example with SMOTE
('classification', svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto'))
])
pipeline_SVM.fit(X_train, y_train) # Fits the model
y_predicted = pipeline_SVM.predict(X_test) # Use fitted model on test data
evaluateModel(y_test, y_predicted, pipeline_SVM)
# Reveals results of the model and creates confusion matrix
def evaluateModel(y_test, y_predicted, clf):
print("Time taken: ", time.time() - start)
print(classification_report(y_test, y_predicted))
accuracy = (metrics.accuracy_score(y_test, y_predicted)) * 100
print(accuracy, '%')
matrix = metrics.confusion_matrix(y_test, y_predicted)
print('Confusion matrix: \n', matrix)
disp = ConfusionMatrixDisplay(confusion_matrix=matrix, display_labels=clf.classes_)
disp.plot()
plt.xticks(rotation=45, ha='right')
plt.gcf().subplots_adjust(bottom=0.3)
plt.show()
# Used to find total and unique word count of a corpus
def findWordCount(data):
totalCounter = 0
uniqueCounter = 0
unique_words = []
for i in range(len(data)):
totalCounter = totalCounter + len(data[i].split())
temp = data[i].split()
for word in temp:
if word not in unique_words:
unique_words.append(word)
uniqueCounter += 1
print("total " + str(totalCounter))
print("unique " + str(uniqueCounter))
# Used to get all class combinations for dialect-distance comparison
def find_combinations(labels):
for i in range(len(labels)):
for j in range(len(labels)):
if i == j or i < j:
continue
print(labels[i] + " - " + labels[j])
def main():
group1, group2, group3, group4 = get_data.createDataframe(isHeatmap=False)
splitdata(group4)
if __name__ == '__main__':
main()