generated from fastai/fastpages
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtext-readability.html
executable file
·519 lines (427 loc) · 39.5 KB
/
text-readability.html
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
<!DOCTYPE html>
<html lang="en"><head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-303PJS70LR"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-303PJS70LR');
</script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="twitter:card" content="summary" /><!-- Begin Jekyll SEO tag v2.6.1 -->
<title>Estimating Text Readability with Transformers | Nikita Kozodoi</title>
<link rel="canonical" href="https://kozodoi.me/blog/20211121/text-readability" />
<meta name="generator" content="Jekyll v4.0.1" />
<meta property="og:title" content="Estimating Text Readability with Transformers" />
<meta name="author" content="Nikita Kozodoi" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="ML solution and web app for predicting reading complexity of your texts" />
<meta property="og:description" content="ML solution and web app for predicting reading complexity of your texts" />
<meta property="og:url" content="https://kozodoi.me/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html" />
<meta property="og:site_name" content="Nikita Kozodoi" />
<meta property="og:image" content="https://kozodoi.me/images/posts/readability.png" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2021-11-21T00:00:00-06:00" />
<script type="application/ld+json">
{"datePublished":"2021-11-21T00:00:00-06:00","@type":"BlogPosting","image":"https://kozodoi.me/images/posts/readability.png","dateModified":"2021-11-21T00:00:00-06:00","mainEntityOfPage":{"@type":"WebPage","@id":"https://kozodoi.me/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html"},"url":"https://kozodoi.me/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html","author":{"@type":"Person","name":"Nikita Kozodoi"},"headline":"Estimating Text Readability with Transformers","description":"ML solution and web app for predicting reading complexity of your texts","@context":"https://schema.org"}</script>
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="/assets/css/style.css"><link type="application/atom+xml" rel="alternate" href="https://kozodoi.me/feed.xml" title="Nikita Kozodoi" /><link rel="apple-touch-icon" sizes="76x76" href="https://kozodoi.me/images/favicons/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="https://kozodoi.me/images/favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="https://kozodoi.me/images/favicons/favicon-16x16.png">
<link rel="manifest" href="https://kozodoi.me/images/favicons/site.webmanifest">
<link rel="mask-icon" href="https://kozodoi.me/images/favicons/safari-pinned-tab.svg" color="#5bbad5">
<link rel="shortcut icon" href="https://kozodoi.me/images/favicons/favicon.ico">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-config" content="browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<!-- Begin Jekyll SEO tag v2.6.1 -->
<title>Estimating Text Readability with Transformers | Nikita Kozodoi</title>
<meta name="generator" content="Jekyll v4.0.1" />
<meta property="og:title" content="Estimating Text Readability with Transformers" />
<meta name="author" content="Nikita Kozodoi" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="ML solution and web app for predicting reading complexity of your texts" />
<meta property="og:description" content="ML solution and web app for predicting reading complexity of your texts" />
<meta property="og:url" content="https://kozodoi.me/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html" />
<meta property="og:site_name" content="Nikita Kozodoi" />
<meta property="og:image" content="https://kozodoi.me/images/posts/readability.png" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2021-11-21T00:00:00-06:00" />
<script type="application/ld+json">
{"datePublished":"2021-11-21T00:00:00-06:00","@type":"BlogPosting","image":"https://kozodoi.me/images/posts/readability.png","dateModified":"2021-11-21T00:00:00-06:00","mainEntityOfPage":{"@type":"WebPage","@id":"https://kozodoi.me/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html"},"url":"https://kozodoi.me/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html","author":{"@type":"Person","name":"Nikita Kozodoi"},"headline":"Estimating Text Readability with Transformers","description":"ML solution and web app for predicting reading complexity of your texts","@context":"https://schema.org"}</script>
<!-- End Jekyll SEO tag -->
<link href="https://unpkg.com/@primer/css/dist/primer.css" rel="stylesheet" />
<link rel="stylesheet" href="//use.fontawesome.com/releases/v5.0.7/css/all.css"><link type="application/atom+xml" rel="alternate" href="https://kozodoi.me/feed.xml" title="Nikita Kozodoi" />
<script>
function wrap_img(fn) {
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading") {
var elements = document.querySelectorAll(".post img");
Array.prototype.forEach.call(elements, function(el, i) {
if (el.getAttribute("title") && (el.className != "emoji")) {
const caption = document.createElement('figcaption');
var node = document.createTextNode(el.getAttribute("title"));
caption.appendChild(node);
const wrapper = document.createElement('figure');
wrapper.className = 'image';
el.parentNode.insertBefore(wrapper, el);
el.parentNode.removeChild(el);
wrapper.appendChild(el);
wrapper.appendChild(caption);
}
});
} else { document.addEventListener('DOMContentLoaded', fn); }
}
window.onload = wrap_img;
</script>
<script>
document.addEventListener("DOMContentLoaded", function(){
// add link icon to anchor tags
var elem = document.querySelectorAll(".anchor-link")
elem.forEach(e => (e.innerHTML = '<i class="fas fa-link fa-xs"></i>'));
});
</script>
</head><body><header class="site-header">
<div class="wrapper">
<a class="site-title" rel="author" href="/">Nikita Kozodoi</a><nav class="site-nav">
<input type="checkbox" id="nav-trigger" class="nav-trigger">
<label for="nav-trigger">
<span class="menu-icon">
<svg viewbox="0 0 18 15" width="18px" height="15px">
<path d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.032C17.335,0,18,0.665,18,1.484L18,1.484z M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.032C17.335,6.031,18,6.696,18,7.516L18,7.516z M18,13.516C18,14.335,17.335,15,16.516,15H1.484 C0.665,15,0,14.335,0,13.516l0,0c0-0.82,0.665-1.483,1.484-1.483h15.032C17.335,12.031,18,12.695,18,13.516L18,13.516z"></path>
</svg>
</span>
</label>
<div class="trigger">
<a class="page-link" href="/about/">About</a><a class="page-link" href="/blog/">Blog</a><a class="page-link" href="/portfolio/">Portfolio</a><a class="page-link" href="/kaggle/">Kaggle</a><a class="page-link" href="/papers/">Papers</a><a class="page-link" href="/talks/">Talks</a><a class="page-link" href="/search/">Search</a>
</div>
</nav>
</div>
</header>
<main class="page-content" aria-label="Content">
<div class="wrapper">
<article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting">
<header class="post-header">
<h1 class="post-title p-name" itemprop="name headline">Estimating Text Readability with Transformers</h1>
<p class="page-description">ML solution and web app for predicting reading complexity of your texts</p>
<p class="post-meta post-meta-title"><time class="dt-published" datetime="2021-11-21T00:00:00-06:00" itemprop="datePublished">
Nov 21, 2021
</time>•
<span itemprop="author" itemscope itemtype="http://schema.org/Person">
<span class="p-author h-card" itemprop="name">Nikita Kozodoi</span></span>
• <span class="read-time" title="Estimated read time">
7 min read
</span></p>
<p class="category-tags"><i class="fas fa-tags category-tags-icon"></i>
<a class="category-tags-link" href="/categories/#deep%20learning">deep learning</a>
<a class="category-tags-link" href="/categories/#natural%20language%20processing">natural language processing</a>
<a class="category-tags-link" href="/categories/#web%20app">web app</a>
</p>
<div class="pb-5 d-flex flex-wrap flex-justify-end">
<div class="px-2">
<label class="switch">
<input type="checkbox" href="/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html" id="theme-toggle" checked onclick="modeSwitcher();">
<span class="slider round"></span>
</label>
</div>
<div class="px-2">
<a href="https://github.com/kozodoi/website/tree/master/" role="button" target="_blank">
<img class="notebook-badge-image" src="/assets/badges/github.svg" alt="View on GitHub">
</a>
</div>
<div class="px-2">
<a href="https://colab.research.google.com/github/kozodoi/website/blob/master/" target="_blank">
<img class="notebook-badge-image" src="/assets/badges/colab.svg" alt="Open in Colab">
</a>
</div>
</div>
<img src="/images/portfolio/fig_books.jpg" style="width:100%">
<script type="text/javascript" src="https://platform-api.sharethis.com/js/sharethis.js#property=607a88d1f94d5c00182f2b41&product=inline-share-buttons" async="async"></script>
</header>
<div class="post-content e-content" itemprop="articleBody">
<ul class="section-nav">
<li class="toc-entry toc-h1"><a href="#1.-Overview">1. Overview </a></li>
<li class="toc-entry toc-h1"><a href="#2.-App-demo">2. App demo</a></li>
<li class="toc-entry toc-h1">
<a href="#3.-Implementation">3. Implementation</a>
<ul>
<li class="toc-entry toc-h2"><a href="#3.1.-Modeling-pipeline">3.1. Modeling pipeline</a></li>
<li class="toc-entry toc-h2"><a href="#3.2.-App-implementation">3.2. App implementation</a></li>
</ul>
</li>
<li class="toc-entry toc-h1"><a href="#4.-Closing-words">4. Closing words</a></li>
</ul>
<div class="cell border-box-sizing text_cell rendered">
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="1.-Overview">
<a class="anchor" href="#1.-Overview" aria-hidden="true"><span class="octicon octicon-link"></span></a>1. Overview<a class="anchor-link" href="#1.-Overview"> </a>
</h1>
<p>Estimating text complexity and readability is a crucial task for teachers. Offering students text passages at the right level of challenge is important for facilitating a fast development of reading skills. The existing tools to estimate readability rely on weak proxies and heuristics. Deep learning may help to improve the accuracy of the used text complexity scores.</p>
<p>This blog post overviews <a href="https://kozodoi-text-readability-prediction-web-app-ddrfmw.streamlit.app">an interactive web app</a> that estimates reading complexity of a custom text with deep learning. The app relies on transformer models that are part of my top-9% solution to the <a href="https://www.kaggle.com/c/commonlitreadabilityprize">CommonLit Readability Prize</a> Kaggle competition. The app is built in Python and deployed in Streamlit. The blog post provides a demo of the app and includes a summary of the modeling pipeline and the app implementation. </p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="2.-App-demo">
<a class="anchor" href="#2.-App-demo" aria-hidden="true"><span class="octicon octicon-link"></span></a>2. App demo<a class="anchor-link" href="#2.-App-demo"></a>
</h1>
<p>You can open the app by clicking on <a href="https://kozodoi-text-readability-prediction-web-app-ddrfmw.streamlit.app">this link</a>. Alternatively, just scroll down to see the app embedded in this blog post. If the embedded version does not load, please open the app <a href="https://kozodoi-text-readability-prediction-web-app-ddrfmw.streamlit.app">in a new tab</a>. Feel free to play around with the app by typing or pasting custom texts and estimating their complexity with different models! Scroll further down to read some details on the app and the underlying models.</p>
</div>
</div>
</div>
<iframe src="https://kozodoi-text-readability-prediction-web-app-ddrfmw.streamlit.app/?embed=true" border="0" width="100%" frameborder="1" height="1200" allowtransparency="false">
</iframe>
<div class="cell border-box-sizing text_cell rendered">
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="3.-Implementation">
<a class="anchor" href="#3.-Implementation" aria-hidden="true"><span class="octicon octicon-link"></span></a>3. Implementation<a class="anchor-link" href="#3.-Implementation"></a>
</h1>
<h2 id="3.1.-Modeling-pipeline">
<a class="anchor" href="#3.1.-Modeling-pipeline" aria-hidden="true"><span class="octicon octicon-link"></span></a>3.1. Modeling pipeline<a class="anchor-link" href="#3.1.-Modeling-pipeline"></a>
</h2>
<p>The app is developed in the scope of the <a href="https://www.kaggle.com/c/commonlitreadabilityprize">CommonLit Readability Prize</a> Kaggle competition on text complexity prediction. My solution is an ensemble of eight transformer models, including variants of BERT, RoBERTa and other architectures. All transformers are implemented in <code>PyTorch</code> and feature a custom regression head that uses a concatenated output of multiple hidden layers. </p>
<p>The project uses pre-trained transformer weights published on the <a href="https://huggingface.co/models">HuggingFace model hub</a>. Each model is then fine-tuned on a data set with 2834 text snippets, where readability of each snippet was evaluated by human experts. To avoid overfitting, fine-tuning relies on text augmentations such as sentence order shuffle, backtranslation and injecting target noise in the readability scores.</p>
<p>Each transformer model is fine-tuned using five-fold cross-validation repeated three times with different random splits. <a href="https://github.com/kozodoi/Text_Readability_Prediction">This GitHub repo</a> provides the source code and documentation for the modeling pipeline. The table below summarizes the main architecture and training parameters.</p>
<p><img src="https://i.postimg.cc/JnY0HdWQ/read-params.jpg" alt="Models"></p>
<p>The ensemble of eight transformer models places in the top-9% of the Kaggle competition leaderboard. The web app only includes two lightweight models from a single fold to ensure fast inference on CPU: DistilBERT and DistilRoBERTa.</p>
<h2 id="3.2.-App-implementation">
<a class="anchor" href="#3.2.-App-implementation" aria-hidden="true"><span class="octicon octicon-link"></span></a>3.2. App implementation<a class="anchor-link" href="#3.2.-App-implementation"></a>
</h2>
<p>The app is built in Python using the Streamlit library. Streamlit allows implementing a web app in a single Python code file and deploying the app to the cloud server so that anyone with the Internet access can check it out.</p>
<p>The app code is provided in <code>web_app.py</code> located in the root folder of the project <a href="https://github.com/kozodoi/Text_Readability_Prediction">GitHub repo</a>. The app is hosted on a virtual machine provided by Streamlit, which includes the list of dependencies specified in <code>requirements.txt</code>. It also imports some helper functions used within the modeling pipeline for text preprocessing and model initialization. </p>
<p>The app works by downloading weights of the selected transformer model to the virtual machine after a user selects which model to use for text readability prediction. The weights of each model are made available as <a href="https://github.com/kozodoi/Text_Readability_Prediction/releases/tag/0e96d53">release files</a> on GitHub. After downloading the weights, the app transforms the text entered by a user into the token sequence with the tokenizer that uses text processing settings specified in the model configuration file. Next, the app runs a single forward pass through the initialized transformer network and displays the output prediction.</p>
<p>The snippet below provides the app source code. The code imports relevant Python modules and configures the app page. Next, it provides functionality for entering the custom text and selecting the NLP model. Finally, the code includes the inference function and some further documentation. </p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<details class="description" open="">
<summary class="btn btn-sm" data-open="Hide Code" data-close="Show Code"></summary>
<p></p>
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1">#collapse-show</span>
<span class="c1">##### PREPARATIONS</span>
<span class="c1"># libraries</span>
<span class="kn">import</span> <span class="nn">gc</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">pickle</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="kn">import</span> <span class="nn">requests</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">import</span> <span class="nn">streamlit</span> <span class="k">as</span> <span class="nn">st</span>
<span class="kn">from</span> <span class="nn">PIL</span> <span class="kn">import</span> <span class="n">Image</span>
<span class="c1"># custom libraries</span>
<span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'code'</span><span class="p">)</span>
<span class="kn">from</span> <span class="nn">model</span> <span class="kn">import</span> <span class="n">get_model</span>
<span class="kn">from</span> <span class="nn">tokenizer</span> <span class="kn">import</span> <span class="n">get_tokenizer</span>
<span class="c1"># download with progress bar</span>
<span class="n">mybar</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">def</span> <span class="nf">show_progress</span><span class="p">(</span><span class="n">block_num</span><span class="p">,</span> <span class="n">block_size</span><span class="p">,</span> <span class="n">total_size</span><span class="p">):</span>
<span class="k">global</span> <span class="n">mybar</span>
<span class="k">if</span> <span class="n">mybar</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">mybar</span> <span class="o">=</span> <span class="n">st</span><span class="o">.</span><span class="n">progress</span><span class="p">(</span><span class="mf">0.0</span><span class="p">)</span>
<span class="n">downloaded</span> <span class="o">=</span> <span class="n">block_num</span> <span class="o">*</span> <span class="n">block_size</span> <span class="o">/</span> <span class="n">total_size</span>
<span class="k">if</span> <span class="n">downloaded</span> <span class="o"><=</span> <span class="mf">1.0</span><span class="p">:</span>
<span class="n">mybar</span><span class="o">.</span><span class="n">progress</span><span class="p">(</span><span class="n">downloaded</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">mybar</span><span class="o">.</span><span class="n">progress</span><span class="p">(</span><span class="mf">1.0</span><span class="p">)</span>
<span class="c1"># page config</span>
<span class="n">st</span><span class="o">.</span><span class="n">set_page_config</span><span class="p">(</span><span class="n">page_title</span> <span class="o">=</span> <span class="s2">"Readability prediction"</span><span class="p">,</span>
<span class="n">page_icon</span> <span class="o">=</span> <span class="s2">":books:"</span><span class="p">,</span>
<span class="n">layout</span> <span class="o">=</span> <span class="s2">"centered"</span><span class="p">,</span>
<span class="n">initial_sidebar_state</span> <span class="o">=</span> <span class="s2">"collapsed"</span><span class="p">,</span>
<span class="n">menu_items</span> <span class="o">=</span> <span class="kc">None</span><span class="p">)</span>
<span class="c1">##### HEADER</span>
<span class="c1"># title</span>
<span class="n">st</span><span class="o">.</span><span class="n">title</span><span class="p">(</span><span class="s1">'Text readability prediction'</span><span class="p">)</span>
<span class="c1"># image cover</span>
<span class="n">image</span> <span class="o">=</span> <span class="n">Image</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'https://i.postimg.cc/hv6yfMYz/cover-books.jpg'</span><span class="p">,</span> <span class="n">stream</span> <span class="o">=</span> <span class="kc">True</span><span class="p">)</span><span class="o">.</span><span class="n">raw</span><span class="p">)</span>
<span class="n">st</span><span class="o">.</span><span class="n">image</span><span class="p">(</span><span class="n">image</span><span class="p">)</span>
<span class="c1"># description</span>
<span class="n">st</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">'This app uses deep learning to estimate the reading complexity of a custom text. Enter your text below, and we will run it through one of the two transfomer models and display the result.'</span><span class="p">)</span>
<span class="c1">##### PARAMETERS</span>
<span class="c1"># title</span>
<span class="n">st</span><span class="o">.</span><span class="n">header</span><span class="p">(</span><span class="s1">'How readable is your text?'</span><span class="p">)</span>
<span class="c1"># model selection</span>
<span class="n">model_name</span> <span class="o">=</span> <span class="n">st</span><span class="o">.</span><span class="n">selectbox</span><span class="p">(</span>
<span class="s1">'Which model would you like to use?'</span><span class="p">,</span>
<span class="p">[</span><span class="s1">'DistilBERT'</span><span class="p">,</span> <span class="s1">'DistilRoBERTa'</span><span class="p">])</span>
<span class="c1"># input text</span>
<span class="n">input_text</span> <span class="o">=</span> <span class="n">st</span><span class="o">.</span><span class="n">text_area</span><span class="p">(</span><span class="s1">'Which text would you like to rate?'</span><span class="p">,</span> <span class="s1">'Please enter the text in this field.'</span><span class="p">)</span>
<span class="c1">##### MODELING</span>
<span class="c1"># compute readability</span>
<span class="k">if</span> <span class="n">st</span><span class="o">.</span><span class="n">button</span><span class="p">(</span><span class="s1">'Compute readability'</span><span class="p">):</span>
<span class="c1"># specify paths</span>
<span class="k">if</span> <span class="n">model_name</span> <span class="o">==</span> <span class="s1">'DistilBERT'</span><span class="p">:</span>
<span class="n">folder_path</span> <span class="o">=</span> <span class="s1">'output/v59/'</span>
<span class="n">weight_path</span> <span class="o">=</span> <span class="s1">'https://github.com/kozodoi/Kaggle_Readability/releases/download/0e96d53/weights_v59.pth'</span>
<span class="k">elif</span> <span class="n">model_name</span> <span class="o">==</span> <span class="s1">'DistilRoBERTa'</span><span class="p">:</span>
<span class="n">folder_path</span> <span class="o">=</span> <span class="s1">'output/v47/'</span>
<span class="n">weight_path</span> <span class="o">=</span> <span class="s1">'https://github.com/kozodoi/Kaggle_Readability/releases/download/0e96d53/weights_v47.pth'</span>
<span class="c1"># download model weights</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">folder_path</span> <span class="o">+</span> <span class="s1">'pytorch_model.bin'</span><span class="p">):</span>
<span class="k">with</span> <span class="n">st</span><span class="o">.</span><span class="n">spinner</span><span class="p">(</span><span class="s1">'Downloading model weights. This is done once and can take a minute...'</span><span class="p">):</span>
<span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlretrieve</span><span class="p">(</span><span class="n">weight_path</span><span class="p">,</span> <span class="n">folder_path</span> <span class="o">+</span> <span class="s1">'pytorch_model.bin'</span><span class="p">,</span> <span class="n">show_progress</span><span class="p">)</span>
<span class="c1"># compute predictions</span>
<span class="k">with</span> <span class="n">st</span><span class="o">.</span><span class="n">spinner</span><span class="p">(</span><span class="s1">'Computing prediction...'</span><span class="p">):</span>
<span class="c1"># clear memory</span>
<span class="n">gc</span><span class="o">.</span><span class="n">collect</span><span class="p">()</span>
<span class="c1"># load config</span>
<span class="n">config</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">folder_path</span> <span class="o">+</span> <span class="s1">'configuration.pkl'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">))</span>
<span class="n">config</span><span class="p">[</span><span class="s1">'backbone'</span><span class="p">]</span> <span class="o">=</span> <span class="n">folder_path</span>
<span class="c1"># initialize model</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">get_model</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">name</span> <span class="o">=</span> <span class="n">model_name</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="n">pretrained</span> <span class="o">=</span> <span class="n">folder_path</span> <span class="o">+</span> <span class="s1">'pytorch_model.bin'</span><span class="p">)</span>
<span class="n">model</span><span class="o">.</span><span class="n">eval</span><span class="p">()</span>
<span class="c1"># load tokenizer</span>
<span class="n">tokenizer</span> <span class="o">=</span> <span class="n">get_tokenizer</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
<span class="c1"># tokenize text</span>
<span class="n">text</span> <span class="o">=</span> <span class="n">tokenizer</span><span class="p">(</span><span class="n">text</span> <span class="o">=</span> <span class="n">input_text</span><span class="p">,</span>
<span class="n">truncation</span> <span class="o">=</span> <span class="kc">True</span><span class="p">,</span>
<span class="n">add_special_tokens</span> <span class="o">=</span> <span class="kc">True</span><span class="p">,</span>
<span class="n">max_length</span> <span class="o">=</span> <span class="n">config</span><span class="p">[</span><span class="s1">'max_len'</span><span class="p">],</span>
<span class="n">padding</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span>
<span class="n">return_token_type_ids</span> <span class="o">=</span> <span class="kc">True</span><span class="p">,</span>
<span class="n">return_attention_mask</span> <span class="o">=</span> <span class="kc">True</span><span class="p">,</span>
<span class="n">return_tensors</span> <span class="o">=</span> <span class="s1">'pt'</span><span class="p">)</span>
<span class="n">inputs</span><span class="p">,</span> <span class="n">masks</span><span class="p">,</span> <span class="n">token_type_ids</span> <span class="o">=</span> <span class="n">text</span><span class="p">[</span><span class="s1">'input_ids'</span><span class="p">],</span> <span class="n">text</span><span class="p">[</span><span class="s1">'attention_mask'</span><span class="p">],</span> <span class="n">text</span><span class="p">[</span><span class="s1">'token_type_ids'</span><span class="p">]</span>
<span class="c1"># clear memory</span>
<span class="k">del</span> <span class="n">tokenizer</span><span class="p">,</span> <span class="n">text</span><span class="p">,</span> <span class="n">config</span>
<span class="n">gc</span><span class="o">.</span><span class="n">collect</span><span class="p">()</span>
<span class="c1"># compute prediction</span>
<span class="k">if</span> <span class="n">input_text</span> <span class="o">!=</span> <span class="s1">''</span><span class="p">:</span>
<span class="n">prediction</span> <span class="o">=</span> <span class="n">model</span><span class="p">(</span><span class="n">inputs</span><span class="p">,</span> <span class="n">masks</span><span class="p">,</span> <span class="n">token_type_ids</span><span class="p">)</span>
<span class="n">prediction</span> <span class="o">=</span> <span class="n">prediction</span><span class="p">[</span><span class="s1">'logits'</span><span class="p">]</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span><span class="o">.</span><span class="n">numpy</span><span class="p">()[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span>
<span class="n">prediction</span> <span class="o">=</span> <span class="mi">100</span> <span class="o">*</span> <span class="p">(</span><span class="n">prediction</span> <span class="o">+</span> <span class="mi">4</span><span class="p">)</span> <span class="o">/</span> <span class="mi">6</span> <span class="c1"># scale to [0,100]</span>
<span class="c1"># clear memory</span>
<span class="k">del</span> <span class="n">model</span><span class="p">,</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">masks</span><span class="p">,</span> <span class="n">token_type_ids</span>
<span class="n">gc</span><span class="o">.</span><span class="n">collect</span><span class="p">()</span>
<span class="c1"># print output</span>
<span class="n">st</span><span class="o">.</span><span class="n">metric</span><span class="p">(</span><span class="s1">'Readability score:'</span><span class="p">,</span> <span class="s1">'</span><span class="si">{:.2f}</span><span class="s1">%'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">prediction</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="n">st</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">'**Note:** readability scores are scaled to [0, 100%]. A higher score means that the text is easier to read.'</span><span class="p">)</span>
<span class="n">st</span><span class="o">.</span><span class="n">success</span><span class="p">(</span><span class="s1">'Success! Thanks for scoring your text :)'</span><span class="p">)</span>
<span class="c1">##### DOCUMENTATION</span>
<span class="c1"># header</span>
<span class="n">st</span><span class="o">.</span><span class="n">header</span><span class="p">(</span><span class="s1">'More information'</span><span class="p">)</span>
<span class="c1"># example texts</span>
<span class="k">with</span> <span class="n">st</span><span class="o">.</span><span class="n">expander</span><span class="p">(</span><span class="s1">'Show example texts'</span><span class="p">):</span>
<span class="n">st</span><span class="o">.</span><span class="n">table</span><span class="p">(</span><span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">({</span>
<span class="s1">'Text'</span><span class="p">:</span> <span class="p">[</span><span class="s1">'A dog sits on the floor. A cat sleeps on the sofa.'</span><span class="p">,</span> <span class="s1">'This app does text readability prediction. How cool is that?'</span><span class="p">,</span> <span class="s1">'Training of deep bidirectional transformers for language understanding.'</span><span class="p">],</span>
<span class="s1">'Score'</span><span class="p">:</span> <span class="p">[</span><span class="mf">1.5571</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.0100</span><span class="p">,</span> <span class="o">-</span><span class="mf">2.4025</span><span class="p">],</span>
<span class="p">}))</span>
<span class="c1"># models</span>
<span class="k">with</span> <span class="n">st</span><span class="o">.</span><span class="n">expander</span><span class="p">(</span><span class="s1">'Read about the models'</span><span class="p">):</span>
<span class="n">st</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"Both transformer models are part of my top-9</span><span class="si">% s</span><span class="s2">olution to the CommonLit Readability Kaggle competition. The pre-trained language models are fine-tuned on 2834 text snippets. [Click here](https://github.com/kozodoi/Kaggle_Readability) to see the source code and read more about the training pipeline."</span><span class="p">)</span>
<span class="c1"># metric</span>
<span class="k">with</span> <span class="n">st</span><span class="o">.</span><span class="n">expander</span><span class="p">(</span><span class="s1">'Read about the metric'</span><span class="p">):</span>
<span class="n">st</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"The readability metric is calculated on the basis of a Bradley-Terry analysis of more than 111,000 pairwise comparisons between excerpts. Teachers spanning grades 3-12 (a majority teaching between grades 6-10) served as the raters for these comparisons. More details on the used reading complexity metric are available [here](https://www.kaggle.com/c/commonlitreadabilityprize/discussion/240886)."</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</details>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="4.-Closing-words">
<a class="anchor" href="#4.-Closing-words" aria-hidden="true"><span class="octicon octicon-link"></span></a>4. Closing words<a class="anchor-link" href="#4.-Closing-words"></a>
</h1>
<p>This blog post provided a demo of an interactive web app that uses deep learning to estimate text reading complexity. I hope you found the app interesting and enjoyed playing with it!</p>
<p>If you have any data science projects in your portfolio, I highly encourage you to try developing a similar app yourself. There are many things you could demonstrate, ranging from interactive EDA dashboards to inference calls to custom ML models. Streamlit makes this process very simple and allows hosting the app in the cloud. Happy learning!</p>
</div>
</div>
</div>
</div>
<!--<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
this.page.url = 'https://kozodoi.me/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html';
this.page.identifier = 'https://kozodoi.me/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html';
};
(function() {
var d = document, s = d.createElement('script');
s.src = 'https://kozodoi.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
--><hr style="height:1px;border-width:0;color:rgb(50,50,50);background-color:rgb(50,50,50)">
Liked the post? Share it on social media!
<div class="sharethis-inline-share-buttons" style="margin-top: 3px;"></div>
<br>
You can also buy me a cup of tea to support my work. Thanks!
<div class="tea">
<a href="https://www.buymeacoffee.com/kozodoi"><img src="https://img.buymeacoffee.com/button-api/?text=Buy%20me%20tea%20&emoji=&slug=kozodoi&button_colour=FFDD00&font_colour=000000&font_family=Lato&outline_colour=000000&coffee_colour=ffffff" align="left"></a>
</div>
<a class="u-url" href="/deep%20learning/natural%20language%20processing/web%20app/2021/11/21/text-readability.html" hidden></a>
<script src="/assets/js/mode_switcher.js"></script>
</article>
</div>
</main><footer class="site-footer h-card">
<data class="u-url" href="/"></data>
<div class="wrapper">
<div class="footer-col-wrapper">
<div class="footer-col">
<p></p>
<center>Blog on ML, AI & other acronyms. All opinions are my own.</center>
</div>
<div class="footer-col">
<p style="text-align:center;">© 2020 - 2023 Nikita Kozodoi</p>
</div>
</div>
<div class="social-links">
<ul class="social-media-list">
<li>
<a rel="me" href="https://www.linkedin.com/in/kozodoi/" target="_blank" title="linkedin">
<svg class="svg-icon grey">
<use xlink:href="/assets/minima-social-icons.svg#linkedin"></use>
</svg>
</a>
</li>
<li>
<a rel="me" href="https://github.com/kozodoi" target="_blank" title="github">
<svg class="svg-icon grey">
<use xlink:href="/assets/minima-social-icons.svg#github"></use>
</svg>
</a>
</li>
<li>
<a rel="me" href="https://scholar.google.com/citations?user=58tMuD0AAAAJ&hl=en" target="_blank" title="google_scholar">
<svg class="svg-icon grey">
<use xlink:href="/assets/minima-social-icons.svg#google_scholar"></use>
</svg>
</a>
</li>
<li>
<a rel="me" href="https://twitter.com/n_kozodoi" target="_blank" title="twitter">
<svg class="svg-icon grey">
<use xlink:href="/assets/minima-social-icons.svg#twitter"></use>
</svg>
</a>
</li>
<li>
<a rel="me" href="https://www.instagram.com/n_kozodoi/" target="_blank" title="instagram">
<svg class="svg-icon grey">
<use xlink:href="/assets/minima-social-icons.svg#instagram"></use>
</svg>
</a>
</li>
</ul>
</div>
</div>
</footer>
</body>
</html>