<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tatiana Dembelova on Medium]]></title>
        <description><![CDATA[Stories by Tatiana Dembelova on Medium]]></description>
        <link>https://medium.com/@tanyadembelova?source=rss-769ed6dae52a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oWF0dbJu0tHePYLtrl7T9A.jpeg</url>
            <title>Stories by Tatiana Dembelova on Medium</title>
            <link>https://medium.com/@tanyadembelova?source=rss-769ed6dae52a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:12:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanyadembelova/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[OCR Typo detection]]></title>
            <link>https://medium.com/data-science/ocr-typo-detection-9dd6e396ecac?source=rss-769ed6dae52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dd6e396ecac</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Tatiana Dembelova]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 18:43:36 GMT</pubDate>
            <atom:updated>2021-08-08T14:14:57.637Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h3>Part 1. OCR Typo detection with BERT embeddings, CNN and PyTorch</h3><h4>OCR Typo correction series</h4><h4>Introduction</h4><p>In this series I would like to present a solution for the OCR typo correction task. This problem is not new: unfortunately, many of us encountered bad quality of the OCRed text, especially if the scanned document had unusual font, some scan artefacts or contained unknown words.</p><p>It is possible to address the issue differently: by improving quality of the picture, tweaking the OCR engine or improving the OCRed text. I am going to discuss the latter approach. In particular, this post is about finding the words with typos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wqDxjwACfG27R3QY" /><figcaption>Photo by <a href="https://unsplash.com/@yogidan2012?utm_source=medium&amp;utm_medium=referral">Daniele Levis Pelusi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I was searching something on the OCR topic and came across a paper from 2019, which described the second round of the ICDAR 2019 competition on post-OCR text correction and presented the different methods submitted by the participants. Here is the <a href="https://hal.archives-ouvertes.fr/hal-02304334/document">link</a>.</p><p>What I noticed first in this paper is that the organizers of the competition defined two subtasks of the problem: typo detection and typo correction. I think this decision is very wise, because it allows to closely follow the performance of the methods by considering intermediate results. Besides, it is possible to combine the sub-solutions from different teams.</p><p>The winner of the competitions was a team from South Korea called Clova AI, NAVER/LINE Corp., which performed the best with a maximum error detection of 95% for German language dataset. I tried to find the implementation of their method, but it seems that the team preferred not to publish it. I decided to implement the approach by myself.</p><p>In this post I show a solution for the typo detection task taking the following steps:</p><ul><li>prepare the dataset</li><li>do some data analysis and data wrangling</li><li>implement and train the model</li><li>do inference on some test sentence</li></ul><p>Firstly, importing all the dependencies</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8163052b1d6b011fa134230600b4a878/href">https://medium.com/media/8163052b1d6b011fa134230600b4a878/href</a></iframe><h4>Dataset</h4><p>I used <a href="https://zenodo.org/record/3515403">a dataset from the competition</a>. The corpus accounts for 22M OCRed characters along with the corresponding Gold Standard (GS). Also it is multilingual and represents 10 languages.</p><p>Each of the files contains OCRed text, aligned OCRed text and aligned GS text, each on the new line. The aligned OCRed and GS texts always have the same length and the missing characters are defined by “@” sign. Let’s check out the first 50 characters of each line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/522323578697c6f66095396d0266ead8/href">https://medium.com/media/522323578697c6f66095396d0266ead8/href</a></iframe><p>Output:</p><pre>[&#39;[OCR_toInput] THE HMOS’ COMPLAINT London :—H. SUCH&#39;,<br> &#39;[OCR_aligned] @THE @@HMOS’ COMPLAINT London :—H. S&#39;,<br> &quot;[ GS_aligned]  THE MINERS&#39; COMPLAINT London : H. S&quot;]</pre><p>I used nltk package for sentence tokenization. Actually for all the languages I used the english tokenizer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b6e60b7296d6b10a3676dbf0a4e6d9b/href">https://medium.com/media/0b6e60b7296d6b10a3676dbf0a4e6d9b/href</a></iframe><p>I decided to split the sentences into subtokens only in those places, where the space sign matches in the both aligned OCR and GS sentences. This way, we escape a situation, when the incorrectly split OCRed word splits also the GS word.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7e45ffc81f5a9c794e4f1ada74e4eee/href">https://medium.com/media/c7e45ffc81f5a9c794e4f1ada74e4eee/href</a></iframe><p>In the following cell we create the ground truth by traversing all the files and collecting sentences split into subtokens (variable words). Every subtoken receives the corresponding binary label, where 1 means that it contains typo (variable labels).</p><p>Besides this we also collect aligned OCRed and GS words for the further analysis (variables aligned_words and aligned_gs_words).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/875902665d1fdf020bc847e344e4fe10/href">https://medium.com/media/875902665d1fdf020bc847e344e4fe10/href</a></iframe><h4>Data Wrangling</h4><p>After some manual exploration of the dataset, I realized that some pieces of the text are just too noisy for learning, they contain either too many typos, unrecognized words or false alarms. We need to eliminate them. My idea was that in order to consider a sentence suitable, it is enough to measure edit distance between the OCRed and GS sentences. If it is very large, then the sentence is a bad material to learn.</p><p>First we create a Pandas dataframe to analyze the edit distance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9460348c56d916523c94ab9ca5a6e6a/href">https://medium.com/media/f9460348c56d916523c94ab9ca5a6e6a/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*TUn_MNEe3GzZ_Zu6rS6jqw.png" /></figure><p>Then we apply a function which measures the normalized edit distance between two sentences to the dataframe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1303a942af12c1bf8eb9412f8ea5dcb/href">https://medium.com/media/b1303a942af12c1bf8eb9412f8ea5dcb/href</a></iframe><p>Now we can see that the majority of the sentences have the normalized edit distance less than 0.4:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba1777cd6a9df9465d9e00676c8507a7/href">https://medium.com/media/ba1777cd6a9df9465d9e00676c8507a7/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*q1VN_8Wc2Wr2jiySUrrcqA.png" /></figure><p>Let’s check exactly how many sentences fall into the “bad” and the “good” categories:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7102a8b0b9fec4b17335a753e0670fea/href">https://medium.com/media/7102a8b0b9fec4b17335a753e0670fea/href</a></iframe><p>Output:</p><pre>good sentences: 112329<br>total sentences: 130866<br>good sentences ratio: 0.8583512906331667</pre><p>Let’s see some examples of the good sentences:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c470f01a2ea4fabe8c92f65076c7b242/href">https://medium.com/media/c470f01a2ea4fabe8c92f65076c7b242/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*DqGcn0QP0azlfsBKGYXj4A.png" /></figure><p>And how do the bad sentences look like?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be4331c08e3a4d0ac93a058e19953ed8/href">https://medium.com/media/be4331c08e3a4d0ac93a058e19953ed8/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZOSeWEop24KrJyWkV5_j9Q.png" /></figure><p>I am satisfied with the results. Saving the filtered sentences in pickle format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac31a0950667700d29bdef1edf9751df/href">https://medium.com/media/ac31a0950667700d29bdef1edf9751df/href</a></iframe><p>The same procedure applies to the test dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84bdbfa61a5df336eda8441ea69a70d4/href">https://medium.com/media/84bdbfa61a5df336eda8441ea69a70d4/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*S_LzfgtbXO-qQmKt-HkfYA.png" /></figure><pre>good sentences: 29934<br>total sentences: 35589<br>good sentences ratio: 0.8358481553288938</pre><h4>Training the model</h4><p>I followed the description from the Clova team:</p><p><em>“Our detection model exploits the pretrained multilingual BERT. The BERT output of each sub-token is then plugged into convolutional layers and fully-connected layers to be classified. The model predictions of sub-tokens are merged into token-level predictions. If more than one sub-token of a token is predicted to be erroneous, then the token is erroneous.</em>”</p><p>First let’s load the multilingual training and test datasets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/074aa35805a3b2655a1fa3f9394912c3/href">https://medium.com/media/074aa35805a3b2655a1fa3f9394912c3/href</a></iframe><p>Checking how many words with typos are there in the training dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/517376b677260d8cd46679a3be3c2979/href">https://medium.com/media/517376b677260d8cd46679a3be3c2979/href</a></iframe><p>Output:</p><pre>typo words: 1317340, total: 2468768, typo_rate: 0.5336021853815345</pre><h4>Preparing inputs for the model</h4><p>We have 10 languages in our dataset, therefore the most suitable BERT tokenizer and pretrained model are called bert-base-multilingual-cased.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5122bbc84d6aa4db66b2bf6cc54cf70/href">https://medium.com/media/b5122bbc84d6aa4db66b2bf6cc54cf70/href</a></iframe><p>Output:</p><pre>Downloading: 100% 996k/996k [00:00&lt;00:00, 6.93MB/s]</pre><p>Using the following function we tokenize each word into BERT subtokens and assign to each of them a label from the whole word:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b8dd93593dfc590330cda4da3f22b9/href">https://medium.com/media/96b8dd93593dfc590330cda4da3f22b9/href</a></iframe><p>In order to convert the data into the tensor format, we have to adjust the lengths of the sequences. This is done in the following function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8416ee33d22e5e7ce88afff832caf666/href">https://medium.com/media/8416ee33d22e5e7ce88afff832caf666/href</a></iframe><p>We prepare the suitable input data for the model by doing the following steps:</p><ol><li>Tokenizing the words using Word piece tokenization from BERT</li><li>Converting the tokens into ids</li><li>Aligning the sequence lengths to the maximum sequence length</li><li>Creating attention masks, where 0 means padding</li><li>Converting the token ids, labels and attention masks into tensors</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18b046c11b67916f884913e38e65df1b/href">https://medium.com/media/18b046c11b67916f884913e38e65df1b/href</a></iframe><p>It is convenient to store the tensors for the later reuse by pickling them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b92caf7a4c61fbb4b59aba02142bc7d/href">https://medium.com/media/7b92caf7a4c61fbb4b59aba02142bc7d/href</a></iframe><h4>Model</h4><p>In our model we use pretrained BERT embeddings model bert-base-multilingual-cased. The BERT embeddings are supplied to the convolutional layers with 4 different kernel sizes (2, 3, 4 and 5), each have 32 filters. The convolutional layers are followed by maxpool layers. Both convolutional and maxpool layers have stride=1, which has an effect of information exchange within the n-grams, that is 2-, 3-, 4- and 5-grams. Finally the outputs from the maxpool layers are concatenated and fed to the linear layer to produce the final logits for the binary classification. I think, this technique is equivalent to image segmentation problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YalQ59CDlx83dZPHXTLcFw.png" /><figcaption>Illustration of the model. For simplicity of the scheme, BERT embeddings dimensionality d = 6 and number of output channels (filters) of 1D convolutions out_channels = 7</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed929ca601771e58aad5842229479f71/href">https://medium.com/media/ed929ca601771e58aad5842229479f71/href</a></iframe><p>Activating GPU if available:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63cbd2252b02596a5f47195afb23fd01/href">https://medium.com/media/63cbd2252b02596a5f47195afb23fd01/href</a></iframe><p>Preparing the data loader for training and validation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf494eb3223e8572f44f78539ee3188c/href">https://medium.com/media/cf494eb3223e8572f44f78539ee3188c/href</a></iframe><p>Initializing the model and sending it to the available device:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f269a9efeef541714abb71281343c3e/href">https://medium.com/media/3f269a9efeef541714abb71281343c3e/href</a></iframe><p>Using the corrected optimizer AdamW with weight decay 0.01 only for non-bias parameters. This is because the biases are not influenced by the input data, so it does not make sense to apply regulation to them.</p><p>Learning rate 3e-5 and eps 1e-8 are taken from the <a href="https://arxiv.org/pdf/1810.04805.pdf">original paper on BERT</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1d24c38b9aa04f033cf3aaff20b8440/href">https://medium.com/media/c1d24c38b9aa04f033cf3aaff20b8440/href</a></iframe><p>The BERT authors also suggest to use no more than 4 epochs for training and the linear decay of the learning rate. In our case the model always overfits on the 3-rd epoch. Additionally we are also using clipping in order to prevent gradient explosion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ad40adc4dd964fc0ee0f0878e283ee3/href">https://medium.com/media/8ad40adc4dd964fc0ee0f0878e283ee3/href</a></iframe><p>Output:</p><pre>0%|          | 0/3511 [00:00&lt;?, ?it/s]</pre><pre>Epoch:0</pre><pre>100%|██████████| 3511/3511 [36:05&lt;00:00,  1.62it/s]</pre><pre>Training loss: 0.18836771278758566<br>Training Accuracy: 0.7048872180451128<br>Validation loss: 0.1820502944736399<br>Validation Accuracy: 0.8648648648648649</pre><pre>0%|          | 0/3511 [00:00&lt;?, ?it/s]</pre><pre>Epoch:1</pre><pre>100%|██████████| 3511/3511 [36:16&lt;00:00,  1.61it/s]</pre><pre>Training loss: 0.13889480290636824<br>Training Accuracy: 0.9624217118997912<br>Validation loss: 0.1735410718486095<br>Validation Accuracy: 0.8687258687258688</pre><pre>0%|          | 0/3511 [00:00&lt;?, ?it/s]</pre><pre>Epoch:2</pre><pre>100%|██████████| 3511/3511 [36:17&lt;00:00,  1.61it/s]</pre><pre>Training loss: 0.11354908036724332<br>Training Accuracy: 0.967551622418879<br>Validation loss: 0.17877337249974984<br>Validation Accuracy: 0.8822393822393823</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/053c08c9643c929c8176d533f4fe26db/href">https://medium.com/media/053c08c9643c929c8176d533f4fe26db/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*_eS5Qs-o23VewetM0cMBKA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b061ee82ed62df6ea75c9d7582beed0/href">https://medium.com/media/9b061ee82ed62df6ea75c9d7582beed0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*fBXDskbeTeDFMtrI3jKcxg.png" /></figure><p>As it was expected, the model started overfitting after epoch 1. Interestingly, it gained the validation accuracy more than 85% already after the zeroth epoch, at the same time the training accuracy was much lower — around 71%.</p><h4>Inference</h4><p>Finally, let’s check how good are the model predictions in practice!</p><p>Let’s first load a model with the best validation loss. We also use the saved tokenizer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9160e6b9f668e261fb9bac996e557b4/href">https://medium.com/media/a9160e6b9f668e261fb9bac996e557b4/href</a></iframe><p>Let’s check the following sentence:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ad726472a760832aa68924442d23ed/href">https://medium.com/media/65ad726472a760832aa68924442d23ed/href</a></iframe><p>We perform very similar operations as before in order to get the input tensors. Then we run the model and extract labels from the logits. Finally, we glue the tokenized BERT subtokens together and see the results!</p><p>In the left column are the typo prediction and on the right the word itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06d40fa20abd5f89a9cd2b1f04a52665/href">https://medium.com/media/06d40fa20abd5f89a9cd2b1f04a52665/href</a></iframe><p>Output:</p><pre>0 [CLS] <br>1 Eroxena <br>1 , <br>0 Does <br>0 my <br>0 soul <br>0 make <br>0 an <br>1 impreillon <br>0 upon <br>0 my <br>1 ryes <br>1 ? <br>0 [SEP]</pre><p>It looks like the model has captured the idea of the typo detection — it showed wrong words such as impreillon and ryes.</p><h4>Conclusion</h4><p>In this post I showed how I implemented the typo detection solution from the Clova team in the ICDAR 2019 Competition on Post-OCR Text Correction. Stay tuned to check out the next post of this series where I will show the solution of the subsequent typo correction problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dd6e396ecac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ocr-typo-detection-9dd6e396ecac">OCR Typo detection</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monty Hall problem solution using Bayes theorem]]></title>
            <link>https://medium.com/data-science/monty-hall-problem-solution-using-bayes-theorem-cb1d6fbc0c9e?source=rss-769ed6dae52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb1d6fbc0c9e</guid>
            <category><![CDATA[bayes-theorem]]></category>
            <category><![CDATA[monty-hall-problem]]></category>
            <category><![CDATA[conditional-probability]]></category>
            <dc:creator><![CDATA[Tatiana Dembelova]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 22:30:06 GMT</pubDate>
            <atom:updated>2020-08-21T09:15:51.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Tdm63sKwgHR6Jbl" /><figcaption>Photo by <a href="https://unsplash.com/@moren?utm_source=medium&amp;utm_medium=referral">moren hsu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p>A couple of days ago I decided to refresh my knowledge of probability theory, so the book “All of Statistics” from Larry Wassermann came quite handy at that point. Somewhere in the first chapters of the book the catchy Monty Hall problem got my attention. Actually, I knew already about the problem before and even thought that I understood the solution, but as time goes by the not-so-much attended pieces of knowledge fade, and the solution to Monty Hall problem, unfortunately, did not escape this bad fortune. Luckily, the combination of free time the last weekend and my passion for blogging on Medium lately, which I want to regard as the Pensieve from the Harry Potter saga of my own, gave birth to this post.</p><p>Namely, I want to explain in details the Monty Hall problem solution using the Bayes theorem. Spoiler: it is intended more for understanding the Bayes theorem, rather than grasping the problem solution in simple terms.</p><h3>Problem statement in “All of Statistics”</h3><blockquote>A prize is placed at random between one of three doors. You pick a door. To be concrete you always pick door 1. Now Monty Hall chooses one of the other two doors, opens it and shows you that it is empty. He then gives you the opportunity to keep your door or switch to the other unopened door. Should you stay or switch? Intuition suggests that it doesn’t matter. The correct answer is that you should switch. Prove it. It will help to specify the sample space and the relevant events carefully. Thus write</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*Rq8XJLWehLvGX69JI46Mvg.png" /></figure><blockquote>where ω₁ is where the prize is and ω₂ is the door Monty opens.</blockquote><p>Additionally, I also add event <em>ω₀ </em>to describe which door we picked originally.</p><h3>Bayes theorem</h3><p>Let’s first shortly revise the Bayes theorem concept, the main tool which I am going to use to solve the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*r_q1ZUVfYWCLGcZfUHyvyQ.png" /></figure><p>The probability of event A in the case when event B has happened equals the joint probability of both events divided by the probability of event B.</p><p>Thanks to symmetrical calculation of joint probability, the conditional probability of event A given event B can be unfolded further:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*tr5-iSw9eQ98RmzMmCWr_g.png" /></figure><p>Finally, if we have one more conditional event C, then it propagates as a condition to all constituting probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*_ArmFGC3heIZ97g7h-QAGw.png" /></figure><h3>Solution</h3><p>Now, how exactly are we going to address the question<em> “Should you stay or switch?”</em> in probability terms?</p><p>First of all, let’s note that if Monty Hall would not open any door, this is straightforward. Probability of the prize behind every of the doors after we chose door 1 would be the same:</p><ol><li>P(prize behind door 1|we chose door 1)=1/3</li><li>P(prize behind door 2|we chose door 1)=1/3</li><li>P(prize behind door 3|we chose door 1)=1/3</li></ol><blockquote>Notice that I use conditional probability to show that we chose door 1 earlier, although this fact does not anyhow change the outcomes. I find it nonetheless important, to keep the condition, because it helps later to understand assignment of the probability measure when Monty opens another door.</blockquote><p>But we know that Monty Hall opened another door.</p><p>What does it change? Clearly, on the right side of the “|” sign in the conditional probability, there should be some events which happened earlier. In my eyes, there were two events before we surrendered to the power of the universe, that 1) we chose a door and 2) Monty Hall opened another door. On the left side of the “|” sign should be an event, which interests us. In particular, we are very interested in the event that the prize is behind the door we picked and the event that it is behind another door, which was left closed. Therefore, in my logic, all the concerning conditional probabilities should look something like this:</p><ol><li>P(prize behind door 1|we chose door 1, Monty Hall opened door 2) = ?</li><li>P(prize behind door 2|we chose door 1, Monty Hall opened door 2) <strong>= 0</strong></li><li>P(prize behind door 3|we chose door 1, Monty Hall opened door 2) = ?</li><li>P(prize behind door 1|we chose door 1, Monty Hall opened door 3) = ?</li><li>P(prize behind door 2|we chose door 1, Monty Hall opened door 3) = ?</li><li>P(prize behind door 3|we chose door 1, Monty Hall opened door 3)<strong> = 0</strong></li></ol><p>However, as I mentioned, according to the problem statement, some of the probabilities are already known, because there is a constraint that Monty Hall opens only door which is empty. Therefore, I zeroed out the probabilities 2. and 6., in which the prize is behind the same door as the one which Monty Hall opened.</p><p>Moreover, for us, there is no big difference between door 2 and 3, which of those Monty will open, after we chose door 1. At the end, we just want to know if the success of the original choice is the same as the choice of another door in the same circumstances. So the probability that prize is behind door 1, after we chose door 1 and Monty Hall opened door 2, is exactly the same as probability that prize is behind door 1, after we chose door 1 and Monty Hall opened door 3. That is, probability 1. equals probability 4.. In the same vein, probability 3. equals probability 5.. So I assume that Monty Hall opened door 2, then we are left only with two probabilities:</p><ol><li>P(prize behind door 1|we chose door 1, Monty Hall opened door 2) = ?</li><li>P(prize behind door 3|we chose door 1, Monty Hall opened door 2) = ?</li></ol><p>And in the mathematical terms it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*6qe2rOSrW9w_kIwyo3oA8Q.png" /></figure><p>Let’s discuss each of the probabilities in order.</p><h4>1. Probability that prize is behind our door (door 1) after seeing that door 2 is empty</h4><p>As I mentioned earlier, I decided to introduce the event of our choice of door 1, although it is then propagated as a condition to all the considered probabilities. Yet I think that this way we can see the fuller picture of the previous events.</p><p>Therefore, according to the Bayes theorem, the probability unfolds as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*fghz7P-7prtOJofQpT5LfQ.png" /></figure><p>where</p><ul><li>probability that Monty Hall opens door 2, given that we picked door 1 and the prize is also behind door 1, equals 1/2. This is because for him it does not matter if he opens door 2 or door 3, since we blocked door 1 already and the prize is also behind door 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*w7jbbW8y5gmN4Irs4IVJ_w.png" /></figure><ul><li>probability that Monty Hall opens door 2, given that we picked door 1, equals 1/2. It is somewhat similar to the previous probability but without knowing where the prize is. We block door 1, therefore he opens door 2 (or door 3) with 50% chance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*rhLTEXQi7n3U_HLcl380Sw.png" /></figure><ul><li>probability that prize is behind door 1, given that we also picked door 1, equals 1/3. That’s logical, because our choice of the door can not influence on appearance of the prize behind this door (or any of the doors). This is an independent event.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*rZWBXWSPr1xz7Z2PZ8IOyA.png" /></figure><p>Now let’s compute the probability in question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*iwmNWiH9463pCMb9nStSJg.png" /></figure><h4>2. Probability that prize is behind door 3 after seeing that door 2 is empty</h4><p>Formula for this probability looks like following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*2RpSDMF4Z5zWvbarJI4Ubg.png" /></figure><p>where</p><ul><li>probability that Monty Hall opens door 2, given that we picked door 1 and the prize is behind door 3, <strong>ATTENTION</strong>, equals 1! This is because he does not have another choice: we blocked door 1 and he can not open the door with the prize.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*clybuPLU6IYEcsdBVSs3HA.png" /></figure><ul><li>probability that Monty Hall opens door 2, given that we picked door 1, equals 1/2. It is somewhat similar to the previous probability but without knowing where the prize is. And not knowing where the prize is crucial — for him there is no difference between door 2 and door 3.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*KYAYNMb_6fBoWqfJ0cdGoA.png" /></figure><ul><li>probability that prize is behind door 3, given that we picked door 1, equals 1/3. As mentioned earlier, our choice of door 1 is independent event for the prize being behind door 3.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*qv27dHCEx0ppxElppd5lCA.png" /></figure><p>Let’s finally calculate what is the final probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*ZG4Y0FPOmfoNgR0UFKJ0XA.png" /></figure><h4>Conclusion</h4><p>We see that indeed it is better to change to door 3, because in this case, we take advantage of Monty Hall’s knowledge where actually the prize is.</p><p>Actually, I don’t know about you, but even after solving the problem, it still seems a bit mysterious. To me, the opportunity to change the choice of door looks like a portal which transports you to the better parallel universe where you have a higher chance to win.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb1d6fbc0c9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/monty-hall-problem-solution-using-bayes-theorem-cb1d6fbc0c9e">Monty Hall problem solution using Bayes theorem</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to generative and discriminative models]]></title>
            <link>https://medium.com/data-science/introduction-to-generative-and-discriminative-models-9c9ef152b9af?source=rss-769ed6dae52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c9ef152b9af</guid>
            <category><![CDATA[discriminative-model]]></category>
            <category><![CDATA[generative-model]]></category>
            <dc:creator><![CDATA[Tatiana Dembelova]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 21:56:16 GMT</pubDate>
            <atom:updated>2020-08-20T23:37:27.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LF7MUP7jrGqPAzVZ" /><figcaption>Photo by <a href="https://unsplash.com/@hellocolor?utm_source=medium&amp;utm_medium=referral">Pawel Nolbert</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Intro</strong></p><p>Recently I gave a presentation at work, where I explained how I solved some problem using <a href="https://en.wikipedia.org/wiki/Conditional_random_field">Conditional Random Fields (CRF)</a>. And, since CRF was not so much known to my colleagues, I had a couple of slides devoted to the theory behind this algorithm. As I prepared the theory slides, I felt a duty to compare CRF with a conceptually similar algorithm, <a href="https://en.wikipedia.org/wiki/Hidden_Markov_model">Hidden Markov Model (HMM)</a>. CRF is known to be a discriminative model and HMM is a generative model. I had to refresh my knowledge about this categorisation of supervised machine learning methods, especially generative models. Now I would like to share my understanding of the difference between generative and discriminative models in simple terms.</p><p><strong><em>Generative models</em></strong> are a wide class of machine learning algorithms which make predictions by modelling joint distribution <em>P(y, x)</em>.</p><p><strong><em>Discriminative models</em></strong> are a class of supervised machine learning models which make predictions by estimating conditional probability <em>P(y|x).</em></p><p>In order to use a generative model, more unknowns should be solved: one has to estimate probability of each class and probability of observation given class. These probabilities are used to compute joint probability, and finally, joint probability can be used as a substitute for conditional probability to make predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*_nXM1QK_jEGjH_-imJDQ5A.png" /><figcaption>Generative model has more steps than discriminative model in order to estimate conditional probability P(y|x)</figcaption></figure><p>The discriminative model takes a shorter way: it simply estimates conditional probability directly.</p><p>There are many pros and cons to each of the models. I just note that generative model can be used to generate new samples, but it requires more data. Discriminative model often superior than generative model, given the same amount of data, but it does not know about dependencies between features, because it is irrelevant for prediction. Therefore discriminative model can not generate new samples.</p><p>Now let’s take a closer look at the concept of generative models.</p><p><strong>Generative model</strong></p><blockquote><em>As I showed earlier, to make predictions, conditional distribution </em>P(y|x) <em>is enough. But since </em>P(y|x) = P(y, x) / P(x)<em>, where </em>P(x)<em> is constant for the given </em>x <em>and</em> <em>all possible </em>y<em>, it is valid to use joint distribution </em>P(y, x)<em> to make predictions.</em></blockquote><p>By modelling joint distribution <em>P(y, x)</em> is meant that for each pair (<em>yᵢ, xᵢ) </em>a probability<em> P(yi, xi) </em>is known (modelled). At the beginning it was a bit difficult for me to understand how it is even possible — the range of possible values of <strong><em>X</em></strong> might be enormous, so it’s gonna be unrealistic to suggest probabilities for each <em>xi</em>, leave alone pair (<em>yi</em>, <em>xi). </em>How is it supposed to be done?</p><p><strong>First. </strong>Bayes theorem! It breaks computation of joint probability <em>P(y,x)</em> into computation of two other types of probabilities: probability of class, <em>P(y),</em> and probability of observation given class, <em>P(x|y).</em></p><p><em>P(y, x) = P(y) * P(x|y)</em></p><p>What benefits does it give? This way it is at least easier to figure out probability<em> P(y)</em>, because it can be estimated from the dataset by computing class frequencies. <em>P(x|y)</em> is trickier, because usually <em>x</em> is not just one feature, but a set of features: <em>x = xi, …, xn</em>, which might have dependencies between each other<em>.</em></p><p><em>P(x|y) = П P(xi|y, x1, xi-1, xi+1, xn)</em></p><p>Often the dependencies between the features are not known, especially when they appear in complex constellations (<em>y, x1, xi-1, xi+1, xn)</em>.</p><p>So what should be done to estimate <em>P(x|y)</em>? For this, there is the following trick:</p><p><strong>Second.</strong> Make wild assumptions! Or just some assumptions which make estimation of <em>P(x|y)</em> tractable. Naive Bayes classifier can serve as a perfect example of a generative model with such assumption, which makes computation of <em>P(x|y) </em>easier. Namely, it has independence assumption between the features <em>xi, …, xn.</em></p><p><em>P(x|y) = П P(xi|y)</em></p><p>With this relaxation, estimation of <em>P(x|y)</em> is tractable, because every <em>P(xi|y)</em> can be estimated either by finding frequencies of discrete feature <em>xi</em> independently from other features or using Gaussian distribution, if feature <em>xi </em>is continuous.</p><p><strong>Conclusion</strong></p><p>So now you can see that in order to use generative models one should be prepared to estimate two types of probabilities<em> P(y) </em>and<em> P(x|y). </em>At the same time, discriminative models estimate conditional probability <em>P(y|x)</em> directly, which often is more efficient because one does not estimate dependencies between features, as these relationships don’t necessarily contribute to the prediction of the target variable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c9ef152b9af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/introduction-to-generative-and-discriminative-models-9c9ef152b9af">Introduction to generative and discriminative models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>