-
Notifications
You must be signed in to change notification settings - Fork 3
/
Emotions Classification in Hindi Text.py
268 lines (137 loc) · 5.05 KB
/
Emotions Classification in Hindi Text.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
#!/usr/bin/env python
# coding: utf-8
# ### Importing Important Libraries and Data Set
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import nltk
import os
# In[2]:
text = []
cat = []
# In[3]:
angry=[]
base_path = "C:/Users/Saurav/Desktop/Python Practise/emotions/angry"
for i in range(130):
filename = str(i)+".txt"
path_to_file = os.path.join(base_path, filename)
fd = pd.read_csv(path_to_file , 'r')
angry.append(list(fd.columns))
for item in angry:
text.append(item[0])
cat.append(0)
# In[4]:
happy=[]
base_path = "C:/Users/Saurav/Desktop/Python Practise/emotions/happy"
for i in range(151):
filename = str(i)+".txt"
path_to_file = os.path.join(base_path, filename)
fd = pd.read_csv(path_to_file , 'r')
happy.append(list(fd.columns))
for item in happy:
text.append(item[0])
cat.append(1)
# In[5]:
neutral=[]
base_path = "C:/Users/Saurav/Desktop/Python Practise/emotions/neutral"
for i in range(128):
filename = str(i)+".txt"
path_to_file = os.path.join(base_path, filename)
fd = pd.read_csv(path_to_file , 'r')
neutral.append(list(fd.columns))
for item in neutral:
text.append(item[0])
cat.append(2)
# In[6]:
sad=[]
base_path = "C:/Users/Saurav/Desktop/Python Practise/emotions/sad"
for i in range(104):
filename = str(i)+".txt"
path_to_file = os.path.join(base_path, filename)
fd = pd.read_csv(path_to_file , 'r')
sad.append(list(fd.columns))
for item in sad:
text.append(item[0])
cat.append(3)
# In[7]:
print(len(text))
print(len(cat))
# In[8]:
data = pd.DataFrame(data=[text, cat])
data = data.T
data.rename(columns={0:'Text', 1:'Class'}, inplace=True)
data['Class'] = data['Class'].astype(int)
# In[9]:
data.head()
# In[10]:
data.isnull().sum()
# In[11]:
data.dtypes
# In[12]:
data.head()
# In[13]:
data.groupby('Class').Class.count()
# In[14]:
X = data['Text']
y = data['Class']
# ### Train Test Split
# In[15]:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=48)
# ### Count Vectorizer (We can also use Tf-idf vectorizer)
# In[16]:
stop_words = ['',' ',' ','!','! ','! ','! !','! ! ','! ! !','?','ही','तुमसे','बार','आप','तुम्हारे','तु','रहा','कुछ','कभी','एक','तुम','होता','नहीं','कितनी','पर','तू','हो','है','क्यों','एप','कर','काम','रहे','बातें','लग','आता','ये चैनल्स','करनी','अपना','पैक्स','चीज़','क्या','अरे ये','करा','मैं']
def my_tokenizer(s):
return s.split(' ')
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer(min_df=2, ngram_range=(1, 3), encoding='ISCII',tokenizer=my_tokenizer,stop_words=stop_words).fit(X_train)
# In[17]:
print(len(vect.get_feature_names())) # Printing length of Vocabulary
# In[18]:
vect.get_feature_names() ## Printing Vocabulary
# In[19]:
X_train_vectorized = vect.transform(X_train) # Getting Bag of words representation for all the documents
X_train_vectorized
# In[20]:
X_train_vectorized.shape
# ### Logistic Regression Model (It works nice for sparse Matrix)
# In[21]:
from sklearn.linear_model import LogisticRegression
model1 = LogisticRegression(C=0.05, max_iter=10000, solver='newton-cg', multi_class='multinomial')
model1.fit(X_train_vectorized, y_train)
# In[22]:
from sklearn.metrics import accuracy_score
X_test_transformed = vect.transform(X_test)
y_pred_train = model1.predict(X_train_vectorized)
y_pred_test = model1.predict(X_test_transformed)
print('Train accuracy = ', accuracy_score(y_train, y_pred_train))
print('Test accuracy = ', accuracy_score(y_test, y_pred_test))
# ### Looking into 50 top and bottom learned features
# In[23]:
feature_names = np.array(vect.get_feature_names())
sorted_coef_index = model1.coef_[0].argsort()
print('Largest Coeff')
print(feature_names[sorted_coef_index[:-50:-1]])
print('Smallest Coeff')
print(feature_names[sorted_coef_index[:50]])
# In[24]:
vect.get_stop_words
# ### Training on the whole Data Set and 10 fold Cross Validation Score
# In[25]:
from sklearn.model_selection import cross_val_score
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer(min_df=2, ngram_range=(1, 3), encoding='ISCII',tokenizer=my_tokenizer,stop_words=stop_words).fit(X)
X_vectorized = vect.transform(X) # Getting Bag of words representation for all the documents
X_vectorized
# In[26]:
from sklearn.linear_model import LogisticRegression
model2 = LogisticRegression(C=0.085, max_iter=10000, solver='newton-cg', multi_class='multinomial')
c=cross_val_score(model2, X_vectorized, y, cv=10)
count = 1
for item in c:
print('cross validation score '+str(count)+' =', item)
count=count+1
# In[29]:
print('Final cross validation score = ', np.mean(c))
# In[ ]: