forked from IshaanG/AutomatedEssayScorer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
277 lines (172 loc) · 7.36 KB
/
model.py
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import nltk
import pandas as pd
import numpy as np
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
import re
import collections
from collections import defaultdict
from sklearn import ensemble
from sklearn.model_selection import GridSearchCV
from sklearn.externals import joblib
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LinearRegression
dataframe = pd.read_csv('essays_and_scores.csv', encoding='latin-1')
dataframe = dataframe.dropna(axis=0, how='any')
dataframe = dataframe.dropna(axis=1, how='any')
x = dataframe[['essay_set', 'essay', 'domain1_score']]
x1 = x[x['essay_set'] == 1]
x2 = x[x['essay_set'] == 2]
x3 = x[x['essay_set'] == 3]
x4 = x[x['essay_set'] == 4]
x5 = x[x['essay_set'] == 5]
x6 = x[x['essay_set'] == 6]
x7 = x[x['essay_set'] == 7]
x8 = x[x['essay_set'] == 8]
scaler = MinMaxScaler()
x1[['domain1_score']] = scaler.fit_transform(x1[['domain1_score']])
x2[['domain1_score']] = scaler.fit_transform(x2[['domain1_score']])
x3[['domain1_score']] = scaler.fit_transform(x3[['domain1_score']])
x4[['domain1_score']] = scaler.fit_transform(x4[['domain1_score']])
x5[['domain1_score']] = scaler.fit_transform(x5[['domain1_score']])
x6[['domain1_score']] = scaler.fit_transform(x6[['domain1_score']])
x7[['domain1_score']] = scaler.fit_transform(x7[['domain1_score']])
x8[['domain1_score']] = scaler.fit_transform(x8[['domain1_score']])
data = pd.concat([x1, x2, x3, x4, x5, x6, x7, x8])
# Tokenize a sentence into words
def sentence_to_wordlist(raw_sentence):
clean_sentence = re.sub("[^a-zA-Z0-9]", " ", raw_sentence)
tokens = nltk.word_tokenize(clean_sentence)
return tokens
# tokenizing an essay into a list of word lists
def tokenize(essay):
stripped_essay = essay.strip()
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
raw_sentences = tokenizer.tokenize(stripped_essay)
tokenized_sentences = []
for raw_sentence in raw_sentences:
if len(raw_sentence) > 0:
tokenized_sentences.append(sentence_to_wordlist(raw_sentence))
return tokenized_sentences
# calculating average word length in an essay
def avg_word_len(essay):
clean_essay = re.sub(r'\W', ' ', essay)
words = nltk.word_tokenize(clean_essay)
return sum(len(word) for word in words) / len(words)
# calculating number of words in an essay
def word_count(essay):
clean_essay = re.sub(r'\W', ' ', essay)
words = nltk.word_tokenize(clean_essay)
return len(words)
# calculating number of characters in an essay
def char_count(essay):
clean_essay = re.sub(r'\s', '', str(essay).lower())
return len(clean_essay)
# calculating number of sentences in an essay
def sent_count(essay):
sentences = nltk.sent_tokenize(essay)
return len(sentences)
# calculating number of punctuations in an essay
def punctuation_count(essay):
clean_essay = re.sub(r'[a-zA-Z0-9]', ' ', essay)
punctuations = nltk.word_tokenize(clean_essay)
return len(punctuations)
# calculating number of lemmas per essay
def count_lemmas(essay):
tokenized_sentences = tokenize(essay)
lemmas = []
wordnet_lemmatizer = WordNetLemmatizer()
for sentence in tokenized_sentences:
tagged_tokens = nltk.pos_tag(sentence)
for token_tuple in tagged_tokens:
pos_tag = token_tuple[1]
if pos_tag.startswith('N'):
pos = wordnet.NOUN
lemmas.append(wordnet_lemmatizer.lemmatize(
token_tuple[0], pos))
elif pos_tag.startswith('J'):
pos = wordnet.ADJ
lemmas.append(wordnet_lemmatizer.lemmatize(
token_tuple[0], pos))
elif pos_tag.startswith('V'):
pos = wordnet.VERB
lemmas.append(wordnet_lemmatizer.lemmatize(
token_tuple[0], pos))
elif pos_tag.startswith('R'):
pos = wordnet.ADV
lemmas.append(wordnet_lemmatizer.lemmatize(
token_tuple[0], pos))
else:
pos = wordnet.NOUN
lemmas.append(wordnet_lemmatizer.lemmatize(
token_tuple[0], pos))
lemma_count = len(set(lemmas))
return lemma_count
# checking number of misspelled words
def count_spell_error(essay):
clean_essay = re.sub(r'\W', ' ', str(essay).lower())
clean_essay = re.sub(r'[0-9]', '', clean_essay)
data = open('C:\\Users\\ig\\Documents\\PY\\big.txt').read()
words_ = re.findall('[a-z]+', data.lower())
word_dict = collections.defaultdict(lambda: 0)
for word in words_:
word_dict[word] += 1
clean_essay = re.sub(r'\W', ' ', str(essay).lower())
clean_essay = re.sub(r'[0-9]', '', clean_essay)
mispell_count = 0
words = clean_essay.split()
for word in words:
if not word in word_dict:
mispell_count += 1
return mispell_count
# parts of speech - calculating number of nouns, adjectives, verbs, adverbs, pronouns and prepositions in an essay
def count_pos(essay):
tokenized_sentences = tokenize(essay)
noun_count = 0
adj_count = 0
verb_count = 0
adv_count = 0
pronoun_count = 0
preposition_count = 0
for sentence in tokenized_sentences:
tagged_tokens = nltk.pos_tag(sentence)
for token_tuple in tagged_tokens:
pos_tag = token_tuple[1]
if pos_tag.startswith('N'):
noun_count += 1
elif pos_tag.startswith('J'):
adj_count += 1
elif pos_tag.startswith('V'):
verb_count += 1
elif pos_tag.startswith('R'):
adv_count += 1
elif pos_tag.startswith('P'):
pronoun_count += 1
elif pos_tag.startswith('I'):
preposition_count += 1
return noun_count, adj_count, verb_count, adv_count, pronoun_count, preposition_count
# extracting essay features
def extract_features(data):
features = data.copy()
features['char_count'] = features['essay'].apply(char_count)
features['word_count'] = features['essay'].apply(word_count)
features['sent_count'] = features['essay'].apply(sent_count)
features['avg_word_len'] = features['essay'].apply(avg_word_len)
features['lemma_count'] = features['essay'].apply(count_lemmas)
features['spell_err_count'] = features['essay'].apply(count_spell_error)
features['punctuation_count'] = features['essay'].apply(punctuation_count)
features['noun_count'], features['adj_count'], features['verb_count'], features['adv_count'], features[
'pronoun_count'], features['preposition_count'] = zip(*features['essay'].map(count_pos))
return features
# extracting features from essay set 1
# features_set = extract_features(data)
# features_set.to_csv("features_set.csv")
# read extracted features
features_set = pd.read_csv('features_set.csv', encoding='latin-1')
# splitting data
X = features_set.iloc[:, 4:].values
y = features_set['domain1_score'].values
linear_regressor = LinearRegression()
linear_regressor.fit(X, y)
# Save model
joblib.dump(linear_regressor,'model.pkl')