<?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 Shaya Farahmand on Medium]]></title>
        <description><![CDATA[Stories by Shaya Farahmand on Medium]]></description>
        <link>https://medium.com/@shayaf?source=rss-2c298d07ebb1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rbYKuGXhGfKglao3rHJ2cQ.png</url>
            <title>Stories by Shaya Farahmand on Medium</title>
            <link>https://medium.com/@shayaf?source=rss-2c298d07ebb1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:16:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shayaf/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[The Fight Against Fake News with Deep Learning]]></title>
            <link>https://medium.com/data-science/the-fight-against-fake-news-with-deep-learning-6c41dd9eaae4?source=rss-2c298d07ebb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c41dd9eaae4</guid>
            <category><![CDATA[fake-news]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Shaya Farahmand]]></dc:creator>
            <pubDate>Wed, 23 Feb 2022 04:50:23 GMT</pubDate>
            <atom:updated>2022-02-23T04:50:23.089Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fake news detection with LSTMs and BERT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b55KgVH1x8nr-MLm0IMrVA.jpeg" /><figcaption>Photo by Markus Winkler on <a href="https://www.pexels.com/photo/close-up-shot-of-a-typewriter-4160060/">Pexels</a></figcaption></figure><p>Let’s play a game. I will give you two titles, and you will tell me which one is fake news. Ready? Here we go:</p><blockquote>“Nancy Pelosi diverting social security money for the impeachment inquiry”</blockquote><blockquote>“FEMA arrives in tornado-stricken Kentucky — with vaccinations”</blockquote><p>Well…it turns out that <strong><em>both </em></strong>headlines were examples of fake news.</p><p>The harsh reality is that misinformation and disinformation is rampant on the internet. According to a 2019 poll conducted by Ipsos Public Affairs for Canada’s Centre for International Governance Innovation, <strong>90% of Canadians have fallen for fake news.</strong></p><p>This got me thinking, would it be possible to create a model that can detect whether the title of a given article is fake news? Well, it turns out that it is! In this article, I will share with you my experiences in building this text classification model with LSTMs and BERT.</p><p>You can find the code I use at my Github repository <a href="https://github.com/shayaf84/Fake-News-Detection">here</a></p><h3>Finding a Dataset</h3><p>We will use the University of Victoria’s ISOT Fake News Dataset. It contains more than 12,600 real news articles from Reuters.com and more than 12,600 fake news articles that were flagged by Politifact (a fact-checking organization in the United States). The dataset contains articles relating to a variety of topics, though mostly political news and world news. Check it out at this <a href="https://www.uvic.ca/ecs/ece/isot/datasets/fake-news/index.php">link</a>.</p><h3>Exploratory Data Analysis</h3><p>First, let’s perform some analyze our data so we can understand possible trends within our data. Because the real news and fake news files are separate, we will need to label and concatenate the two data frames. For the real news dataset, we loop the number of rows, and add a 0 to a NumPy array (denoting class). This array will be added to the real news dataframe. For the fake news dataset, we repeat this procedure, but add a 1 to the NumPy array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34adf02fe1d0c78dbdec68813308de70/href">https://medium.com/media/34adf02fe1d0c78dbdec68813308de70/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*h05zWQCQprb2xu9dJrUliA.png" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*yiekGH8KgAM2NO6_x8pg3w.png" /><figcaption>Image by Author</figcaption></figure><p>Because we have 21, 417 samples of real news, and 23, 481 samples of fake news, there is an approximately 48:52 real:fake news ratio. This means that our dataset is relatively balanced. For the purposes of our project, we only want the title and class columns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d08ab1d79890daeb8877c0ce89322495/href">https://medium.com/media/d08ab1d79890daeb8877c0ce89322495/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*bNMFi118yJmT6zi0tlkOJQ.png" /><figcaption>Final dataframe | Image by Author</figcaption></figure><p>Great! Now that we cleaned our dataset, we can analyze trends we found within it. To get a gauge of our dataset’s size, we will analyze the mean, minimum, and maximum character length of our titles. We will plot this frequency with a histogram.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/976c6527f56832c88aec473a4a5ef096/href">https://medium.com/media/976c6527f56832c88aec473a4a5ef096/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*TjgOpU_uRoA4Ktl25nzq-w.png" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*R4E6LS1ggrqbj_uJLlEfwQ.png" /><figcaption>Image by Author</figcaption></figure><p>We see that that the numbers of characters in each entry ranges from 8–286. There is a high concentration of samples with a length of 50–100. This can be further seen with the mean length in the dataset being approximately 80.</p><h3>Preprocessing our Data</h3><p>We will conduct some initial preprocessing using python’s string library. They involve:</p><ul><li><strong>Lowercasing all characters</strong></li><li><strong>Removing punctuation</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4323799811928468e4b95cca60fd420/href">https://medium.com/media/c4323799811928468e4b95cca60fd420/href</a></iframe><p>Afterwards, we will need to use the <strong>NLTK library</strong> to conduct further preprocessing on our dataset. It involves:</p><ul><li><strong>Tokenization: </strong>Splitting a text into a smaller unit called a token (each individual word will be an index in an array)</li><li><strong>Lemmatization: </strong>Removing the word’s inflectional endings. For example, the word “children” will be lemmatized to “child”</li><li><strong>Removal of Stop words: </strong>Commonly used words such as “the” or “for” will be removed, as they take up space in our dataset.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7df9d65fd090ed6aa6a980632276f65/href">https://medium.com/media/c7df9d65fd090ed6aa6a980632276f65/href</a></iframe><p>This means that our processed data frame will appear like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*APgHRs7GF9FGCKy86_uCjw.png" /><figcaption>Image by Author</figcaption></figure><p>We will construct two models on this data to classify the text:</p><ul><li>An<strong> LSTM model </strong>(We will use Tensorflow’s wiki-words-250 embeddings)</li><li>A <strong>BERT</strong> model.</li></ul><h3>Creating an LSTM Model</h3><p>First, we will split our dataset to an 80:20 train:test ratio.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dd2f388f723bdb12fcf530d496514a7/href">https://medium.com/media/4dd2f388f723bdb12fcf530d496514a7/href</a></iframe><p>If we want our model to make predictions based on text data, we will need to convert it to vector format, where it can be processed by our computers.</p><p>Tensorflow’s wiki-words-250 uses a Word2Vec Skip-Gram architecture. Skip-gram is trained by predicting the context based on an input word.</p><p>For example, if we have the sentence:</p><blockquote>I am going on a <strong>vacation</strong> with an airplane</blockquote><p>We will pass in the word “vacation” as input, and specify a window size of 1. The window size indicates the words before and after the target word to predict. In this case, they are the words are “go” and “airplane” (excluding stopwords, and “go” is the lemmatized form of “going”).</p><p>We one hot-encode our word so our input vector is the size 1 x V where V is the size of our vocabulary. The representation will be multiplied by a weight matrix with V rows (one for each word in our vocabulary) and E columns, where E is a hyperparameter denoting the size of each embedding. Because the input vector is one-hot encoded, all values are 0, except for one (representing the word we are inputting). Hence, when multiplied by the weight matrix, the output is a 1xE vector which denotes the embedding for that word.</p><p>The 1xE vector will be passed into the output layer, consisting of a softmax regression classifier. It consists of V neurons (corresponding to the vocabulary’s one-hot encoding), with an output between 0 and 1 for each word, denoting a probability of that word being in the window size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HMZ7EArwJhod3vLusMDeQ.png" /><figcaption>Word2Vec Skipgram Representation | Image by author</figcaption></figure><p>Tensorflow’s wiki-words-250 consists of word embeddings with a size E of 250. It can be applied to our model by looping through every word and calculating the embedding for each. We will need to apply the pad_sequences function to account for samples of different lengths.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faea07c48e3faff8d5dccc101580cfbc/href">https://medium.com/media/faea07c48e3faff8d5dccc101580cfbc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*HC__GRjYrYstbhhFjcmw2A.png" /><figcaption>Image by Author</figcaption></figure><p>Hence, there are 35,918 samples in the training data, the maximum length is 34 words (the ones with less are padded), and each word has 250 features.</p><p>We can apply the same procedure to our testing data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9a30c6ff5a03ce19bae91b1937bc792/href">https://medium.com/media/b9a30c6ff5a03ce19bae91b1937bc792/href</a></iframe><p>Now, let’s construct our model. It will consist of:</p><ul><li><strong>1 LSTM layer </strong>with 50 units</li><li><strong>2 Dense layers</strong> (one with 20 neurons, the second with 5) with a ReLU activation function</li><li><strong>1 Dense output layer</strong> with a sigmoid activation function</li></ul><p>We will use the Adam optimizer, a binary crossentropy loss, and a performance metric of accuracy. The model will be trained over 10 epochs. Feel free to further adjust these hyperparameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f4ecc73c91fb5b22c032098969e2e41/href">https://medium.com/media/2f4ecc73c91fb5b22c032098969e2e41/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNT3VkwpznsT6LUQz6mjSw.png" /><figcaption>Image by Author</figcaption></figure><p>As seen above, our model has a maximum accuracy of 91.5% on test data.</p><h3>Introducing BERT</h3><p>If I were to ask you for the word in the English language with the most definitions, what would you say?</p><p>According to the Second Edition of the Oxford English Dictionary, that word is “set”.</p><p>If you think of it, we can generate many different sentences using that word in different contexts. For example:</p><blockquote>My pencils are part of a <strong>set </strong>of stationary supplies<br><br>My teammate <strong>set</strong> the volleyball to me</blockquote><blockquote>I <strong>set</strong> the table for dinner</blockquote><p>The problem with Word2Vec is that it generates the same embedding regardless of the way in which the word is used. To combat against this, we can use BERT, which can <strong>generate contextualized embeddings</strong>.</p><p>BERT stands for “Bidirectional Encoder Representations from Transformers”. It uses a transformer model, taking advantage of attention mechanisms to generate contextualized embeddings.</p><p>A transformer model uses an encoder-decoder architecture. The encoder layer generates a continuous representation which consists of the information learned from the input. The decoder layer creates an output, with the previous input being passed into the model. <strong>BERT only uses an encoder </strong>as its goal is to generate a vector representation to gain information from the text.</p><h3>Pre-training and Fine-tuning BERT</h3><p>Two methods are employed to train BERT. The first is called masked language modelling. Before passing sequences, <strong>15% of the words are replaced with a [MASK] token</strong>. The model will predict the masked words, using the context provided by the unmasked ones. This is done by</p><ul><li><strong>Applying a classification layer</strong> on the encoder output, consisting of an embedding matrix. Hence, it will be the same size as that of the vocabulary.</li><li><strong>Calculating the probability</strong> of the word with the softmax function.</li></ul><p>The second method is next sentence prediction. The model will receive 2 sentences as input, and <strong>predict a binary value of whether the second sentence follows the first</strong>. While training, 50% of inputs are pairs, while the other 50% are random sentences from the corpus. To differentiate between the two sentences,</p><ul><li>a <strong>[CLS] token</strong> is added at the beginning of the first sentence, and an <strong>[SEP] token </strong>is added at the end of each.</li><li>each token (word) has a <strong>positional embedding</strong> to discern information from the position within the text. This is important as there is no recurrence in a transformer model, so there is no inherent understanding of the word’s position</li><li>a <strong>sentence embedding</strong> is added to each token (further differentiating between the sentences).</li></ul><p>To perform the classification for Next Sentence Prediction, the <strong>output of the [CLS] embedding</strong>, which denotes the “aggregate sequence representation for sentence classification,” is<strong> passed through a classification layer with softmax</strong> to return the probability of the two sentences being sequential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8Qv29PxM8NXjjToSr0ibg.png" /><figcaption>Masked Language Modelling and Next Sentence Prediction | Image by Author</figcaption></figure><p>Because our task is classification, to fine-tune BERT, one needs to simply add classification layers over BERT’s output of the [CLS] token.</p><h3>Implementing BERT</h3><p>We will use Tensorflow-hub’s BERT preprocesser and encoder. Do not pass the text through our framework described earlier (which removes capitalization, applies lemmatization, etc). This has been abstracted with the BERT preprocesser.</p><p>Our dataframe should look like this initially:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*bNMFi118yJmT6zi0tlkOJQ.png" /><figcaption>Final dataframe | Image by Author</figcaption></figure><p>Afterwards, we can split our model into training and testing data with an 80:20 train:test ratio.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dd2f388f723bdb12fcf530d496514a7/href">https://medium.com/media/4dd2f388f723bdb12fcf530d496514a7/href</a></iframe><p>We can now import the BERT pre-processer and encoder with Tensorflow-hub</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef90c43c1237dbf06531305741f838e9/href">https://medium.com/media/ef90c43c1237dbf06531305741f838e9/href</a></iframe><p>Now, we can develop our neural network. It must be a functional model, where the output of a previous layer must be an argument to the next layer. The model consists of:</p><ul><li><strong>1 Input layer: </strong>This will represent the sentence that will be passed into the model).</li><li><strong>The bert_preprocess layer: </strong>Here we pass in our input to preprocess the text.</li><li><strong>The bert_encoder layer: </strong>Here we pass the preprocessed tokens into the BERT encoder.</li><li><strong>1 Dropout layer </strong>with a rate of 0.2. The pooled_output of the BERT encoder is passed into it (more on this below)</li><li><strong>2 Dense layers </strong>with 10 and 1 neurons respectively. The first one will use a ReLU activation function, and the second will use sigmoid.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19b0cf470c47a43314b3f7f8aa510734/href">https://medium.com/media/19b0cf470c47a43314b3f7f8aa510734/href</a></iframe><p>You can see that the “pooled_output” will be passed into the dropout layer. This value denotes the overall sequence representation of the text. As mentioned earlier, it is the representation of the [CLS] token outputs.</p><p>We will use the Adam optimizer, a binary_crossentropy loss, and a performance metric of accuracy. The model will be trained over 5 epochs. Feel free to further adjust these hyperparameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b35f36abcb3ad8971d1c185bc9f613d/href">https://medium.com/media/6b35f36abcb3ad8971d1c185bc9f613d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_lu8KUu-up30n2OywS8Iw.png" /><figcaption>Image by Author</figcaption></figure><p>You can see above that on the testing data (derived from the model.evaluate() method), the model reached an accuracy of 91.14%.</p><h3>Creating a Web Application</h3><p>We can create a web application using HTML and Flask, allowing users to interact with the models that we made.</p><p>The link to the model’s front end can be found <a href="https://github.com/shayaf84/Fake-News-Detection/blob/master/templates/index.html">here</a> and the link to the back end can be found <a href="https://github.com/shayaf84/Fake-News-Detection/blob/master/app.py">here</a>. You can host this model locally through Google Colab and ngrok.</p><p>The interface will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jKBBn_4MYn0fvkb9BLMzQ.png" /><figcaption>Image by Author</figcaption></figure><p>Three models are available to the user.</p><ul><li>A <strong>baseline dense neural network </strong>using Gensim Doc2Vec</li><li>The <strong>LSTM model </strong>using wiki-words-250 embeddings (with the Word2Vec architecture)</li><li>The <strong>BERT model</strong></li></ul><p>The user can enter a title and choose the model. The app will return a classification and a probability, where if the probability is above 50%, the model predicts that the title is from a fake news source. Consequently, if the probability is below 50%, the model will predict that the title is from a real news source.</p><p>I hope that this article demonstrated how we can harness techniques in NLP to classify Fake News from Real News. You might ask, “What can we do next?” Well, our process is by no means finished here. To further improve our model, we can:</p><ul><li>Train our models on more data</li><li>Adjust our models’ hyperparameters</li><li>Deploy the web application that we created</li></ul><p>Hope you enjoyed reading the article! Feel free to add me on <a href="https://www.linkedin.com/in/shaya-farahmand-168307220/">Linkedin</a> and stay tuned for more content!</p><h4>Bibliography</h4><p>[1] <a href="https://www.tensorflow.org/text/tutorials/classify_text_with_bert">Classify Text with BERT</a> (2022), Tensorflow</p><p>[2] E. Thompson. <a href="https://www.cbc.ca/news/politics/fake-news-facebook-twitter-poll-1.5169916">Poll finds 90% of Canadians have fallen for fake news</a> (2019), CBC</p><p>[3] H. Ahmed, I. Traore, and S. Saad. Detecting opinion spams and fake news using text classification (2018), Journal of Security and Privacy, Volume 1, Issue 1, Wiley,</p><p>[4] H. Ahmed, I. Traore, and S. Saad. Detection of Online Fake News Using N-Gram Analysis and Machine Learning Techniques, In: Traore I., Woungang I., Awad A. (eds) Intelligent, Secure, and Dependable Systems in Distributed and Cloud Environments. ISDDC 2017. Lecture Notes in Computer Science, vol 10618. Springer, Cham (pp. 127- 138).</p><p>[5] J. Devlin, M. Chan, K. Lee, and K. Toutanova. <a href="https://arxiv.org/abs/1810.04805">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a> (2019), arXiv</p><p>[6] R. Horev, <a href="https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270">BERT Explained: State of the art language model for NLP</a> (2018), Towards Data Science</p><p>[7] R. Kulshrestha, <a href="https://towardsdatascience.com/nlp-101-word2vec-skip-gram-and-cbow-93512ee24314#:~:text=In%20the%20CBOW%20model%2C%20the,used%20to%20predict%20the%20context%20.">NLP 101: Word2Vec- Skip-gram and CBOW</a> (2019), Towards Data Science</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c41dd9eaae4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-fight-against-fake-news-with-deep-learning-6c41dd9eaae4">The Fight Against Fake News with Deep Learning</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[Opening the Black Box: An Explanation of Explainable AI]]></title>
            <link>https://medium.com/data-science/opening-the-black-box-an-explanation-of-explainable-ai-7024d8b1f6b3?source=rss-2c298d07ebb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7024d8b1f6b3</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[editors-pick]]></category>
            <dc:creator><![CDATA[Shaya Farahmand]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 06:50:13 GMT</pubDate>
            <atom:updated>2021-11-23T06:50:13.479Z</atom:updated>
            <content:encoded><![CDATA[<h4>Can we explain the predictions our model makes? Let’s analyze why our model predicted an image to be part of a certain class</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*cUqQPa1rabwaJ_68fryP2A.jpeg" /><figcaption>Photo by TheDigitalArtist on <a href="https://pixabay.com/illustrations/why-question-blackboard-school-4129050/">Pixabay</a></figcaption></figure><p>Imagine that you went to a hospital feeling unwell and are in need of medical tests. One might assume that results can be trusted, but there is a catch. A human isn’t the one who interprets the results and forms a diagnosis. That job is given to an AI model.</p><p>Wouldn’t you want to know the rationale behind the decision? Should we just blindly follow the prediction that the model makes?</p><p>Well it was refreshing to know that there is a field devoted to training models to explain their decisions. It is called <strong>Explainable AI (XAI).</strong></p><h3>What is Explainable AI?</h3><p>This is a black box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mq3D91K8fnJD_VPz.png" /><figcaption>Photo by Anon on <a href="https://pixabay.com/illustrations/cube-block-black-box-3d-geometric-250082/">Pixabay</a></figcaption></figure><p><em>Ok…and?</em></p><p>Well, it turns out that with new deep learning innovations, it becomes increasingly difficult for us to understand how a model came to its decision, given the use of backpropagation and gradient descent. This system is referred to as the <strong>black box</strong>, as engineers or data scientists can not easily interpret the calculations the model employs, given the extensive parameters used in training.</p><p>This is where Explainable AI comes in. It is a set of processes and techniques to provide insights into the decision-making of a black-box model. This allows you to:</p><ul><li><strong>Tune the model’s hyperparameters</strong> by developing an increased understanding of the decision making processes</li><li>Inform clients and stakeholders about <strong>why a specific prediction was made</strong>, providing more transparency.</li></ul><p>By making a machine learning model explainable, the aim is to answer the questions:</p><ul><li><strong>Why</strong> did the model make a certain decision?</li><li><strong>What were the features </strong>that affected a model’s success or failure?</li><li>What degree of <strong>confidence</strong> must the model have for you to be able to trust it?</li></ul><p>I am sure you have seen examples of XAI in action. For example, take <strong>youtube advertisements</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*UZrZb29k--ZQJ4WmrTnM_Q.png" /><figcaption>States the reason the ad was shown — Image by author</figcaption></figure><h3>Limitation: Performance vs. Explainability</h3><p>Models such as linear regression and decision trees are <strong>inherently explainable</strong>. They take in fewer parameters and have a degree of transparency through intuitive mathematical and statistical formulae. For example, we can evaluate the decision of a linear regression algorithm’s decision to choose a certain function, by mapping the error of the corresponding residuals.</p><p>However, the <strong>accuracy</strong> of these models are <strong>less</strong> than those of deep neural networks which derive complex functions from a great amount of parameters. These mathematical algorithms and techniques, such as gradient descent and backpropagation are what adds to their complexity. For example, OpenAI’s GPT-3 takes 175 billion parameters. While it can potentially generate realistic human text, it is difficult to derive explanations for the decisions made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*m-cwHhfC0W_MmIPXv24-pQ.png" /><figcaption>Examining how Accuracy and Explainability Correlate — Image by Author</figcaption></figure><p>As shown above, a <strong>tradeoff</strong> between accuracy and explainability is evident. Hence, efforts must be made to develop algorithms, working towards ensuring a heightened degree of explainability in more complex models.</p><h3>Deep Dive: Integrated Gradients</h3><p>If we want to discern methods to explain our models, we need to understand the type of data that is being analyzed. In this post, we will go over how to explain image data, though a modified technique can also be applied for structured data.</p><p>Currently, a main technique for implementing Explainable AI are <strong>Integrated Gradients</strong>. Feel free to learn more at the Tensorflow tutorial <a href="https://www.tensorflow.org/tutorials/interpretability/integrated_gradients">here</a>. I will go over how to implement it by using the VGG19 model with ImageNet Weights, to predict a picture of my oboe. You can find the full code at my Github Repository <a href="https://github.com/shayaf84/ExplainableAI">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*k8r20BrNnv4U6MDpCqSbIg.png" /><figcaption>Input to the model as well as top prediction — Image by Author</figcaption></figure><ul><li><strong>Step 1: </strong>We need to <strong>define a baseline image</strong> in which we place a sequence of images above it. It can be all black, all white, or a random image. The importance is that the baseline will generate a neutral prediction by the model.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec89e99810c1446511fd977e62476180/href">https://medium.com/media/ec89e99810c1446511fd977e62476180/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*5jDqMqpZCjQ2HDmoPg3Zdw.png" /><figcaption>Baseline Image — Image by Author</figcaption></figure><p>As seen above, the baseline image was implemented as a 224 x 224 x 3 image with pixel values of 0.</p><ul><li><strong>Step 2: </strong>From there we can map a <strong>series of our image</strong> over the baseline, called an interpolation. However, the intensity of the pixels will be linearly increased by a proportion of alpha (α).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67422636b6a6ca3088aab4052f3c8c0c/href">https://medium.com/media/67422636b6a6ca3088aab4052f3c8c0c/href</a></iframe><p>The segment above constructs the parameters for our image interpolation. It preprocesses our image by converting it to a tensor and resizing it. In addition, we define our alpha value, which consists of 50 evenly spaced values (the increments for interpolation).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b096737ee012e0e20a2ac993649046a/href">https://medium.com/media/5b096737ee012e0e20a2ac993649046a/href</a></iframe><p>Here we define our function for interpolation in two steps. We:</p><ul><li>Compute the difference between pixel values for our image and the baseline</li><li>Construct a new tensor containing the baseline and interpolated images (which are the pixel differences multiplied by the alpha rate of change).</li></ul><p>Great! Now let’s call the function and visualize our interpolations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0789946773f66291288208a2a5f6ab6/href">https://medium.com/media/a0789946773f66291288208a2a5f6ab6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYlQXD7s_nrlNnaZh4zaFw.png" /><figcaption>Image Interpolations (Skips every 10 intervals due to the large alpha increments) — Image by Author</figcaption></figure><ul><li><strong>Step 3: Calculate the gradient</strong> of your model’s prediction with respect to an individual pixel for each of the interpolation images. Because of these gradients, pixels that affect the model’s outcome will have a greater attribution, and vice versa.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e11e36d45498b3c7507987b5fc94655a/href">https://medium.com/media/e11e36d45498b3c7507987b5fc94655a/href</a></iframe><ul><li><strong>Step 4: Accumulate each of the gradients</strong> for the interpolation images, using techniques such as the Riemann Trapezoidal to estimate area under a curve.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8890529ac882bc5fd41e9af99dc272c8/href">https://medium.com/media/8890529ac882bc5fd41e9af99dc272c8/href</a></iframe><ul><li><strong>Step 5: Scale the final feature importance values</strong> over all the interpolation images, and display the final feature importances.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10866e90fd82bb0c13419b3027bbc91d/href">https://medium.com/media/10866e90fd82bb0c13419b3027bbc91d/href</a></iframe><p>Here are the visualizations are feature importance for the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*FhdpcYOz51auwdZkpKqcfA.png" /><figcaption>Image by Author</figcaption></figure><p>Great! We have successfully plotted the pixels that contributed the most to the model’s decision. If you look at the attribution mask, it becomes clear that the <strong>brighter pixels have the highest attribution</strong>. Because of this, it is likely to be included in the overlay.</p><h4>What does this mean though?</h4><p>Let’s take some time to analyze why our model predicted that this image was an oboe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaFTasgbPJY-6pymBS1pPg.png" /><figcaption>Image by Author</figcaption></figure><p>As you can see, it is evident that the model made its prediction based off the shape and structure of the keys. This is good, as it demonstrates the model was able to <strong>grasp key features</strong> within the instrument. However, there are some instances where the model used areas of the image that were not a part of the oboe to make its prediction. Some of them ended up having a high feature attribution, such as the one labelled. This is problematic, as it shows that the model is making the <strong>right decision for the wrong reasons</strong>.</p><p>In this instance, the model is determining that part of the wall is part of the oboe. This is most likely because it is shaped like an oboe key, and thus the model thinks it is part of the instrument.</p><h3>Industries that will be affected by XAI</h3><p>The effects of XAI will be seen in industries such as <strong>healthcare </strong>and<strong> finance.</strong></p><h4>Healthcare</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*8M-jbZOiksrQqqUBGARPqQ.jpeg" /><figcaption>Photo by Hush Naidoo Jaide on <a href="https://unsplash.com/photos/yo01Z-9HQAw">Unsplash</a></figcaption></figure><p>In the Healthcare Industry, there are many instances when decisions that are made will have high impacts. This is particularly noticeable in disease diagnoses, where false positives and false negatives can have an immense impact on the patient. Therefore, XAI can be used in a setting where the <strong>cost of a negative decision is too high</strong>, such as in biopsies.</p><p>According to Erik Birkender, a digital health and medical devices expert,</p><blockquote>“Doctors are trained primarily to identify the outliers, or the strange cases that don’t require standard treatments. If an AI algorithm isn’t trained properly with the appropriate data, and we can’t understand how it makes its choices, we can’t be sure it will identify those outliers or otherwise properly diagnose patients.”</blockquote><p>This lack of comprehension about a model’s decision is what prevents the doctors from understanding whether it was trained correctly. This is reminiscent of the example we saw, in which the model makes a correct decision for a wrong reason.</p><h4>Finance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RWMbBR9oVwAl_MqCAMcmVQ.jpeg" /><figcaption>Photo by Austin Distel on <a href="https://unsplash.com/photos/DfjJMVhwH_8">Unsplash</a></figcaption></figure><p>Because financial markets are increasingly complex and involves analyses of significant amounts of data, AI models are developed to <strong>value companies</strong> and <strong>forecast future asset prices</strong>.</p><p>This is because it is difficult for humans to process all the data without error at an efficient speed. However, this approach still involves a black box in which a user is not able to understand why a model predicted a certain forecast.</p><p>As our economic system can be impacted by decisions influencing it, it will be important to understand what are the key features that drive macroeconomic predictions. This ensures that money is not blindly invested, and forecasts are justified by historical trends and current social factors.</p><p>With Explainable AI, we are able to understand the features that drove a model to make a prediction. This is fundamental when a decision is to be made with a minimal margin of error and will not only advise help us navigate high risk scenarios, but also, help us improve our model. As progress is being made in developing Explainable Algorithms, we can begin to look inside the Black Box of Deep Learning.</p><p>Thanks for reading this article! Feel free to add me on <a href="https://ca.linkedin.com/in/shaya-farahmand-168307220">Linkedin</a> and subscribe to my monthly <a href="https://shayafmd.substack.com/">newsletter</a>.</p><h3>Bibliography</h3><p>[1] <a href="https://www.ibm.com/watson/explainable-ai">Explainable AI</a>, IBM</p><p>[2] <a href="https://www.capestart.com/resources/blog/how-explainable-ai-for-health-care-helps-build-user-trust/">How Explainable AI (XAI) for Health Care Helps Build User Trust — Even During Life-and-Death Decisions</a>, CapeStart</p><p>[3] <a href="https://www.tensorflow.org/tutorials/interpretability/integrated_gradients">Integrated Gradients</a> (2021), Tensorflow</p><p>[4] O. Yalçın, <a href="http://5 Significant Reasons Why Explainable AI is an Existential Need for Humanity">5 Significant Reasons Why Explainable AI is an Existential Need for Humanity</a> (2020), Towards Data Science</p><p>[5] R. Schmelzer, <a href="https://www.forbes.com/sites/cognitiveworld/2019/07/23/understanding-explainable-ai/?sh=e1e2f67c9ef5">Understanding Explainable AI</a> (2019), Forbes</p><p>[6] S. Qian, <a href="http://The Significance of Explainable AI in Finance &amp; Asset Management">The Significance of Explainable AI in Finance &amp; Asset Management</a> (2020), Rebellion Research</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7024d8b1f6b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/opening-the-black-box-an-explanation-of-explainable-ai-7024d8b1f6b3">Opening the Black Box: An Explanation of Explainable AI</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[Protecting Your Money: Detecting Credit Card Fraud with ML/DL]]></title>
            <link>https://medium.com/data-science/protecting-your-money-detecting-credit-card-fraud-with-ml-dl-2c4a9b9a0779?source=rss-2c298d07ebb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c4a9b9a0779</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[fraud]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[credit-cards]]></category>
            <dc:creator><![CDATA[Shaya Farahmand]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 16:00:20 GMT</pubDate>
            <atom:updated>2021-09-30T16:00:20.776Z</atom:updated>
            <content:encoded><![CDATA[<h3>Protecting your Money: Detecting Credit Card Fraud with ML/DL</h3><h4>Detecting Credit Card Fraud with Machine Learning and Deep Learning while Tackling Imbalanced Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*L9COBx9nR-rXBsW3" /><figcaption>Photo by Ryan Born on <a href="https://unsplash.com/photos/x8i6FfaZAbs">Unsplash</a></figcaption></figure><p>In 2019, credit card fraud losses amounted to <strong>$28.65 <em>billion</em></strong> worldwide. As Julie Ferguson, CEO of Merchant Risk Council says, “If a small one-shop business or a restaurant all of a sudden has a $10,000 loss, that could be the difference between making payroll and not making payroll for that company.” Many companies, such as VISA, are looking to AI-based solutions to combat this issue. There are many benefits to using ML to detect credit card fraud, such as MORE:</p><ul><li><strong>Efficient</strong> data processing</li><li><strong>Pattern</strong> recognition</li><li><strong>Accurate</strong> predictions</li></ul><p>This article will demonstrate different machine learning methods to detect credit card fraud. They include:</p><ul><li>Random Forest Classifiers</li><li>Logistic Regression</li><li>Neural Networks</li></ul><p>You can find the GitHub repository to the project at this <a href="https://github.com/shayaf84/Credit_Card_Fraud_Detection">link</a>.</p><h3>Retrieving Data</h3><p>This project uses data from the “Credit Card Fraud Detection” dataset on kaggle.com. You can access it at <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud">this</a> link. For the purposes of this project, I downloaded the file and placed it in my google drive, as the file is large. It can easily be accessed if the drive is mounted with Google Colaboratory. Because credit card fraud relies on processing sensitive data, the original data CAN NOT be displayed. Thus 28 features (V1 — V28) are masked using Principal Component Analysis (PCA). Only two variables were not transformed:</p><ul><li>“<strong>Time</strong>” which represents the seconds elapsed between the current transaction and the first transaction in the dataset</li><li>“<strong>Amount</strong>” which represents the total transaction value.</li></ul><p>The response variable, “<strong>Class</strong>”, has two values:</p><ul><li>1 for fraudulent cases</li><li>0 for non-fraudulent cases</li></ul><h3>Setting up the Environment and Uploading Data</h3><p>We will begin by importing key packages that we will use, as well as mounting our google drive so we can upload our dataset! The file path will be different depending on the folder in which you store the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75282b36e974e828806ae1bf3748a5da/href">https://medium.com/media/75282b36e974e828806ae1bf3748a5da/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e7ea032618126f22bfc0514e082a708/href">https://medium.com/media/2e7ea032618126f22bfc0514e082a708/href</a></iframe><p>The libraries we will use are:</p><ul><li>Numpy</li><li>Pandas</li><li>Seaborn and Matplotlib</li><li>Imbalanced-Learn, Scikit-Learn, Tensorflow</li><li>Google.Colab (to upload files)</li></ul><h3>Exploratory Data Analysis</h3><p>Let’s analyze our data! We can start by looking at the first five rows of the dataset, and retrieving its shape.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5afe813c77c5c40ae6158d4d1340114/href">https://medium.com/media/f5afe813c77c5c40ae6158d4d1340114/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1-jEqvZzFPDOxjSCBzkLQ.png" /><figcaption>Image by Author</figcaption></figure><p>There are <strong>31 columns</strong> in the dataset, 28 of them being the output of PCA (V1 — V28), as well as values for amount and time. Our response variable is class, with 0 being the result for no fraud, and 1 being the result for fraud. The shape of the data tells us that there are 284807 entries and 31 columns.</p><p>Next, we can create a Seaborn countplot to visualize the distribution of the two classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b5380e8db1cb1f777870b9849df915a/href">https://medium.com/media/6b5380e8db1cb1f777870b9849df915a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9gABYRpAj2P7OeDmZNYHw.png" /><figcaption>Image by Author</figcaption></figure><p>Ughhh…this is indeed a dilemma. As you can see, our dataset is <em>highly</em> imbalanced, as an overwhelming majority of our data is in the 0 class. This is a problem because <strong>we have to give the same amount of opportunities for the model to train from both classes</strong>.</p><p>Next, we can plot the distribution of both amount and time over the two classes. We can do this by indexing the dataframe to extract the column we want to plot. In addition, we can adjust the font size, figure size, and axes titles using the different functions in matplotlib, as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44d7928d37ffc9ed2d9470cb6bd0b3ea/href">https://medium.com/media/44d7928d37ffc9ed2d9470cb6bd0b3ea/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b2b55aa5157c3afa5b6027b56d0eb65/href">https://medium.com/media/6b2b55aa5157c3afa5b6027b56d0eb65/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNseWDLIJkKcEfIIjYWx2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HE4NWGdl6D5-Dj6HJncWxw.png" /><figcaption>Image by Author</figcaption></figure><p>From the plot on the left, we can see that fraudulent entries tend to have lower amount values, as opposed to non-fraudulent ones. It is also noteworthy that values for non-fraudulent amounts aren’t spread evenly, as there are larger intervals between the higher values in this variable.</p><p>In terms of time, there doesn’t seem to be a differentiation between the two classes, as those values are consistent among both fraudulent and non-fraudulent entries. This makes sense, because as mentioned earlier, the time feature is representing the seconds elapsed since the first transaction. Hence, the time variable will continue to increase. Assuming that the fraudulent transactions are not all isolated from the non-fraudulent ones in terms of time, they will both have continuous time values.</p><p>Another technique we could use to analyze the relationship between all the variables, including the ones transformed by PCA, is to set up a correlation matrix!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b4a00c989005c899bf841744c11871c/href">https://medium.com/media/3b4a00c989005c899bf841744c11871c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-O1EcBaDeERI5xWil6po2Q.png" /><figcaption>Image by Author</figcaption></figure><p>From this correlation matrix, we can see that there are <strong>no <em>major</em> correlations</strong> between the features in the dataset. Most of the relationships fall between -0.2 and 0.2. Though, there are <strong>some exceptions</strong>, particularly in analyzing the correlation between the amount feature, V7, and V20.</p><p>Another observation is the minimal relationship between the features and class. This can be attributed to the imbalanced nature of the data, which can downplay the importance of certain features.</p><h3>Splitting and Standardizing our Dataset</h3><p>Now let’s drop the time feature. That does not have relevance in making classifications and just logs time… Then, we can split the data into training and testing values with a <strong>test size of 30%</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce9195fd29d48c648f47686c84b8cd1b/href">https://medium.com/media/ce9195fd29d48c648f47686c84b8cd1b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1-jEqvZzFPDOxjSCBzkLQ.png" /><figcaption>Image by Author</figcaption></figure><p>If you look at the data, you will see that the amount values are significantly higher than the entries for other features. For example, in the first entry in data.head(), the amount value is 149.62, which is significantly different from V1 which is approximately -1.36. To resolve this problem, we will use the <strong>standard scaler.</strong> By scaling the variable, the model’s efficiency will increase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f42a5e77f47f526b07cbdfd62fce608/href">https://medium.com/media/8f42a5e77f47f526b07cbdfd62fce608/href</a></iframe><h3>Balancing the Data with Borderline-SMOTE</h3><p>Now, we will need to balance our data to ensure that the model has enough exposure to BOTH classes! This ensures that the model won’t be biased towards the non-fraudulent values, as currently there are more than 280,000 entries with a class of 0, while there are only 492 fraudulent values.</p><p>To change the number of values in class 1, there are two possible methods: random undersampling (reduces the number of entries from the majority class) and synthetic oversampling (synthetically generating new entries for the minority class). Because we want to provide our model with as much data as possible, we will use a technique called <a href="https://sci2s.ugr.es/keel/pdf/specific/congreso/han_borderline_smote.pdf">Borderline-SMOTE</a> (Borderline Synthetic Minority Oversampling Technique). The reason that Borderline-SMOTE was used as opposed to SMOTE is that it takes synthetically generates data in between different elements in the minority class, <strong>while ignoring outliers</strong>. Outliers can be defined as features which neighbour more majority points, than minority ones.</p><p>Below is the code to apply Borderline-SMOTE. It is important to only balance the training data, as the test series must reflect real-world field data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1bb75cedaa33774865b87c804b505f1/href">https://medium.com/media/e1bb75cedaa33774865b87c804b505f1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGtFe3C007ZG7ShTbsP4fw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-mCyGlCUcoIsfr5fzgV_w.png" /><figcaption>(Left) Distribution of training data before oversampling; (Right) Distribution of data after oversampling</figcaption></figure><h3>Machine Learning Models</h3><p>Our dataset is now balanced! This ensures that our model can see the same amount of elements from each of the classes. We can build machine learning models for classification. Two models will be used:</p><ul><li><strong>Random Forest</strong></li><li><strong>Logistic Regression</strong></li></ul><p>Before we start building models, it is crucial to define the performance metrics we will be using. As our validation data is imbalanced,<strong> </strong>if the model would predict the majority class every time, our model will receive an accuracy that is <strong>significantly skewed without consideration for the minority class.</strong> Hence, we will be using precision, recall, and F1 score.</p><p>First, we will build our Random Forest Model, with 15 estimators. Keep in mind that due to the size of the dataset, it will take a couple minutes to run.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d06e7d7285e034b631a6c6c2cca768c/href">https://medium.com/media/3d06e7d7285e034b631a6c6c2cca768c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r7G-Acj6tNObbiAENZmyAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*SshpFP0Dx8pkBbmxiYNXCw.png" /><figcaption>Rounded to two decimal places</figcaption></figure><p>Great! Our model had a high precision and recall, meaning that it did not select as many false positives (precision) or false negatives (recall) as it did true positives! Because of this, the F1 score was high as well.</p><p>Second, we will also build a Logistic Regression Model to solve this classification problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab110cb3977f820aba4ba4b4736a93a1/href">https://medium.com/media/ab110cb3977f820aba4ba4b4736a93a1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sI4eExo6OPcg3AS5Z2MkWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*6SDWrmma7sD0bzumgk0anw.png" /><figcaption>Rounded to two decimal places</figcaption></figure><p>Well…in this case, while recall was high (model selected more true positives than false negatives), the precision was really low, which means that the model selected more false positives than true positives. Hence, the F1 score decreased.</p><p>In comparing these two models, it is important to evaluate the metrics by which we compare them. Our <strong>logistic regression</strong> model had a <strong>higher recall</strong> (by approximately 5%), while the <strong>random forest</strong> classifier had a <strong>higher precision</strong>, (by approximately 78%). Hence, in terms of F1 score, which is a harmonic mean of both precision and recall, the <strong>random forest model </strong>performed better.</p><h3>Neural Network</h3><p>Finally, we will also make a neural network with two hidden layers to solve this classification problem.</p><p>Before creating our model, it is important to define the hyperparameters that we will be using. Here are the ones I used, but feel free to tune them even further with the goal of achieving improved results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJoNhcqMPnMJB5SrRbLnHg.png" /><figcaption>Our Neural Network — Image by Author</figcaption></figure><p>As shown in the diagram, we have:</p><ul><li>An input layer of <strong>64 neurons </strong>with<strong> ReLU </strong>activation</li><li>Two dense hidden layers of <strong>32</strong> and <strong>16 neurons</strong> respectively, each with a <strong>ReLU </strong>activation</li><li>An output layer of <strong>1 neuron</strong> with a <strong>sigmoid</strong> activation</li></ul><p>Additionally, we have:</p><ul><li>An<strong> Adam </strong>optimizer with a learning rate of <strong>1e-4 </strong>and a decay of <strong>1e-6</strong></li><li>Loss of <strong>Binary Crossentropy</strong> and metrics of <strong>precision and recall</strong></li></ul><p>The model will be trained on <strong>5 epochs</strong></p><p>Below is the code I used to create the model, with the Keras module of Tensorflow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01b22ad8454e47ed7eb5087ce44190a8/href">https://medium.com/media/01b22ad8454e47ed7eb5087ce44190a8/href</a></iframe><p>Now that we built the model, let’s run it to see our results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doRpE5IyiFgrNEaOa4ioFQ.png" /><figcaption>Output of the model</figcaption></figure><p>As we can see, our validation precision ranged from approximately <strong>19.52 </strong>to<strong> 61.26%</strong>, while the validation recall ranged from <strong>86.03 </strong>to <strong>90.44%.</strong> Epoch 4 had the best validation recall, and epoch 1 had the best validation precision. The model did not overfit, as the values for precision and recall are still increasing. Feel free to change the number of epochs to view how the model performs over greater periods of time! Do note however that it will take longer to train…</p><p>ML/DL brings <strong><em>speed </em></strong>and <strong><em>accuracy </em></strong>in the fight against credit card fraud as shown in this simple example<strong>. </strong>In 2019, Visa prevented an estimated $25 billion in credit card fraud with their AI systems. Kount’s platform AI was able to return risk rates in speeds as fast as 250 milliseconds. By harnessing the power of machine learning and deep learning, we can work towards combatting such instances of theft.</p><p>Hope you enjoyed reading the article! Feel free to add me on <a href="https://www.linkedin.com/in/shaya-farahmand-168307220/">Linkedin</a> and stay tuned for more content!</p><h3>Bibliography</h3><p>[1] Anon, <a href="https://www.businesswire.com/news/home/20190617005366/en/Visa-Prevents-Approximately-25-Billion-in-Fraud-Using-Artificial-Intelligence">Visa Prevents Approximately $25 Billion in Fraud Using Artificial Intelligence</a> (2019), Business Wire</p><p>[2] L. Columbus, <a href="https://www.forbes.com/sites/louiscolumbus/2019/09/05/how-ai-is-protecting-against-payments-fraud/?sh=518f57044d29">How AI Is Protecting Against Payments Fraud</a> (2019), Forbes</p><p>[3] N. Lee, <a href="https://www.cnbc.com/2021/01/27/credit-card-fraud-is-on-the-rise-due-to-covid-pandemic.html">Credit card fraud will increase due to the Covid pandemic, experts warn</a> (2021), CNBC</p><p>[4] Machine Learning Group — ULB, <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud">Credit Card Fraud Detection</a> (updated 2021), Kaggle</p><p>[5] S. Goswami, <a href="https://towardsdatascience.com/class-imbalance-smote-borderline-smote-adasyn-6e36c78d804">Class Imbalance, SMOTE, borderline SMOTE, ADASYN</a> (2020), Towards Data Science</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c4a9b9a0779" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/protecting-your-money-detecting-credit-card-fraud-with-ml-dl-2c4a9b9a0779">Protecting Your Money: Detecting Credit Card Fraud with ML/DL</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[Detecting Pneumonia from Chest X-Rays with Deep Learning]]></title>
            <link>https://medium.com/data-science/detecting-pneumonia-from-chest-x-rays-with-deep-learning-6b83b4a77ee8?source=rss-2c298d07ebb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b83b4a77ee8</guid>
            <category><![CDATA[pneumonia]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chest-x-ray]]></category>
            <dc:creator><![CDATA[Shaya Farahmand]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 03:07:35 GMT</pubDate>
            <atom:updated>2021-06-21T20:30:09.947Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building various models, and using pre-trained models to diagnose pneumonia from a chest x-ray</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*WzEop492l12u6fxn" /><figcaption>Photo by CDC on <a href="https://unsplash.com/photos/NMZdj2Zu36M">Unsplash</a></figcaption></figure><p><strong><em>Note from Towards Data Science’s editors:</em></strong><em> While we allow independent authors to publish articles in accordance with our </em><a href="https://towardsdatascience.com/questions-96667b06af5"><em>rules and guidelines</em></a><em>, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our </em><a href="https://towardsdatascience.com/readers-terms-b5d780a700a4"><em>Reader Terms</em></a><em> for details.</em></p><p>In 2017, 2.56 million people died from pneumonia. About a third of those people were children less than 5 years old. The WHO estimated that 45,000 of these premature deaths were due to household air pollution. With more efficiency in the diagnostics, many of these deaths can be reduced.<br>The goal of this project is to create various machine learning and deep learning models so that when optimized, can assist radiologists in detecting Pneumonia from Chest X-Rays.</p><h3>Environment and Tools</h3><p>Throughout this project, we will be using python, so it is recommended that you have editors such as Google Colaboratory that is compatible with it but also allows the use of certain python packages.</p><p>We will be using python packages:</p><ul><li>Numpy</li><li>Pandas</li><li>Tensorflow (Version 1.x)</li><li>Sci-Kit Learn and Keras</li><li>Seaborn and Matplotlib</li></ul><p>We will be using other packages to download files and helper functions that do not have to do with building the models. For a full list, check the code attached below.</p><h3>Project and Code</h3><p>Now that we got all the introduction out of the way, let’s get started.</p><p>We will begin by importing some key packages which we will be using throughout the project. We will also be downloading the data (in this case, images of Chest X-rays) for the project.</p><p>You can find the full code on Github <a href="https://github.com/shayaf84/Detecting-Pneumonia-">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14b778ab2df8001bcf0656eb33ef47de/href">https://medium.com/media/14b778ab2df8001bcf0656eb33ef47de/href</a></iframe><p>We have to analyze and become familiar with our data before we start building various models. Let’s download a file called “metadata” which gives us key information about our data. After that, we will create a data frame (essentially a table) using the pandas library, which will give info about the first five images in our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78b364c7894241c70736cca7c94054db/href">https://medium.com/media/78b364c7894241c70736cca7c94054db/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*FKzknNr4_1pUaAN2uPMAOA.png" /><figcaption>Image by Author</figcaption></figure><p>Each row in the table represents one image of a chest x-ray. You can see three columns: class, split, and index. Class is either 0 or a 1, 0 meaning that the lung is healthy, and 1 meaning that the lung has pneumonia. The index is a label for the image that tells us which image in the dataset we are looking at.</p><p>In regards to split, when we are teaching the computer how to do something (in this case diagnose pneumonia), we have to train it, by giving the image with a label. However, we also have to test the computer by giving different images that the computer has not seen before, and letting the computer decide whether or not the lung has pneumonia. So, the split column describes whether the image is used to train the computer or test it. Below is a chart I made to help distinguish between the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*_LjyNQ0bcnM4HrPDMl68hw.png" /><figcaption>Image by author</figcaption></figure><p>Now, make a graph and table of the info given to further classify how many images are in each class, and split. We will be using the pandas method “count” to display the table, and we will be using the seaborn “count plot” to display a graph that classifies the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9143cdaf69e279dc0002e3c96c8ed959/href">https://medium.com/media/9143cdaf69e279dc0002e3c96c8ed959/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*EuvxoR62E9C7fle-pqvq6Q.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*AMd-7oegYjNRGFNh6aa-rg.png" /><figcaption>Image by author</figcaption></figure><p>As the charts show, 1200 lungs are healthy, and 1200 lungs have pneumonia. Within those 1200, a thousand will be used to train the model, and the other thousand will be used to test the model.</p><p>Now that we fully understand which category our data is in, we can go ahead and plot some images, to view what the chest x-rays will look like.</p><p>Run this function, which allows you to plot images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab7fd8af8ee74a4426c54add70a981a7/href">https://medium.com/media/ab7fd8af8ee74a4426c54add70a981a7/href</a></iframe><p>From here you can call the function by running the code below. It downloads the training and testing data (from the functions we defined earlier) and will plot an image depending on an index (the number associated with the image. Notice the 1 on line 4). The “data” is the image while the “labels” section is the number 0 or 1 to say whether the patient has pneumonia or not.</p><p>I specifically chose one healthy image, and one with a lung that has pneumonia. Feel free to play around with the index to see other images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38c977a120ac47da714c26c28d2cfe8e/href">https://medium.com/media/38c977a120ac47da714c26c28d2cfe8e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*mOocdkQfaRwQnEXnCzvePw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*yJespG2WoDS1xacDNcecGw.png" /><figcaption>The image on the left is a healthy lung, and the one on the right has pneumonia. Images by author</figcaption></figure><h3>Simple Machine Learning Models</h3><p>Now that we finished examining and analyzing our data, we can go ahead and build some machine learning models. We will begin simple, using the K-nearest neighbours, and logistic regression classifiers.</p><h4>K-Nearest Neighbours</h4><p>The key concept of K-nearest neighbours is that, when we see an unknown example, we will look at what the unknown is closest too, and predict that it is the same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*0a9_oaWWlyRrlHGmDNe_mA.png" /><figcaption>Image by author</figcaption></figure><p>This diagram above shows the K-Nearest Neighbours Classifier. For example, if k=1, the (single) closest shape to the one in question is a circle. Thus, if k=1, the shape is a circle. However, if k=3, the 3 closest shapes to the one in question are 2 rectangles and 1 circle. So, if k=3, the shape is a rectangle.</p><h4>Logistic Regression</h4><p>Logistic Regression is used to predict probabilities that will later be turned into a category (0–1). In linear regression, the predicted y-value can exceed the 0–1 range (with the continuous straight line). However, in logistic regression, the predicted y-values can not exceed the 0–1 range because it is in the shape of an “s”. As an example, look at the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*3zn-zTP8_NjMuCth.jpeg" /><figcaption>Image by Michaelg2015 on <a href="https://en.wikipedia.org/wiki/Logistic_regression#/media/File:Exam_pass_logistic_curve.jpeg">Public Domain</a></figcaption></figure><p>It shows on the x-axis, the number of hours students were studying, and the y-axis shows whether or not they passed the exam (0 or 1). However, the logistic curve’s y-axis shows the probability of whether or not they passed the exam. As you can see, the curve predicts that people who study less will fail, rather than pass, and vice versa.</p><h3>Building the Machine Learning Models</h3><p>We will be using the sci-kit learn library to build these models, specifically the KNeighborsClassifier and LogisticRegression methods.</p><p>The steps to build a machine learning model is to load the model, fit (or train) the model, use the model to predict whether a patient has pneumonia or not, and finally evaluate the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b410b0773aec39fa26677aca4aad220f/href">https://medium.com/media/b410b0773aec39fa26677aca4aad220f/href</a></iframe><p>As you can see, in lines 6 and 7, we loaded or initiated the models. Then, on lines 10, and 11, we trained the models using the train data. For predictions, the models predicted what the test_labels were based on the test_data. This is why, to check the accuracy score, we were checking to see how our predictions were, based on the test_data.</p><p>So, now we can run the model and check the accuracy scores. Note that you can improve the performance of the KNN classifier by just changing the number of neighbours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*URnhcoTCQs0WKs5an-ndUw.png" /><figcaption>Accuracy Scores</figcaption></figure><p>It is obvious that the accuracy scores for these models were low. Thus, these are not the best models to use for this problem. So, we have to take a different approach to it.</p><h3>Convolutional Neural Networks</h3><p>Convolutional Neural Networks are a specific type of neural networks, used to find patterns between images. I will briefly describe 3 key parts:</p><ol><li>Convolution</li><li>Pooling</li><li>Fully-Connected Layers</li></ol><h4>Convolution</h4><p>A convolutional kernel is a matrix of weights, similar to the ones of a fully-connected layer. A convolutional kernel is applied to inputs by multiplying the weights elementwise with the corresponding pixel values in the image input. This will help sharpen the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*l6MArXYUcU8msA0A.gif" /><figcaption>Image by Michael Plotke on <a href="https://commons.wikimedia.org/wiki/File:2D_Convolution_Animation.gif">Public Domain</a></figcaption></figure><h4>Pooling</h4><p>The convolution layer output is still too big for the neural network to make any predictions. We can reduce its size by pooling. It combines certain pixels from the convolution layer and combines them into a single one. Max pooling is one of the most common examples of pooling, where it divides the output into tiles, and takes the maximum of each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*SN804CdGmwYS_T7Mht7sYg.png" /><figcaption>Image by Aphex34 on <a href="http://en.wikipedia.org/wiki/Convolutional_neural_network#/media/File:Max_pooling.png">Public Domain</a></figcaption></figure><h4>Fully Connected Layers</h4><p>Fully connected layers connect each neuron in a single to every other neuron in the next layer. The last layer uses an activation function that outputs probabilities, such as softmax or sigmoid, which the computer will use to classify images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*BQ0SxdqC9Pl_3ZQtd3e45A.png" /><figcaption>Image by Kjell Magne Fauske on <a href="https://texample.net/tikz/examples/neural-network/">Public Domain</a></figcaption></figure><h3>Building our Convolutional Neural Network</h3><p>We will be using the Keras library to build our model. Before you build your model, run these two functions, that will allow you to plot accuracy and loss.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc5bf6b8eacff7d90924580bb567071e/href">https://medium.com/media/dc5bf6b8eacff7d90924580bb567071e/href</a></iframe><p>So, now that we ran those functions, let’s build the model. There are key components that you must know, which are:</p><ul><li><strong>add(Conv2D())</strong>: The layer that performs convolution. It takes 3 arguments. The first is the number of times it performs the convolution, second is the dimensions of the convolution, and the third is the activation function. For the first layer, make sure to specify the input shape as well.</li><li><strong>add(MaxPooling2D()): </strong>The layer that performs the max-pooling. It takes in 1 argument, which is the dimensions of the pixels that are combined.</li><li><strong>add(Flatten()): </strong>Flattens the images into a one dimensional array.</li><li><strong>add(Dense()): </strong>Adds a fully-connected layer. It takes in two arguments, the number of neurons in the layer, and the activation function of that layer.</li><li><strong>add(Dropout(): </strong>Shuts off a certain amount of neurons, to reduce overfitting. Takes in one argument, usually a number between 0 and 1, which when converted to percents, is the percents of neurons from the previous layers that will be shut off.</li><li>Our activation function for every layer (except the output layer) will be <strong>ReLU</strong>. For our output layer, the activation function will be <strong>sigmoid </strong>which outputs probabilities of whether our patient has pneumonia or not.</li><li>Our loss will be <strong>binary_crossentropy</strong>, and we will use the optimizer, <strong>RMSprop</strong>, customized to a learning rate of 1e-4 and a decay of 1e-6.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ba054fa48ce1f45d9e468609cb6d0e2/href">https://medium.com/media/5ba054fa48ce1f45d9e468609cb6d0e2/href</a></iframe><p>Great! Now that we built our model, let’s run it to see how well it did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*qQDPIhmh3wsHSFmOjefoRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*K955UY-vCQhEYpaDglZRgQ.png" /><figcaption>Images by author</figcaption></figure><p>You can see from the plots above, that our model did fairly well. However, it did not perform well enough for it to be used in a clinical setting. You can from here continue tinkering with the model to increase accuracy and decrease the loss. However, make sure to avoid overfitting (when the computer memorizes the training data, so it performs poorly on the testing data.</p><h3>How to read the graph</h3><p>The x-axis shows the number of epochs. Whenever there are decimals on the x-axis, you can ignore it, because only full epochs are allowed (whole numbers). On the y-axis, you have the value you are measuring. It could be loss, accuracy, etc. The yellow line represents the training data, while the blue line represents the validation data. The green line represents the best epoch for that metric.</p><h3><strong>Transfer Learning</strong></h3><p>For our transfer learning, we will be using VGG16. VGG16 is an “expert” model used during the “ImageNet” Classification Problem. In ImageNet, contestants were challenged to build models that can distinguish between 14 million image categories, where there were more than 20,000 categories available.</p><p>VGG16 was allowed to study those 14 million images 74 times. It then was able to guess an image to the real label better than a human can.</p><p>We are going to take VGG16 and let it train on our x-rays. Hopefully, their experience in the ImageNet Problem will assist in distinguishing pneumonia from our x-rays.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c801c8ef51fa47f43c3fc747513b80a/href">https://medium.com/media/6c801c8ef51fa47f43c3fc747513b80a/href</a></iframe><p>The first line will download, VGG16’s Convolution algorithms. Then we will have to declare it as trainable, making sure we can train every layer, by utilizing a “for” loop. After that, we have to add and customize fully connected layers, as VGG16 contains fixed convolution layers.</p><p>Now, run it and let’s see how it performed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*5nsIXQtuyQ9_McgCcfqtEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*aY_rPfETP49jVaRG7uxwVQ.png" /></figure><p>As you can see, the performance of our model, with VGG16 significantly increased. You can also see that the model began to overfit after 1–2 epochs. This is because VGG16 is pre-trained, so that makes it more efficient and accurate, but at the same time, it can overfit easier.</p><h3><strong>Conclusion</strong></h3><p>We started this project by analyzing the data we learned and learning how many images have pneumonia or are healthy. We also split the dataset into training data and testing data. Afterwards, we constructed simple machine learning models, that were able to make informed decisions based on the training that we applied to it. Finally, we built Convolutional Neural Networks to improve the accuracy and efficiency of the model. Afterwards, we used a pre-trained model as our transfer learning to further optimize our model. Now, I leave it to you. How can you continue to improve the model, so that it will be able to be used in medical practices? Maybe you can even run it on some field data and apply data augmentation.</p><h3><strong>References</strong></h3><p>[1] Anon, <a href="https://inspiritaischolars.teachable.com/courses/1040297/lectures/21877191">Classification</a> (n.d.), Teachable</p><p>[2] Anon, <a href="https://www.who.int/news-room/fact-sheets/detail/pneumonia">Pneumonia</a> (2019), World Health Organization</p><p>[2] B. Dadonaite, and M. Roser, <a href="https://ourworldindata.org/pneumonia#citation">Pneumonia</a> (2019), Our World in Data</p><p>[3] C. Archie, <a href="https://towardsdatascience.com/chest-x-rays-pneumonia-detection-using-convolutional-neural-network-63d6ec2d1dee">Chest X-rays Pneumonia Detection using Convolutional Neural Network</a> (2020), Medium.com</p><p>[4] R. Prabhu,<a href="https://medium.com/@RaghavPrabhu/understanding-of-convolutional-neural-network-cnn-deep-learning-99760835f148"> Understanding of Convolutional Neural Network (CNN) — Deep Learning</a> (2018), Medium.com</p><p>Credit to Inspirit AI for teaching me about all the technical details and providing the dataset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b83b4a77ee8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/detecting-pneumonia-from-chest-x-rays-with-deep-learning-6b83b4a77ee8">Detecting Pneumonia from Chest X-Rays with Deep Learning</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[Prime Editing in Four Steps]]></title>
            <link>https://medium.com/@shayaf/prime-editing-in-four-steps-f4246ccdee2e?source=rss-2c298d07ebb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4246ccdee2e</guid>
            <category><![CDATA[search-and-replace]]></category>
            <category><![CDATA[dna]]></category>
            <category><![CDATA[innovative]]></category>
            <category><![CDATA[prime-editing]]></category>
            <category><![CDATA[gene-editing]]></category>
            <dc:creator><![CDATA[Shaya Farahmand]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 03:27:19 GMT</pubDate>
            <atom:updated>2020-08-30T21:02:25.989Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple introduction to the new gene-editing technology</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O-nYms8K4D-eF9fL.jpg" /><figcaption>Image by DNA on <a href="https://commons.wikimedia.org/wiki/File:Dna-163466.jpg">Public Domain</a></figcaption></figure><p>When I first heard about Prime Editing, the first thing that came to my mind was a type of language editing! It took me some googling to recognize that I was way off track. After reading the first paragraph about it, I was blown away and fascinated by the topic and its importance. Prime Editing is about editing the human genome. Yes, that means a mechanism to reprogram human beings. This is very exciting and equally scary. The opportunities are unlimited if you can stretch your imagination such as eradicating all genetic diseases, and the threat is quite serious as these tools in the wrong hands can really hurt humans. Here we will discuss Prime Editing in four steps at a high level.</p><h3>Step 1: What are Genes?</h3><p>The human genome is made up of DNA. Beginning with the basics, DNA is the molecule that contains our genetic code. On each strand, there are a series of chemicals known as letters. This is to make it easier to abstract the genetic concepts and draw a parallel to coding in information technology as genetic codes really define a human¹. The following diagram shows a simplified example of DNA structure. Don’t worry about what letters mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*lK02K5Gf_zYK82wWDfkmTg.png" /><figcaption>The structure of DNA. Notice how A is always across T and G is always across C.</figcaption></figure><p>From a medical perspective, any error (bug) in human genes (code) can cause a disease. For example, an extra or lack of appropriate letters cause genetic diseases. Scientists (like programmers) have been looking for ways to identify and correct (debug) genetic codes to cure diseases. That means they have to trace the human genes to identify these errors and use a mechanism to fix it. This is where gene editing becomes important.</p><h3>Step 2: Current Gene Editing Mechanisms: CRISPR</h3><p>A notable current method of gene editing is CRISPR which stands for ‘clustered regularly interspaced short palindromic repeats’. CRISPR treats the genome harshly. Think of it as a pair of scissors that:</p><ul><li>Cut the erroneous letter(s) from the code (i.e. by cutting the DNA double helix)</li><li>Insert the right letter in their place (i.e. programmed DNA are placed at the cut)²</li></ul><p>This is shown in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*SH1vdoGdFIsYAMdIUmNvXw.png" /><figcaption>Depiction of how CRISPR functions</figcaption></figure><p>What happens next? Well, the cell will have to repair itself, often causing other errors. Scientists and geneticists are trying to improve CRISPR and its search and replace function. The idea is to use a more simple concept which is like a pencil and paper. Instead of cutting and inserting letters (such as carving on a stone), scientists want to find, erase and rewrite the right letters to make the necessary corrections with a more straightforward mechanism.³ In the words of David Liu, Biologist at Harvard University, the goal of genome engineers is “the ability to make virtually any targeted change in the genome of any living cell or organism”. One of the most recent improvements to CRISPR technology, which Liu introduced, is “prime editing”.</p><h3>Step 3: The Emerging Mechanism — Prime Editing</h3><p>Prime Editing, is a genome editing tool that works like a “search and replace” function of a word processor to modify the genome of living organisms. Prime Editing works by finding the location of an erroneous letter and writing the new genetic information instead. You may wonder how all of this happens. To give you an idea, Prime Editing writes directly into a targeted DNA by using a protein that is called Cas9. This is the same protein that is used in CRISPR, which can zero in on a location in a plant or animal genome.⁴</p><p>Unlike CRISPR, Prime Editing does not break the entire gene structure (i.e. DNA double-helix). It keeps a part of Cas9 that serves as a homing mechanism and uses a guide (i.e. pegRNA⁵) to target a specific location. It cuts only a single strand of DNA, where genetic text will be added to half of the DNA structure (double-helix). Prime Editing uses another enzyme, known as reverse transcriptase⁶ which replicates the genetic text to ensure that it covers the entire DNA strand. You can think of it as the copy and paste commands in a word processor.</p><p>This is shown in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*YxJ2oSqUDizT9k1OGIGEQA.png" /><figcaption>Depiction of how Prime Editing functions</figcaption></figure><p>The initial attempts of Prime Editing by Liu and his team had been proven successful. They claim that Prime Editing successfully fixed the error that causes sickle cell disease (one wrong letter), Tay-Sachs disease (four extra letters), as well as a cause of cystic fibrosis (three missing letters). They hope that one day prime editing could repair most inherited DNA errors that cause genetic diseases.⁷</p><h3>Step 4: Where We Are Going with Prime Editing</h3><p>Prime editing has received mainstream press attention due to its applications in medicine. It is believed to be worth an immense amount of money. Venture Capitals such as Newpath and F-Prime formed a company called Prime Medicine, and bought rights to it. The company is very new. Beam Therapeutics is also another company that Liu founded, which helped advance the development of Prime Editing. The startup currently has a market cap of $1.28B.⁸</p><p>While Prime Editing is a great advancement to CRISPR, it has some negatives. First, not every cell will complete the change, thereby it is not as efficient as researchers desired it to be. Second, Prime Editing requires a complex process. It does not easily absorb into cells and requires cumbersome gene therapy. Also, as genetic engineering enhances, there can be controversies surrounding potential uses, such as genetic pesticides or bioterror weapons.⁹</p><p>As of 2019, Prime Editing is a proof of concept. There are approximately 70,000 genetic mutations, and Dr. Liu says there is an 89% chance of curing them, utilizing Prime Editing.¹⁰ However, more research needs to be done to understand how Prime Editing functions. Researchers need to determine if and how Prime Editing can cure other diseases, as well as the long term effects of Prime Editing.¹¹</p><p>“This is the beginning rather than the end,” Liu told journalists in a conference call arranged by Nature. “If CRISPR is like scissors, base editors are like a pencil. Then you can think of prime editors like a word processor, capable of precise search and replace … All will have roles.”</p><p>Prime Editing is a good example of how you can apply coding concepts in biology to cure complex diseases. I am quite excited and hope you are as well. This field has a lot of potential to shape the future of healthcare and more.</p><p>[1]: <a href="https://www.livescience.com/37247-dna.html#:~:text=DNA%20structure,DNA&#39;s%20instructions%2C%20or%20genetic%20code.">https://www.livescience.com/37247-dna.html#:~:text=DNA%20structure,DNA&#39;s%20instructions%2C%20or%20genetic%20code.</a></p><p>[2]: <a href="https://ghr.nlm.nih.gov/primer/genomicresearch/genomeediting">https://ghr.nlm.nih.gov/primer/genomicresearch/genomeediting</a></p><p>[3]: <a href="https://www.technologyreview.com/2019/10/21/102528/the-newest-gene-editor-radically-improves-on-crispr/">https://www.technologyreview.com/2019/10/21/102528/the-newest-gene-editor-radically-improves-on-crispr/</a></p><p>[4]: <a href="https://en.wikipedia.org/wiki/Prime_editing#Delivery_method">https://en.wikipedia.org/wiki/Prime_editing#Delivery_method</a></p><p>[5]: <a href="https://directorsblog.nih.gov/tag/pegrna/">https://directorsblog.nih.gov/tag/pegrna/</a></p><p>[6]: Ibid.</p><p>[7]: <a href="https://www.technologyreview.com/2019/10/21/102528/the-newest-gene-editor-radically-improves-on-crispr/">https://www.technologyreview.com/2019/10/21/102528/the-newest-gene-editor-radically-improves-on-crispr/</a></p><p>[8]: Ibid.</p><p>[9]: Ibid.</p><p>[10]: <a href="https://geneticliteracyproject.org/2019/12/19/crispr-gene-editings-prime-upgrade-could-snip-out-89-of-genetic-diseases/">https://geneticliteracyproject.org/2019/12/19/crispr-gene-editings-prime-upgrade-could-snip-out-89-of-genetic-diseases/</a></p><p>[11]: <a href="https://www.synthego.com/guide/crispr-methods/prime-editing#:~:text=Prime%20editing%20is%20a%20gene,achieved%20previously%20in%20different%20ways.">https://www.synthego.com/guide/crispr-methods/prime-editing#:~:text=Prime%20editing%20is%20a%20gene,achieved%20previously%20in%20different%20ways.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4246ccdee2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>