-
Notifications
You must be signed in to change notification settings - Fork 1
/
AUTOENCODER.py
185 lines (87 loc) · 3.01 KB
/
AUTOENCODER.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
#!/usr/bin/env python
# coding: utf-8
# In[2]:
from keras.models import Model
from keras.layers import Input, Dense, Embedding, LSTM
from keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
# In[1]:
import pandas as pd
df=pd.read_csv("depression_dataset_reddit_cleaned.csv")
# In[9]:
tokenizer = Tokenizer()
tokenizer.fit_on_texts(df['clean_text'])
sequences = tokenizer.texts_to_sequences(df['clean_text'])
word_index = tokenizer.word_index
# In[10]:
data = pad_sequences(sequences)
# In[11]:
labels = df['is_depression'].values
# In[12]:
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42)
# In[13]:
maxlen = data.shape[1]
embedding_dim = 100
# In[14]:
input_seq = Input(shape=(maxlen,))
embedded_seq = Embedding(len(word_index) + 1, embedding_dim, input_length=maxlen)(input_seq)
encoded = LSTM(128, return_sequences=True)(embedded_seq)
encoded = LSTM(64)(encoded)
decoded = Dense(128, activation='relu')(encoded)
decoded = Dense(maxlen, activation='sigmoid')(decoded)
sequence_autoencoder = Model(input_seq, decoded)
# In[15]:
encoder = Model(input_seq, encoded)
sequence_autoencoder.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# In[16]:
hist=sequence_autoencoder.fit(X_train, X_train,
epochs=10,
batch_size=64,
shuffle=True,
validation_data=(X_test, X_test))
# In[17]:
encoded_text = encoder.predict(data)
# In[18]:
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
# In[19]:
tsne_model = TSNE(n_components=2, random_state=0)
tsne_data = tsne_model.fit_transform(encoded_text)
# In[20]:
tsne_df = pd.DataFrame(data = tsne_data, columns = ['Dim_1', 'Dim_2'])
tsne_df = pd.concat([tsne_df, df['is_depression'].reset_index(drop=True)], axis=1)
# In[21]:
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('Dim_1', fontsize = 15)
ax.set_ylabel('Dim_2', fontsize = 15)
ax.set_title('2D plot of encoded text', fontsize = 20)
targets = [0, 1]
colors = ['r', 'g']
for target, color in zip(targets, colors):
indicesToKeep = tsne_df['is_depression'] == target
ax.scatter(tsne_df.loc[indicesToKeep, 'Dim_1'], tsne_df.loc[indicesToKeep, 'Dim_2'], c = color, s = 50)
ax.legend(targets)
ax.grid()
# In[22]:
from sklearn.cluster import KMeans
# In[23]:
n_clusters = 2
# In[24]:
kmeans = KMeans(n_clusters=n_clusters)
# In[26]:
kmeans.fit(tsne_df)
# In[27]:
cluster_assignments = kmeans.labels_
# In[32]:
from sklearn.metrics import silhouette_score
score = silhouette_score(tsne_df, cluster_assignments)
print('Silhouette Score: ', score)
# In[36]:
plt.scatter(tsne_df.iloc[:, 0], tsne_df.iloc[:, 1], c=cluster_assignments, cmap='viridis')
plt.title("t-SNE visualization with KMeans clustering")
plt.show()
# In[ ]: