02_evaluation.ipynb 10.4 KB
Newer Older
Philipp Koncar's avatar
Philipp Koncar committed
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import glob\n",
    "from sklearn.metrics import balanced_accuracy_score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configuration\n",
    "\n",
    "*extended_words_dir:* The path to the directory where you saved resulting dictionaries. Please make sure to use a '/' (slash) in the end. For example: path/to/input/.\n",
    "\n",
    "*annotated_positive_words_filename:* The complete path to the **.txt** file containing annotated positive evaluation words.\n",
    "\n",
    "*annotated_negative_words_filename:* The complete path to the **.txt** file containing annotated negative evaluation words.\n",
    "\n",
    "*annotated_neutral_words_filename:* The complete path to the **.txt** file containing annotated neutral evaluation words.\n",
    "\n",
    "*num_words_to_annotate:* The number of words to randomly sample from each class (positive, negative, neutral) for annotation. This is only needed if you do not use the ready-to-use ecaluation words.\n",
    "\n",
    "*annotated_words_dir:* The path to the directory where you want to save randomly extracted evaluation words as well as selected evaluation words. Please make sure to use a '/' (slash) in the end. For example: path/to/output/."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "extended_words_dir = \"result/\"\n",
    "annotated_positive_words_filename = \"ready_to_use/French_positive.txt\"\n",
    "annotated_negative_words_filename = \"ready_to_use/French_negative.txt\"\n",
    "annotated_neutral_words_filename = \"ready_to_use/French_neutral.txt\"\n",
    "num_words_to_annotate = 10\n",
    "annotated_words_dir = \"evaluation_words/\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Directory Setup (Optional)\n",
    "Creates directories according to the configuration if not already created manually."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if not os.path.exists(annotated_words_dir):\n",
    "    os.makedirs(annotated_words_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create annotation lists\n",
    "The following cells are only necessary if you want to create your own evaluation word lists. You can also use the ready-to-use lists and skip to the *Evaluate extended dictionaries* section."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Randomly sample evaluation words"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"{}negative.txt\".format(extended_words_dir), \"r\", encoding=\"utf-8\") as fr:\n",
    "    neg = fr.read().splitlines()\n",
    "with open(\"{}positive.txt\".format(extended_words_dir), \"r\", encoding=\"utf-8\") as fr:\n",
    "    pos = fr.read().splitlines()\n",
    "with open(\"{}neutral.txt\".format(extended_words_dir), \"r\", encoding=\"utf-8\") as fr:\n",
    "    neu = fr.read().splitlines()\n",
    "neg_s = pd.Series(index=neg, dtype=\"object\")\n",
    "pos_s = pd.Series(index=pos, dtype=\"object\")\n",
    "neu_s = pd.Series(index=neu, dtype=\"object\")\n",
    "neg_samples = neg_s.sample(num_words_to_annotate)\n",
    "pos_samples = pos_s.sample(num_words_to_annotate)\n",
    "neu_samples = neu_s.sample(num_words_to_annotate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Save evaluation words to .csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "evaluation_words_s = pd.concat([neg_samples, pos_samples, neu_samples])\n",
    "\n",
    "print(\"enter name of annotator: \")\n",
    "annotator = input()\n",
    "\n",
    "evaluation_words_s.to_csv(\"{}{}_evaluation_words.csv\".format(annotated_words_dir, annotator.lower()), index_label=\"word\", header=[\"sentiment\"])\n",
    "\n",
    "print(\"set up annotation file for: {}\".format(annotator))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Annotate seed words\n",
    "Please open the created annotation files (.csv files) with a spreadsheet program of your choice (e.g., Excel or LibreOffice Calc) and annotate the seed words.\n",
    "Make sure you use either of the following sentiment classes:\n",
    "\n",
    "* positive\n",
    "* negative\n",
    "* neutral\n",
    "\n",
    "Example:\n",
    "\n",
    "| word | sentiment |\n",
    "| --- | --- |\n",
    "| good | positive |\n",
    "| bad | negative |\n",
    "| house | neutral |\n",
    "\n",
    "Once you are finished, make sure to save the file using the **.csv** extension."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Select evaluation words"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "annotation_file_names = glob.glob(\"{}*.csv\".format(annotated_words_dir))\n",
    "print(\"found {} annotations\".format(len(annotation_file_names)))\n",
    "annotations = []\n",
    "for annotation_file_name in annotation_file_names:\n",
    "    annotations.append(pd.read_csv(annotation_file_name, index_col=\"word\"))\n",
    "print(\"loaded {} annotations\".format(len(annotations)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Select evaluation words\n",
    "This is similar to the procedure for seed words and based on a majority vote."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "annotations_df = pd.concat(annotations, axis=1).fillna(\"neutral\")\n",
    "pos_words = []\n",
    "neg_words = []\n",
    "neu_words = []\n",
    "for w, row in annotations_df.mode(axis=1).iterrows():\n",
    "    row = row.dropna()\n",
    "    if len(row) > 1:\n",
    "        continue\n",
    "    if row[0] == \"positive\":\n",
    "        pos_words.append(w)\n",
    "    elif row[0] == \"negative\":\n",
    "        neg_words.append(w)\n",
    "    elif row[0] == \"neutral\":\n",
    "        neu_words.append(w)\n",
    "print(\"number of positive:\", len(pos_words))\n",
    "print(\"number of negative:\", len(neg_words))\n",
    "print(\"number of neutral:\", len(neu_words))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Save selected evaluation words"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"{}positive.txt\".format(annotated_words_dir), mode=\"wt\", encoding=\"utf-8\") as pos_file:\n",
    "    pos_file.write(\"\\n\".join(pos_words))\n",
    "with open(\"{}negative.txt\".format(annotated_words_dir), mode=\"wt\", encoding=\"utf-8\") as neg_file:\n",
    "    neg_file.write(\"\\n\".join(neg_words))\n",
    "with open(\"{}neutral.txt\".format(annotated_words_dir), mode=\"wt\", encoding=\"utf-8\") as neu_file:\n",
    "    neu_file.write(\"\\n\".join(neu_words))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate extended dictionaries"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load extended dictionaries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"{}negative.txt\".format(extended_words_dir), \"r\", encoding=\"utf-8\") as fr:\n",
    "    pred_neg = fr.read().splitlines()\n",
    "with open(\"{}positive.txt\".format(extended_words_dir), \"r\", encoding=\"utf-8\") as fr:\n",
    "    pred_pos = fr.read().splitlines()\n",
    "with open(\"{}neutral.txt\".format(extended_words_dir), \"r\", encoding=\"utf-8\") as fr:\n",
    "    pred_neu = fr.read().splitlines()\n",
    "pred_y_neg_s = pd.Series(\"negative\", index=pred_neg)\n",
    "pred_y_pos_s = pd.Series(\"positive\", index=pred_pos)\n",
    "pred_y_neu_s = pd.Series(\"neutral\", index=pred_neu)\n",
    "pred_y_s = pd.concat([pred_y_neg_s, pred_y_pos_s, pred_y_neu_s])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load annotated evaluation words"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"{}\".format(annotated_negative_words_filename), \"r\", encoding=\"utf-8\") as fr:\n",
    "    true_neg = fr.read().splitlines()\n",
    "with open(\"{}\".format(annotated_positive_words_filename), \"r\", encoding=\"utf-8\") as fr:\n",
    "    true_pos = fr.read().splitlines()\n",
    "with open(\"{}\".format(annotated_neutral_words_filename), \"r\", encoding=\"utf-8\") as fr:\n",
    "    true_neu = fr.read().splitlines()\n",
    "true_y_neg_s = pd.Series(\"negative\", index=true_neg)\n",
    "true_y_pos_s = pd.Series(\"positive\", index=true_pos)\n",
    "true_y_neu_s = pd.Series(\"neutral\", index=true_neu)\n",
    "true_y_s = pd.concat([true_y_neg_s, true_y_pos_s, true_y_neu_s])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Evaluate\n",
    "Compute the balanced accuracy score. For three classes (i.e., positive, negative, neutral), the random baseline is 0.33. If the score is higher than that, you are better than random guessing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pred_y_s = pred_y_s[pred_y_s.index.isin(true_y_s.index)]\n",
    "pred_y_s.sort_index(inplace=True)\n",
    "true_y_s.sort_index(inplace=True)\n",
    "print(\"balanced accuracy score:\", balanced_accuracy_score(true_y_s, pred_y_s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}