<?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 Manu Siddhartha on Medium]]></title>
        <description><![CDATA[Stories by Manu Siddhartha on Medium]]></description>
        <link>https://medium.com/@sid321axn?source=rss-9579240f862------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XcZL00myhaHcmAQi</url>
            <title>Stories by Manu Siddhartha on Medium</title>
            <link>https://medium.com/@sid321axn?source=rss-9579240f862------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:26:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sid321axn/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[Foreign Exchange Rate Prediction Using Deep Learning (ANN, LSTM & GRU)]]></title>
            <link>https://medium.com/@sid321axn/foreign-exchange-rate-prediction-using-deep-learning-ann-lstm-gru-936a0a7df293?source=rss-9579240f862------2</link>
            <guid isPermaLink="false">https://medium.com/p/936a0a7df293</guid>
            <category><![CDATA[foreign-exchange]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[forex-trading]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Manu Siddhartha]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 09:22:20 GMT</pubDate>
            <atom:updated>2020-08-27T16:08:26.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*kSKaX0p1yHO-EUks.jpg" /></figure><h4>Prediction of Forex Rate (USD/INR) Using LSTM &amp; GRU</h4><p>The foreign exchange rate (Forex) market is the largest and most crucial trading market in the world followed by the credit market. The foreign exchange rate market determines the exchange rate of different currencies of the world. It involves buying, selling, and exchanging currencies at current or determined prices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*kLG4Cm-O-Gi_SgOPZJgPHw.jpeg" /><figcaption><a href="https://www.quora.com/How-much-volume-is-traded-per-day-in-the-forex-market">Image Source</a></figcaption></figure><p>As we can see from the above figure, the average daily trading volume of the Forex market is way too higher than other big stock exchanges in the world.</p><p>Some of the nice quotes on trading are -</p><blockquote><strong><em>“</em>Trading effectively is about assessing probabilities, not certainties”.</strong><em> </em><strong><em>Yvan Byeajee, </em></strong><a href="https://www.goodreads.com/work/quotes/44949307"><em>Paradigm Shift: How to cultivate equanimity in the face of market uncertainty</em></a></blockquote><blockquote><strong><em>“</em>The stock market is a device for transferring money from the impatient to the patient”.</strong><em> Warren Buffet</em></blockquote><p>The ability to predict the foreign exchange rate is a valuable skill in the trading business. But the prediction of the foreign exchange rate is a highly complex time series problem. As forex prices depend on many external, political factors, its prediction is a very challenging task.</p><blockquote><strong><em>“</em>It’s not whether you’re right or wrong that’s important, but how much money you make when you’re right and how much you lose when you’re wrong”.</strong><em> Stanley Druckenmiller</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CQ8jTwlRGPqWmTCX.jpg" /></figure><p>Deep learning models proven to be very efficient in the prediction of complex financial analytics problems.</p><p>In the case of time series problems, Recurrent Neural Networks (RNNs) proven to outperform traditional Machine Learning algorithms and Artificial Neural Networks (ANNs).</p><p>RNNs are the networks with loops in their architecture as shown in the below figure. This feature of RNN helps them to retain information from previous sequences or events which makes them favorable for time series problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*VPjKqVLBHarPSCT6xysaEw.png" /><figcaption><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">Image Source</a></figcaption></figure><p>In this article, we will demonstrate the application of two different variants of RNNs i.e., <strong><em>Long Short Term Memory</em> <em>(LSTM)</em></strong> and <strong><em>Gated Recurrent Unit (GRU)</em></strong> for prediction of the foreign exchange rate (i.e., USD/INR).</p><p>For knowing more about the architecture and basic working principle of RNN and LSTM you can refer to <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/"><em>colah’s blog</em></a> and for GRU you can refer to <a href="https://d2l.ai/chapter_recurrent-modern/gru.html"><em>dive into deep learning blog</em></a></p><p>Firstly, we will build Artificial Neural Networks as a base model, and later, we will improve the performance in prediction by applying LSTM and GRU. The full code with the dataset demonstrated in this article is available at this <a href="https://github.com/sid321axn/foreign-exchange-prediction-using-deep-learning">repo</a>.</p><p>The article is divided in the following order:</p><h4>1. About Dataset</h4><p>The data is the heart of any machine learning or deep learning project. in this case study, we have web scraped the Foreign exchange rates of USD/INR for the time period of 26 Aug 2010 to 26 Aug 2020 i.e., 10 years from the website <a href="https://in.investing.com/"><strong><em>in.investing.com</em></strong></a>.</p><p>The sample entries of the dataset are shown in below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*XX_ZEvvnMa1Binlh.png" /></figure><h4>2. Data pre-processing</h4><p>For the time-series problem, we have to convert our first column i.e., date to index.</p><p>For doing this there are two methods, in one method while reading <strong>CSV</strong> file in pandas you can specify <strong><em>index_col=’Date’</em></strong> and <strong><em>=True</em></strong>. By specifying these two parameters, pandas preprocess your DateTime column i.e., Date during import, and set it to the index of the data frame.</p><p>The second method is related to <strong>post-reading</strong> means after reading the data you can first convert the date column to DateTime and then set it to the index of data frame. The code snippet demonstrating this method is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb28b3f941c304ae889e742ddfc57db4/href">https://medium.com/media/bb28b3f941c304ae889e742ddfc57db4/href</a></iframe><p>After doing the above pre-processing, the dataset looks like below as shown in table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*2kEc368QadxmdYBR.png" /></figure><p>As per the above table, our target variable is <strong>Price</strong> which we have to predict based on <strong>Date</strong>.</p><p><strong>Sorting the dataframe</strong></p><p>Next, we will sort the pandas dataframe with respect to the Date column in ascending order. The code snippet for sorting the dataframe is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73320c2c4252d723eb58f98c90aec078/href">https://medium.com/media/73320c2c4252d723eb58f98c90aec078/href</a></iframe><p>As our target variable is Price, so we will select Price column and date as index while discard all other columns present in the dataset.</p><p>The below figure shows the distribution of Price from August 2010 to August 2020. As per the figure, we can observe three spikes in the dataset first one is the major spike in the year 2014, the second spike observed in early 2019 while the third one is in the late 2020s.</p><h4>3. Summary Statistics</h4><p>Next, we will explore the summary statistics of the data. As per the below table, we can observe that the average price in the dataset is <strong>61.9025</strong> while 50% of the price is around 64 and the maximum price in the dataset is <strong>76.97</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/0*mBn59JnfRHY6hPr-.png" /></figure><p>Further, we will check the distribution of data in percentage. As we can see from below figure, the total data comprise of 10 years and 80% of it lies in the interval between 2010 to 2018.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*7HLzgLVB6NqJK-Vo.png" /></figure><h4>4. Train Test Split</h4><p>As we have seen 80% of the data lies in the interval of 2010 and 2018 so we will train the model for the date range of <strong>26 August 2010 to 26 August 2018</strong> and rest will be used for testing purposes.</p><p>The code snippet for splitting the dataset and plotting the train test data frame is shown below. As per the code, we have first selected the split date as 26–08–2020 based on which segregate training and test set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9903d11e6e1d99e16edf9c7c16a4c65/href">https://medium.com/media/f9903d11e6e1d99e16edf9c7c16a4c65/href</a></iframe><p>Next, we have created the training set by selecting data points up to 26–08–2020 and test set by retaining all the data points after split date 26–08–2020.</p><p>The below plot showed the visualization of train test split of dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*MbHDOuFD-HVIBYjp6GVoaw.png" /></figure><h4>5. Data Normalization</h4><p>In this step, we will normalize the dataset using a <strong>standard scaler</strong> normalization method. Standard Scaler normalization involves rescaling the distribution of values so that the <strong>mean of observed values is 0</strong> and the <strong>standard deviation is 1</strong>.</p><p>The code for normalizing the dataset is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b4b317f17f8935503a76843ea3b5ada/href">https://medium.com/media/4b4b317f17f8935503a76843ea3b5ada/href</a></iframe><p>Next, we will segregate the train and test set into <strong>X_train</strong>, <strong>X_test</strong>, <strong>y_train, </strong>and <strong>y_test</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d990b1e67b03d8f8581013d9771f8abb/href">https://medium.com/media/d990b1e67b03d8f8581013d9771f8abb/href</a></iframe><h4>6. Modeling</h4><p>In this step, we will build deep learning model and fit them into dataset for making the prediction. In this case study, we will first build the Artificial Neural Network (ANN) as a base model and evaluate its performance for making its result as a benchmark for LSTM and GRU models.</p><h4>Artificial Neural Network (ANN)</h4><p>Artificial neural networks (ANNs) are biologically inspired computational networks. ANNs are generally used in supervised learning problems in which we know the target labels of the data. It consists of mainly three layers: input, hidden, and output layer.</p><p>In our case, we have a single input, 12 neurons in hidden layers, and an output layer which will give the output result in terms of predicted price. We have used shallow neural network with one hidden layer for our use-case and this will be our base model.</p><p>The architecture of Artificial Neural Network is outlined in the below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ORQd5bFNKYogtxWX.png" /></figure><p>The code snippet of ANN model is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2efcbcae009ef4e1b9d964890773f20/href">https://medium.com/media/c2efcbcae009ef4e1b9d964890773f20/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/0*Fo7yv-H6kgjIKUVz.png" /></figure><p>As we can see, we have 37 total parameters in our ANN model. So it is quite a lightweight model which helps in lowering down the risk of <a href="https://www.mathworks.com/help/nnet/ug/improve-neural-network-generalization-and-avoid-overfitting.html#:~:text=One%20of%20the%20problems%20that,to%20generalize%20to%20new%20situations.">overfitting</a></p><p>The code for compiling and fitting the model is shared in the below code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9f8d250a21455cf7252a4a41d66f73d/href">https://medium.com/media/a9f8d250a21455cf7252a4a41d66f73d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*Hdhk11UNwUjVCV_6.png" /></figure><p>Now let’s talk about some of the hyper-parameters we have used in our ANN model.</p><ol><li><strong>loss =</strong> <strong>mean_squared_error</strong>: As it is a regression problem, we have used mean_squared_error as our loss function. The <strong>mean squared error (MSE)</strong> of an estimator measures the average of the squares of the errors i.e., the average squared difference between the predicted values by the model and actual values. The mathematical formulae for mean squared error are shown below</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*FRjZDhZbjjzLOdC8Apbo6A.png" /></figure><p>2. <strong>metric = rmse</strong>: For metric we have used Root Mean Square Error (RMSE) which is the square root of mean squared error. It is basically the standard deviation of the residuals (i.e., difference of predicted and actual value). Residuals are a measure of how far from the regression line data points are.</p><p>3. <strong>Early stopping:</strong> Early stopping used to stop the training process of the model once the model stops showing improvement in terms of loss. Its monitor parameter used to specify which hyper-parameter we want to monitor while training the model. in our case we are monitoring loss.</p><p>As we can see from the above simulation, the model stopped training after 13 epochs as it stops showing improvement further.</p><h4>Result of ANN</h4><p>After fitting the model, we have perform model evaluation based on R2 score, RMSE and Mean Absolute error. The results are shown in below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*-48VF2-NmonV5OiTN0H2eg.png" /></figure><p>As we can see from the above results, the Test R2 score is <strong>0.943</strong> and the Adjusted R2 score is <strong>0.942</strong> which is quite good as in regression problem R2 and Adjusted R2 are two important performance metrics. The more the value closer to 1, the better is the model. Test RMSE of <strong>0.071 </strong>and Test MAE of <strong>0.054 </strong>are also relatively smaller errors which determines that the model is fitted decent regression line over the actual price.</p><figure><img alt="Prediction plot of ANN" src="https://cdn-images-1.medium.com/max/721/1*8CFROah2fb74xv6x2gEvaQ.png" /></figure><p>As per the above prediction plot of ANN, it is observed that the model predicts closely the actual prices in the initial observations, but after 400 observations, its predicted values become too far from the actual values.</p><p>Next we will move towards more complex models in time series i.e., LSTM and see how it will perform.</p><h4>LSTM</h4><p>Long Term Short Memory (LSTM) networks are another variant of RNNs. They are capable of retaining long term dependencies among the sequence of events or data points. They were first introduced by <a href="http://www.bioinf.jku.at/publications/older/2604.pdf">Hochreiter &amp; Schmidhuber (1997)</a>.</p><p>The major difference between RNN and LSTM is that an LSTM has an<strong> explicit memory</strong> <strong>unit</strong> which stores information relevant for learning some task. In LSTMs, the memory units retain pieces of information even when the sequences get really long.</p><p>The structure of LSTM cell is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*55T2h7EzozIa6rxu.png" /></figure><p>Each LSTM cell consists of three gates Forget gate, Update gate and Output gate.</p><p><strong>Forget Gate: </strong>This gate controls how much information needs to be discarded from the previous cell state depending on the new input.</p><p><strong>Update Gate:</strong> This gate makes an <strong>update to the previous the cell state</strong> by writing a new piece of information to it.</p><p><strong>Output Gate:</strong> This gate controls how much information needs to be passed on to the next LSTM layer based on the current cell state.</p><p>The structure of an LSTM cell allows an LSTM network to have a smooth and uninterrupted flow of gradients while backpropagating. This flow is also called the <strong>constant error carousel</strong>. Due to this characteristic LSTMs are able to solve the problem of <a href="https://en.wikipedia.org/wiki/Vanishing_gradient_problem">vanishing</a> and <a href="https://deepai.org/machine-learning-glossary-and-terms/exploding-gradient-problem">exploding gradients</a>.</p><h3><strong>Data Pre-processing for LSTM</strong></h3><p>Before building the LSTM model, we have to pre-process the training and test set as shown in the below code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c14c81032426487365d20a8e105cb73f/href">https://medium.com/media/c14c81032426487365d20a8e105cb73f/href</a></iframe><p>The code for building LSTM model using keras framework is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/458dab954ccdc6ec11039a98d1e4e100/href">https://medium.com/media/458dab954ccdc6ec11039a98d1e4e100/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*oiKKRY4CLJJ7yf7Z.png" /></figure><p>As we can see from the above code, we have used 50 neurons in the LSTM cell with activation function relu, kernel initializer lecun_uniform, and return sequence False.</p><p>For understanding the concept of kernel initializer you can refer a good discussion on <a href="https://datascience.stackexchange.com/questions/37378/what-are-kernel-initializers-and-what-is-their-significance">datasciencestackexchange</a>.</p><p>The code for compiling and fitting the LSTM model is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5021c38094b5fe584f0e5f14aa869433/href">https://medium.com/media/5021c38094b5fe584f0e5f14aa869433/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*zFHp8ONmqdS5BU14.png" /></figure><p>As we can see from above figure, the training of LSTM model stopped after 40 epochs due to early stopping.</p><h4>Result of LSTM</h4><p>The result after fitting the LSTM model is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*h-J_m02MZpWJg1LJhxZUGQ.png" /></figure><p>As we can see from the above results, the Test R2 score is <strong>0.879 </strong>and the Adjusted R2 score is also <strong>0.0.879</strong> which is lower than ANN’s R2 and adjusted R2 score. Test RMSE of <strong>0.102 </strong>and Test MAE of <strong>0.075 </strong>are also relatively more than ANN’s RMSE and MAE. The above result of LSTM led to the conclusion that LSTM performance is lower than shallow ANN network for this particular case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*g7m118llyQuNgMys.png" /></figure><p>As we can see from above plot, LSTM performs well for initial observations but for later part it performs worse than ANN.</p><p>Further, you can try some other combinations of hyper-parameters of LSTM to see if its performance will improve or not.</p><p>So, next we will build GRU model to see if its performance will be bettern than LSTM and ANN or not.</p><h4>GRU</h4><p>Gated Recurrent Unit (GRU) and LSTM both have the characterstics to retain the long term dependency of past sequence of events. The major difference between the two is LSTMs control the exposure of memory content (cell state) while GRUs expose the entire cell state to other units in the network.</p><p>The LSTM unit has a separate <strong>update</strong> and <strong>forget gates</strong>, while the GRU performs both of these operations together via its <strong>reset gate</strong>.</p><p>The architecture of GRU is shown in below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*kBdVGVNNaqFB34gM.png" /></figure><p>The code for building GRU model using keras framework is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccef143327f89bb2b7bf0c655a77d8e1/href">https://medium.com/media/ccef143327f89bb2b7bf0c655a77d8e1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*xE6H8DtuAQlEqJNV.png" /></figure><p>As we can see from above figure, we have build a light weight GRU model having only 7 neurons in hidden layer due to which total model parameters are only 197.</p><p>The code for compiling and fitting the model is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e5376fd65c3e7e9a9887238c4b4e7b8/href">https://medium.com/media/9e5376fd65c3e7e9a9887238c4b4e7b8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/0*jKDgrBz5r5X_TSOC.png" /></figure><p>As we can observe from above figure, the model stops training after 44 epochs due to early stopping.</p><h4>Result of GRU</h4><p>The result after fitting the GRU model is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*iP48CL4QjmjtU8oaIayTwQ.png" /></figure><p>As we can see from the above results, the Test R2 score is <strong>0.967</strong> and the Adjusted R2 score is also <strong>0.967</strong> which is better than ANN and LSTM. Test RMSE of <strong>0.054 </strong>and Test MAE of <strong>0.042 </strong>are also relatively too lesser than ANN and LSTM.</p><p>The above result of GRU led to the conclusion that GRU performance is way better than the shallow ANN network and LSTM network for prediction of Forex rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*aoa9Ga11QdHYxyY2.png" /></figure><p>From the above plot, we can observe that GRU prediction is very close to actual values whereas after 400 observations its deviation from actual price is way too lower in comparison to ANN and LSTM.</p><p>So from the above results, it is clear that our final model for foreign exchange rate prediction is GRU. We further do the inverse transform of predicted and actual values as we had transformed the actual values during normalization using standard scaler.</p><h4>7. Final Assessment of Model</h4><p>In this step, after inverse transforming the predicted and actual values, we finally create the pandas data frame comprising Date, Actual Price, Predicted Price, and RMSE as shown in the table below. The reason for creating this data frame is to assess the summary statistics of predicted and actual values.</p><p>The summary statistics of the above dataframe is shown below.</p><p>As we can see from the above stats table, the average RMSE is 0.195 which is quite lower for this kind of dataset. Further, if we compare average, 50%, and max prices of Actual Price with GRU_prediction price, we can observe a slight difference between the two which prove that the GRU model performs literally well for the prediction of Forex prices. As the model has predicted prices that are very close to actual prices, this model can be used to detect the trend of prices which can be utilized for forecasting whether to buy or sell the currency at a particular time in the future.</p><p>Finally we have plotted the prediction result of final dataframe with dates on x-axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*SfzbVL4ycofVr-Pv.png" /></figure><h4>8. Conclusion</h4><p>In this article, we have explored the Forex dataset of USD/ INR currency exchange rate for the time period of 10 years. After necessary pre-processing, we have applied the ANN model as our base model, further, we have applied LSTM and GRU.</p><p>Finally, after comparing the results of these three models, we found that GRU outperformed ANN and LSTM for this task and shown commendable results</p><p>Further, there is much scope left for further improvement like trying different combinations of hyperparameters in LSTM and GRU for improving the performance, you can apply the Bi-directional LSTM model and check whether it can outperform GRU and lastly, you can also apply vanilla RNN and compare its performance with other variants for prediction of the foreign exchange rate.</p><p>Lastly, as we know foreign exchange rate depends on different factors like Balance of Payment of the country, Government debt, inflation, interest rates, current economic condition like recession, depression or boom, current political condition, etc. So we can use these factors in addition to technical indicators which can be fed into the input of the model for prediction of the foreign exchange rate in order to make more realistic forecasting.</p><blockquote><strong>“Deep Learning is the quality learning that ‘sticks’ with you for the rest of your life…”</strong><em> </em><strong>Michael Fullan, Joanne Quinn &amp; Joanne McEachen</strong></blockquote><p><em>Originally published at </em><a href="https://wisdomml.com/foreign-exchange-rate-prediction-using-deep-learning/"><em>https://wisdomml.com</em></a><em> on August 27, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=936a0a7df293" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[r complaint of tion in bankApplication of Machine Learning in Banking Sector — Wisdom ML]]></title>
            <link>https://medium.com/@sid321axn/r-complaint-of-tion-in-bankapplication-of-machine-learning-in-banking-sector-wisdom-ml-259eaca7f40b?source=rss-9579240f862------2</link>
            <guid isPermaLink="false">https://medium.com/p/259eaca7f40b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[banking-technology]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Manu Siddhartha]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 20:49:49 GMT</pubDate>
            <atom:updated>2020-08-13T07:19:01.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>Application of Machine Learning in Banking Sector — Wisdom ML</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*IGFuFXaTjNUVC2hK.png" /></figure><h4>Top 11 Use cases of Machine Learning in Banking Sector</h4><p>In this article, we will explore the areas where machine learning can be used in the banking sector. Apart from that, we will discuss some of the machine learning solutions developed by top banks of the world. Machine Learning is the science of pattern extraction from data for making intelligent decisions. The main advantage of machine learning is that it does not require programming instead it learns the patterns from the data on its own.</p><p>In the banking sector, machine learning can be applied to automate day to day tasks. Further, it can also help in servicing customers through chatbots to save huge manpower that can be easily delegated to some other critical tasks. It can assist the bank in taking important business decisions such as the prediction of default loans and much more.</p><p>Below we will look through 11 potential use cases of machine learning in the banking sector.</p><ol><li><strong>Chatbots for real-time servicing customers</strong></li></ol><p><strong>2. Prediction of Fraudulent Transactions</strong></p><p><strong>3. Financial Text Classification</strong></p><p><strong>4.</strong> <strong>Credit Risk Modelling / Early Stage Prediction of Default Loans</strong></p><p><strong>5. Credit Risk Profiling</strong></p><p><strong>6. Targeting Potential Customer Using Customer Segmentation</strong></p><p><strong>7. Customer Churn Prediction</strong></p><p><strong>8. Bankruptcy Prediction of Companies</strong></p><p><strong>9. Customer’s Complaint Sentiment Analysis</strong></p><p><strong>10. Document summarization &amp; Information extraction</strong></p><p><strong>11. Detection of Money Laundering transactions</strong></p><h4>1. Chatbots for real-time servicing Customers</h4><p>A chatbot is an online chat facility via text-messages that helps solve user queries and gives a feeling of human interaction. Banks can effectively utilize chatbots for various tasks like automation of real-time conversation regarding product queries, the recommendation of relevant products, collecting the basic details of potential customers of the bank, etc. This would mark an end to waiting in long queues for common tasks and hence results in happier customers.</p><p>Today, more advanced forms of chatbots are emerging i.e., contextual chatbots. The contextual chatbots have the ability to predict the user’s intent, sentiments, and remember the short-term conversation details just like humans. Banks can effectively utilize these chatbots to automate customer service by real-time conversation and delegate their manpower to some other critical tasks. Some of the top banks in the U.S. have already deployed chatbots for assisting their customers and solving their queries.</p><p>The <strong>Bank of America</strong> has introduced a virtual assistant named to send important notifications to their customers, provide account summary, balance details, give smart suggestions about money-saving, etc. Similarly, <strong>Wells Fargo </strong>launched a virtual assistant on Facebook messenger platform to serve its customers for resetting of password, providing account details, answering common queries like <strong>where is the nearest ATM?</strong> <strong>how much money they have in their accounts?</strong> <strong>how much money they have spent last week?</strong> Through this chatbot, Wells Fargo can easily serve their customers on a social media platform Facebook Messenger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*g6MvV3Zwzrp1RvXau48bQA.png" /></figure><h4>2. Prediction of Fraudulent Transactions</h4><p>Due to the increase in usage of digital transactions, a huge amount of fraudulent transactions happen every day globally.</p><p>According to the <strong><em>Nilson Report</em></strong>, In 2018 fraud losses reached $27.85 billion worldwide and are projected to rise to $35.67 billion in five years.</p><p>Fraudulent transactions impact the image of the bank directly and create mistrust and dissatisfaction among customers of the bank. So, it is the need of the hour to build an effective fraud prevention solution that generates flags against such fraudulent transactions and blocks or suspends such transactions.</p><p>Machine learning can be used for building such a solution as banks have a huge amount of historical records of customer transactions.</p><p>The machine learning model can be built by training on historical data of customer transactions and after building the model, it can be deployed for real-time detection and prevention of fraudulent transactions.</p><p>Every transaction it processes adds to its repository of historical information, which means it will continuously learn the habits of fraudsters and can also outline important features responsible for predicting fraudulent transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*x_th4Iyzeb6_Pli5bqgP0w.png" /></figure><h4>3. Financial Text Classification</h4><p>As we know different businesses or companies applies for a loan in bank and banks generally use their financial documents to assess their credit worthiness.</p><p>Banks can use Machine Learning based financial news classification to identify the basic sentiments of the applicant’s company (i.e., positive, negative, and neutral) in the market. Such systems will help banks in assessing the current financial status of the company.</p><p>With the use of Machine Learning based Financial Text classification, banks can easily assess the sentiments of the company from financial news or financial documents which will in turn help banks in deciding whether to give loans to the company or not.</p><figure><img alt="Financial News classification" src="https://cdn-images-1.medium.com/max/624/1*GSYSzB_oaVEzRjH_AhWrWA.png" /></figure><h4>4. Credit Risk Modelling / Early Stage Prediction of Default Loans</h4><p>Generally, when the bank receives a loan application, the bank manager has to make a decision for loan approval based on the applicant’s profile. Two types of risks are associated with the bank’s decision:</p><ol><li>If the applicant is <strong>likely to repay the loan</strong>, then not approving the loan results in a <strong>loss of business</strong> to the bank</li><li>If the applicant is <strong>not likely to repay the loan</strong>, i.e. he/she is <strong>likely to default</strong>, then approving the loan may lead to a <strong>financial loss </strong>for the bank.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*_wkjPDB5iqIFz4vB.png" /></figure><p>Banks can leverage machine learning to predict the probability of default loans given input data in terms of borrower loan application.</p><p>Loan applications generally comprise of demographic features, credit profile features, and loan-related features.</p><p>The complexity of dealing with the above two issues multiplies when banks incorporate many dimensions they examine during credit risk modeling.</p><p>These additional dimensions typically include demographic features, loan-related features, credit profile features, or behavioral information such as loan/trade credit payment behavior.</p><p>Analyzing all of these dimensions to predict whether the applicant will repay the loan or not is a very challenging task, but machine learning techniques can help achieve this goal.</p><p>Further Interpretable machine learning models can help banks to check if the model is capturing appropriate features for the prediction of default loans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*oZAFkQX2xRNdBcJC4i7JpA.png" /></figure><h4>5. Credit Risk Profiling</h4><p>Credit risk profiling (finance risk profiling) is very important in terms of identifying specific loan segments that will default or repay the loan in the future.</p><p>The basic principle behind the credit risk profile suggests that <strong><em>80% to 90% of the loan defaults originate from 10% to 20% of the lending segments</em></strong>. Profiling the segments helps in revealing useful information for credit risk management.</p><p>Banks often collect a vast amount of information on their borrowers and it consists of hundreds of variables that help in identifying payment behavior of borrowers.</p><p>Machine Learning can be used for credit risk profiling which learns the payment behavior of borrowers and can help determine which factors are most contributing in segregating borrowers to a particular segment or profile.</p><figure><img alt="Credit Risk Profiling" src="https://cdn-images-1.medium.com/max/506/1*boMw_MHSIHg3N526kBL4Gg.png" /></figure><h4>6. Targeting Potential Customer Using Customer Segmentation</h4><p>Target marketing is important in the sense it is very cost-effective and helps in generating higher revenue. Generally, when a bank launches a new product, it has to make huge advertisement costs which include sending SMS to all customers, distributing printed advertisement leaflets to customers, TV advertisements, etc.</p><p>Target marketing helps in targeting those customer segments which will likely purchase the product and in this way it brings down huge advertisement costs and helps in generating higher revenue at less cost.</p><p>Machine learning can be used for automating the target marketing for banks, as banks have vast historical records of customer transaction data, demographic data, and spending and loan repayment habits of the customer.</p><p>Machine learning can make clusters of customer segments based on their data and help in targeting the corresponding customer base as and when the bank launches a new product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*fRXRLuLht7_D27zYs4bTpg.png" /></figure><h4>7. Customer Churn Prediction</h4><p>In any financial institution, it is much more expensive to get the new customer than retaining the existing one. According to Harvard Business Review companies can increase their revenue by 25% to 85% just by reducing the customer churn rate by 5%.</p><p>Banks should avoid the loss of customers while acquiring new ones in order to increase their profits and enhance their core competitiveness.</p><p>Banks maintain historical customer records of active and dormant accounts of customers.</p><p>So in this scenario, machine learning can be applied in predicting the churn rate of customers and outputs important variables. Based on those variables bank can restructure their products by offering them concessions in products and reduce the churn rates.</p><figure><img alt="Bank customer churn prediction" src="https://cdn-images-1.medium.com/max/616/1*oXekWeQ5eMUamdk5TTftMg.png" /></figure><h4>8. Bankruptcy prediction of companies</h4><p>When any company applies for a loan in the bank, they have to submit their financial statement so that banks can assess their profitability and repayment capacity.</p><p>For this bank requires analysis of their financial statements to decide whether the company can repay the loan in the future or not. Machine learning can be used at this stage for the initial financial statement analysis for predicting corporate bankruptcy. In this case input to the machine learning model could be the financial parameters of the company.</p><h4>9. Customer complaints sentiment analysis</h4><p>Sentiment Analysis of the customer complaints of banks is an interesting task and critical for customer service improvement. Sentiment Analysis is most useful in the examination of individuals’ feelings from textual data. Machine learning in combination with NLP can be applied for classifying customer complaints into moderate, less severe, or most severe. For this task, properly labeled dataset is required so that the machine learning model can be trained on the data with proper pre-processing of raw texts using NLP and provide real-time predictions as soon as customer complaints arrive.</p><p>if you want to know how you can apply machine learning in combination with NLP for text classification kindly refer to this <a href="https://wisdomml.com/2020/08/fake-news-detection-using-nlp-and-machine-learning/">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*quNU1ZUrG8lw4fi5E0GtAg.png" /></figure><h4>10. Document summarization &amp; Information extraction</h4><p>One of the most challenging tasks for the banks is to analyze policy documents for regulatory compliance. In the past decades, banks are investing billions of dollars for compliance every year. The most painful task in this is to extract relevant information from hundreds of pages of policy documents. This task is really time-consuming and results in the huge expense of manpower. Automated text summarization using machine learning and NLP helps in summarizing lengthy documents into a few paragraphs or key points that help in interpreting the overall document. It will also highlight key phrases or sentences which are relevant in the document.</p><p>Machine learning based content summaries will definitely reduce the time in analyzing lengthy documents and will reduce the expenditure of banks in complying with the regulatory policies.</p><p><strong>JP Morgan Chase &amp; Co.</strong>, one of the largest banks of the US has unveiled machine learning based software named <strong>COIN (Contract Intelligence) </strong>which automates document review of legal documents highlighting important clauses and summarizing the result in few paragraphs in a matter of seconds. Earlier, its legal and loan officers spend a total of 360,000 hours each year for interpreting commercial loan legal documents.</p><figure><img alt="Document Summarization" src="https://cdn-images-1.medium.com/max/544/1*pDpAgPnzDL2Vkx8mmYl7aQ.png" /></figure><h4>11. Detection of money laundering transactions</h4><p>According to <strong><em>United Nations Office on drugs and Crime (UNODC)</em></strong>, “ <em>The estimated amount of money laundered globally in one year is 2–5% of global GDP, or $800 billion — $2 trillion in current US dollars.</em> “</p><p>As it has a direct impact on the economy of the government, it is need of the hour to prevent money laundering transactions and reduce false positives which are the current challenging task in the banking industry.</p><p>Between 1% and 2% of all the Anti Money Laundering (AML) alerts are the actual suspicious transactions to be reported to the authorities.</p><p>So, machine learning can be used here to reduce 98% of the cases which are false positives. It will help banks in utilizing their resources to identify 2% potential AML cases.</p><h4>Conclusion</h4><p>So, in this article, we have discussed 11 potential use cases of machine learning in the banking sector. Banking is now very dynamic in nature with the increase in digitization of numerous banking operations. So the potential applications of machine learning will also increase in the banking industry at a rapid pace. Consequently, the requirement of skilled professionals in the machine learning domain will also increase at the same rate.</p><p>I hope I have discussed some of the interesting applications of machine learning in the banking sector.</p><h4>References</h4><ol><li><a href="https://thefinancialbrand.com/71251/chatbots-banking-trends-ai-cx/">Meet 11 of the Most Interesting Chatbots in Banking</a></li><li><a href="https://nilsonreport.com/upload/content_promo/The_Nilson_Report_Issue_1164.pdf">Nilson Report Card Fraud Worldwide</a></li><li><a href="https://www.researchgate.net/publication/265903831_Pre-processing_Online_Financial_Text_for_Sentiment_Classification_A_Natural_Language_Processing_Approach">Pre-processing Online Financial Text for Sentiment Classification: A Natural Language Processing Approach</a></li><li><a href="https://pdfs.semanticscholar.org/100f/ef8fb36d71b096a57d9f463b3ad11c86930e.pdf">Financial Sentiment Analysis Using Machine Learning Techniques, <em>International Journal of Investment Management and Financial Innovations</em></a></li><li><a href="https://www.moodysanalytics.com/risk-perspectives-magazine/managing-disruption/spotlight/machine-learning-challenges-lessons-and-opportunities-in-credit-risk-modeling">Machine Learning: Challenges, Lessons, and Opportunities in Credit Risk Modeling</a></li><li><a href="http://www.iosrjournals.org/iosr-jef/papers/Vol8-Issue2/Version-2/J0802026981.pdf">Credit Risk Analysis &amp; Modeling: A Case Study, <em>IOSR Journal of Economics and Finance</em></a></li><li><a href="https://www.neuraldesigner.com/learning/examples/bank-churn">Predict customer churn in a bank using Neural Designer</a></li><li><a href="https://www.semanticscholar.org/paper/CORPORATE-BANKRUPTCY-PREDICTION-USING-MACHINE-Mattsson-Steinert/cd5faff7c02bcba0b3f7f438d4d1c38c3d30d43e">CORPORATE BANKRUPTCY PREDICTION USING MACHINE LEARNING TECHNIQUES</a></li><li><a href="https://www.researchgate.net/publication/338004293_Sentiment_Classification_of_Indian_Banks&#39;_Customer_Complaints">Sentiment Classification of Indian Banks’ Customer Complaints</a></li><li><a href="https://blog.usejournal.com/nlp-for-topic-modeling-summarization-of-financial-documents-10-k-q-93070db96c1d">NLP For Topic Modeling Summarization Of Financial Documents (10-K/Q)</a></li><li><a href="https://blog.frase.io/20-applications-of-automatic-summarization-in-the-enterprise/">20 Applications of Automatic Summarization in the Enterprise</a></li><li><a href="https://www.emerald.com/insight/content/doi/10.1108/JMLC-07-2019-0055/full/html">Detecting money laundering transactions with machine learning</a></li></ol><p><em>Originally published at </em><a href="https://wisdomml.com/2020/08/application-of-machine-learning-in-banking-sector/"><em>https://wisdomml.com</em></a><em> on August 10, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=259eaca7f40b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fake News Detection using NLP and Machine Learning in Python — Wisdom ML]]></title>
            <link>https://medium.com/@sid321axn/fake-news-detection-using-nlp-and-machine-learning-in-python-wisdom-ml-6f548b0691a7?source=rss-9579240f862------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f548b0691a7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fake-news]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Manu Siddhartha]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 10:21:32 GMT</pubDate>
            <atom:updated>2020-08-10T05:20:34.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fake News Detection using NLP and Machine Learning in Python — Wisdom ML</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*OT_N4E4FjLnwoxu58dcOJA.png" /></figure><h4>Step by Step guide for fake news detection using machine learning, natural language processing in python</h4><p>In this post, we will be discussing fake news detection using machine learning and will start to understand what is fake news, and what is the source of its generation?</p><h3>What is Fake news?</h3><p>Fake news is a form of news that consists of falsified information or hoaxes to deceive users for <strong><em>clickbait</em></strong>. Clickbait is the technique for grabbing the attention of users with flashy headlines which makes them click the link with the purpose of generating revenue by showing different advertisements. Today, with the increasing usage of social media, spreading fake news over the internet, increases manifold and the major source of spreading fake news is online news portals which makes it really difficult to distinguish between real and fake news. In this case study, we will discuss how we can detect fake news from news headlines using <strong>natural language processing</strong> <strong>(NLP) </strong>and <strong>machine learning-based</strong> techniques. The full code used in this post is available in my <a href="https://github.com/sid321axn/fake-news-classifier">Github repo</a>.</p><h3>About Data</h3><p>The dataset used in this case study is the <a href="https://drive.google.com/open?id=1IoTRrJNDJqvaG3hnUpnHQyGvPAJbO8y3">ISOT Fake News Dataset</a>. The dataset contains two types of articles <strong>fake</strong> and <strong>real</strong> news. This dataset was collected from real-world sources; the truthful articles were obtained by crawling articles from <strong>Reuters.com</strong> (News website). As for the fake news articles, they were collected from different sources. The fake news articles were collected from unreliable websites that were flagged by Politifact (a fact-checking organization in the USA) and Wikipedia. The dataset contains different types of articles on different topics, however, the majority of articles focus on political and world news topics.</p><p>The dataset consists of two CSV files. The first file named contains more than 12,600 articles from reuter.com. The second file named contains more than <strong><em>12,600</em></strong> articles from different fake news outlet resources. Each article contains the following information:</p><ul><li><strong>article title (News Headline)</strong>,</li><li><strong>text</strong>,</li><li><strong>label (REAL or FAKE)</strong></li></ul><h3>Exploratory data analysis</h3><p>In this case study, we have extracted interesting patterns from the news headline text using NLP and perform exploratory data analysis to provide useful insights about real and fake news headlines.</p><h4>Snapshot of dataset</h4><p>Figure 1 shows the top 5 entries of the actual dataset used in the case study.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*q8mFQVw4uvCNSVHP2wM8Ig.png" /><figcaption>Figure 1. Snapshot of the actual dataset used in the case study</figcaption></figure><h4>Distribution of Fake news</h4><p>Firstly, we check the distribution of fake and true news in the dataset by plotting the bar graph as shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*Oz5VAmfv_fXeEKs76Z6l8A.png" /><figcaption>Figure 2. Distribution of Real and Fake news in the dataset</figcaption></figure><p>As we have seen from the above figure, the dataset is balanced having 21417 true news and 23481 fake news.</p><h4>Distribution of the number of characters</h4><p>Next, we have checked the distribution of the number of characters in the fake and true news titles. From the below figure it is evident that the average number of characters is higher in case of fake news in comparison to true news.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*zZ9Xfwbuiw5mYRACpg35mg.png" /><figcaption>Figure 3. Distribution of the number of characters in fake news (left) and true news (right)</figcaption></figure><h4>Distribution of unique words</h4><p>Further, we have checked the distribution of unique words used in both fake news and true news titles. As per the figure, it is observed that fake news consists of more unique words in comparison to true news as its main objective is to deceive users with the use of attention-grabbing words in the headlines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*oNDbQB1V7ivHmzZqGTl7pQ.png" /><figcaption>Figure 4. distribution of unique words used in fake news (left) and true news (right)</figcaption></figure><h4>Distribution of special characters</h4><p>In the end, we have checked the distribution of special characters used in both fake and true news and found that more special characters are used in fake news in comparison to true news.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*NzZATLi1lKBlsF2416_Fqw.png" /><figcaption>Figure 5. distribution of special characters in fake news (left) and true news (right)</figcaption></figure><h4>Word Cloud to plot the most frequent words</h4><p>So, next, we will plot the most frequent words in fake news and real news using the word cloud. <strong>Word cloud</strong> is a technique for visualizing<em> most frequent words in a text corpus where the size of the words represents their frequency.</em> For plotting <a href="https://pypi.org/project/wordcloud/">word cloud</a> we have used word cloud python library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*yUXObywQZOyMLb26HbjtwQ.png" /><figcaption>Figure 6. Word cloud representation of fake news and real news</figcaption></figure><p>As we can see from the above figure, most frequent words in fake news are <strong>Video</strong>, Obama, Hillary, Trump and Republican whereas Real news comprises <strong>Trump</strong>, <strong>White House</strong>, <strong>North Korea</strong>, <strong>China,</strong> etc.</p><h3>Text pre-processing</h3><p>After analyzing the data, we move towards text pre-processing before building machine learning models. The text pre-processing consists of the following steps:</p><h4>Step 1: Lower casing</h4><p>In the lower casing, we convert all the words in the text in lower case as words VIDEO and video are the same in contextual meaning but it represents different words in vector space resulting in more dimensions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce8d881b027858e090530160eed4cf6a/href">https://medium.com/media/ce8d881b027858e090530160eed4cf6a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*NgKyH3roB-CZzjKy6xHgPg.png" /></figure><p>So, as we can see from the above data frame, all the text in the title column is now converted to lower case. Here df is the pandas data frame using which we have loaded the dataset.</p><h4>Step 2: Stop word removal</h4><p>Stop words are the most common words used in regular conversation and it does not add significant value in the conversation. The examples of stop words are a, an, the, he, she, it, etc. So in text classification tasks, we use to remove such stop words by importing stop words defined in <strong>nltk</strong> corpus. The python code for removing stop words are shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdb46fd5bd47ec6c960521a5bf423df8/href">https://medium.com/media/fdb46fd5bd47ec6c960521a5bf423df8/href</a></iframe><h4>Step 3: Special character removal</h4><p>In this step, we remove all types of special characters in the news title. The special characters are also not significant for text classification and it only increases the total dimension in vector space, so we filter them out before building the machine learning model. The code for filtering out special characters is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21e744c7f590b1a2f6e975d880a1cbdf/href">https://medium.com/media/21e744c7f590b1a2f6e975d880a1cbdf/href</a></iframe><p>It is important to note that, stemming and lemmatization are considered important steps but for this case study we have not performed any of them either, but you are free to try them and see how the final result changes.</p><h4>Train Test Split</h4><p>In this step, we split the data into train and test set in the ratio of 75:25 i.e., 75% of the data used in training the model and rest 25% used for testing the model. The code for splitting data is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/880dcfc55ece8bf4d87f45ef7d5cb30e/href">https://medium.com/media/880dcfc55ece8bf4d87f45ef7d5cb30e/href</a></iframe><h3>Model building</h3><p>First, we have built our baseline model with a count vectorizer. <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html"><strong>Count vectorizer</strong></a> converts the text document to a vector of token counts. The actual working of the count vectorizer is shown in the below figure.</p><p>So, as we can see from the below figure, the sentence “<strong><em>The quick brown fox jumps over the lazy dog</em></strong>” is converted into a frequency table in which column represents tokens in the sentence and rows represents the corresponding frequency of those tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*TwckC6aDmXFKXc4fwd5zFA.png" /></figure><p>So, the code for applying the count vectorizer to the text document is shown below. Code vectorizer is defined in <em>sklearn</em> python library</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/704caf05c930c8402e5769f251cfda49/href">https://medium.com/media/704caf05c930c8402e5769f251cfda49/href</a></iframe><p>Next, with count vectorizer, we have used three machine-learning algorithms Multinomial Naive Bayes which generally performs better in case of text classification, Passive Aggressive classifier, and Logistic regression algorithms. The results of these algorithms in terms of the confusion matrix are below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*bRVK6uxMCM3Je88I6AnTaw.png" /><figcaption>Figure 7. Figure showing the confusion matrix of Multinomial Naive Bayes (Left), Passive-aggressive classifier (Middle) and Logistic regression (Right) using count vectorizer</figcaption></figure><p>As we can see from Figure 7, the highest true positives and true negatives detected by the logistic regression algorithm while the second best is a passive-aggressive classifier.</p><p>To improve the performance of our machine learning algorithms we have used the <em>TFIDF vectorizer</em>. TFIDF vectorizer converts the text document into a matrix of TFIDF features. Now lest see what is TFIDF ? and why it performs better than count vectorizer?</p><p>Now, let&#39;s break down TFIDF into TF i.e., Term Frequency and IDF i.e., Inverse Document Frequency.</p><h4>Term Frequency (TF)</h4><p>Term Frequency represents the number of times a word appears in a document divided by the total number of words in the document. The formulae of Term frequency is mathematically shown as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*gfKuFNWdSHFyOKlRsOeSCQ.png" /></figure><h4>Inverse Document Frequency (IDF)</h4><p>It represents the log of the number of documents divided by the number of documents containing the word <em>w</em>. Inverse data frequency used to weight the rare words across all documents in the corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*UjJH139sV10AVvH5B_6uRw.png" /></figure><p>The reason why TFIDF performs better than count vectorizer is that TFIDF gives higher weight to rare words across all the documents whereas count vectorizer gives importance to common words which are of very little importance in text classification.</p><p>The code for implementing TFIDF is defined in the form of a library that is defined under sklearn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df9e7ce545f8be37bdf1194048be4ddb/href">https://medium.com/media/df9e7ce545f8be37bdf1194048be4ddb/href</a></iframe><p><strong>TFIDF Hyperparameters</strong></p><p>Now let’s talk about its hyper-parameter first one is stopwords which is defined for making aware that stopwords used in the text are of English language, max_df is used for removing terms that appear too frequently, In our case, we have taken its value as 0.8 which means remove those words which appear in more than 80% of the documents and the last hyper-parameter is ngram_range which is set as (1,2) i.e., it will allow both unigrams and bigrams.</p><p>Next, with the TFIDF vectorizer, we have used the same machine-learning algorithms i.e., Multinomial Naive Bayes, Passive Aggressive classifier, and Logistic regression algorithms. The results of these algorithms in terms of the confusion matrix is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Mpp-us9HSHG3gGbpxfMytA.png" /><figcaption>Figure 8. Figure showing the confusion matrix of Multinomial Naive Bayes (Left), Passive-aggressive classifier (Middle) and Logistic regression (Right) using TFIDF vectorizer</figcaption></figure><h3>Result Analysis</h3><p>Now let&#39;s see detailed results of both count vectorizer and TFIDF vectorizer and compare which one performs better. Now, let’s compare both the techniques and find which one performs better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*2ss6y27tMWJM4IfOqp1zSA.png" /></figure><h4>Findings and discussion</h4><p>As per the above Table, Passive Aggressive classifier with TFIDF outperforms others in terms of accuracy, precision, and F1-score whereas the highest recall achieved by Multinomial Naive Bayes which is really surprising. The important thing to notice that after applying TFIDF significant improvement observed in the performance of all three algorithms in comparison to the count vectorizer. In the case of count vectorizer, Logistic Regression outperforms others in all the performance measures except recall.</p><h3>Feature Importance</h3><p>Now, let’s see what are the most informative features in predicting Fake and True news with the TFIDF vectorizer. The top 10 key features in predicting fake news are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*N8YTDQgaZ3G41dNIdfvwng.png" /></figure><p>The top 10 key features in predicting true news are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*w5LN5i6hxLZXmQMh_TjfGQ.png" /></figure><p>As we can see from the above figures, the first column is the label the second column consists of coefficient and the last one are the top contributing features. From the figure, it is evident that top features in the case of Fake News are the lowest negative value whereas in the case of true news highest positive value.</p><p>In most of the top fake and true news, only unigrams are present while in case of true news one bigram feature is also present i.e., Islamic state.</p><h3>Conclusion</h3><p>So in this post, we have discussed the application of machine learning algorithms for detecting fake news from news headlines and also discussed text processing using natural language processing. In the end, we compare that TFIDF Vectorizer with Count Vectorizer and found that the former performs better and improves the performance of Multinomial Naive Bayes, Passive Aggressive classifier, and Logistic regression machine learning algorithms and out of which Passive Aggressive attains the highest performance in terms of accuracy, precision, and F1-score.</p><p>I hope this discussion helps you in understanding the application of natural language processing in predicting fake news from news headlines.</p><p>Kindly clap, if you really like this post to show your support.</p><p><em>Originally published at </em><a href="https://wisdomml.com/2020/08/fake-news-detection-using-nlp-and-machine-learning/"><em>https://wisdomml.com</em></a><em> on August 3, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f548b0691a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brain Tumor Classification using Deep Learning]]></title>
            <link>https://medium.com/@sid321axn/brain-tumor-classification-using-deep-learning-5bbd8acef4b4?source=rss-9579240f862------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bbd8acef4b4</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[brain-tumor]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[Manu Siddhartha]]></dc:creator>
            <pubDate>Wed, 01 Apr 2020 02:33:53 GMT</pubDate>
            <atom:updated>2020-04-01T02:33:53.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*l83-JpmYdbv1Cx0RWI1w3w.jpeg" /><figcaption>Figure showing brain tumor in an MRI scan</figcaption></figure><p>A brain tumor is an abnormal mass of tissue in which cells grow and multiply abruptly, which remains unchecked by the mechanisms that control normal cells. Brain tumors are classified into benign tumors or low grade (grade I or II ) and malignant or high grade (grade III and IV). Benign tumors are non-cancerous and are considered to be non-progressive, their growth is relatively slow and limited. However, malignant tumors are cancerous and grow rapidly with undefined boundaries. So, early detection of brain tumors is very crucial for proper treatment and saving of human life.</p><p>Magnetic Resonance Imaging (MRI) of the brain is one of the best diagnostic imaging techniques used by neurologists for the detection of brain tumors. MRI images provide a lot of information about brain structure and abnormalities within brain tissues due to high-resolution images. In the past few decades, researchers have used different automated techniques for the detection of brain tumors using MRI images, as it is possible to scan and load these images in the computer for visual inspection. But recently, deep learning techniques have shown tremendous results and become the state of the art in the field of bioinformatics, medical informatics, and medical image analysis. In this post, I will discuss the detection of brain tumors from MRI scan images using a deep learning technique and compare the performance of different transfer learning approaches for the same.</p><p>My approach for solving this problem is divided into six major steps:</p><ol><li>Dataset Description</li><li>Data Import and preprocessing</li><li>Data Augmentation</li><li>Model Building</li><li>Model Analysis and comparison</li><li>Conclusion</li></ol><h4><strong>1. Dataset Description</strong></h4><p>The dataset used for this problem is Kaggle dataset named <a href="https://www.kaggle.com/navoneel/brain-mri-images-for-brain-tumor-detection">Brain MRI Images for Brain Tumor Detection</a> . It consists of MRI scans of two classes:</p><ul><li>NO - Tumor does not present i.e., normal, encoded as 0</li><li>YES - Tumor present, encoded as 1</li></ul><p>There are 155 images of tumor cases and 98 images of normal patients. In the next step, we import the data and arrange it into separate folders for further model building process.</p><h4>2. Data Import and preprocessing</h4><p>In this step, we first arrange the images which are currently present in two folders Yes and No into three separate folders Train, Test, and Val. The new folder hierarchy will look as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*a-M_MndMAwG23RZVCtdZCw.jpeg" /><figcaption>Tree structure of folders for splitting images</figcaption></figure><p>Next, we have loaded the images in the above folders, resized them into size of (224,224) and created X_test, y_test, X_val, y_val, X_test and y_test in the following distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*fxRS_yEcbG5YokWRaOfhXw.jpeg" /></figure><p>After loading the images we have visualized the images of both the categories as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*LlSgbUx1ftguhhd8aK1B5Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*pDbTL7hO7ylixcMwaoX15g.jpeg" /></figure><p>As we can see from the above sample images tumor is visible in some of the images whereas in some other images it is very difficult to spot them only through visual inspection. Apart from that, it is evident from above sample images that they have different width and height and different size of black corners. As I have used VGG16, VGG19 and Xception network pre-trained models which require input images of shape (224,224) due to this reason some of the wide images look abnormal.</p><p>Next major step is preprocessing of images and in this dataset, the most important preprocessing step for normalizing the images is <strong>cropping brain out of images</strong>, as they are of different size and shape and consists of the unnecessary part which may act as a noise for the model. I have cropped the images by finding extreme points in the images using opencv. The detailed process for cropping an image is mentioned in this <a href="https://www.pyimagesearch.com/2016/04/11/finding-extreme-points-in-contours-with-opencv/">pyimagesearch</a> blog. The step by step process for cropping is shown in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*3uJepY_p5MwWTqAD49gl6g.jpeg" /></figure><p>As you can see from the above images, first the method takes the original image, find the biggest contour, find the extreme points of the brain image and in the end, cropped the brain part in the image successfully. In the next step, we have cropped all the images in the train, test and validation set and save them in separate folder for populating train, test and all set containing only cropped images. After loading images in all the three sets we have again resized the images to (224,224), this is done so because after cropping of images width and height changed significantly.</p><h4>3. Data Augmentation</h4><p>As we have relatively less training images of the tumor and normal cases, so for building the robust model we have augmented the images in the training set using the following parameters as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b2a35fd37f75ef1f95df6b6bd49d622/href">https://medium.com/media/8b2a35fd37f75ef1f95df6b6bd49d622/href</a></iframe><p>After augmenting images in training set, sample images look like below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*kcQyUn1zaBBMR-6B-IE2ng.jpeg" /></figure><h4>4. Model building</h4><p>In this step, we have built different customized deep learning models using the transfer learning approach. We have built VGG16, VGG19 and XceptionNet based sequential model using Keras framework. The detailed architecture of <a href="https://arxiv.org/pdf/1409.1556.pdf">VGG16</a>, <a href="https://arxiv.org/pdf/1409.1556.pdf">VGG19</a>, and <a href="https://arxiv.org/abs/1610.02357">Xception</a> is shown below. We have trained all three models for 30 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*bd7wj2qt1uIxLkEbUw7Liw.jpeg" /><figcaption>Fig. Architecture of VGG16</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*O8QMx1lGfE9xglilds5sKA.jpeg" /><figcaption>Fig. Architecture of VGG19</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*4K0SNI1gZmYzuooF1AAckw.jpeg" /><figcaption>Fig. Architecture of Xception</figcaption></figure><h4>5. Model Analysis and comparison</h4><p>In this step, I have analyzed all the three models using various evaluation metrics and the most important one for this problem domain is sensitivity and F1- measure. The detailed performance of all three transfer learning approaches is shown in the below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*ULTP1sA8hlkzOWXuTlecaw.jpeg" /><figcaption>Table. Showing performance comparison of Xception, VGG-16, and VGG-19</figcaption></figure><p>As we can see from the above results VGG-16 outperforms others by detecting all the brain tumor cases with 100% sensitivity while Xception model is the worst performer having only 50% accuracy and precision. The confusion matrix of all three models is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*sU9rTM6faxn1hDE2R0CwJg.jpeg" /><figcaption>Figure Showing confusion matrix of Xception, VGG-19, and VGG-16 from left to right</figcaption></figure><p>As we can see from above confusion matrix Xception is just similar to random guessing while VGG-16 detected all the 5 brain tumor cases whereas it has also predicted 2 normal cases to be brain tumor cases which brings down its specificity to 60% but overall F1-score of VGG-16 is 83.33% which is somewhat not bad with just 30 epochs.</p><p>For evaluating models on more appropriate measure is to plot the <a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">Receiver Operating Characteristics Curve (ROC)</a> curve which is also known as 1- specificity vs 1-sensitivity curve. The ROC plot of all the three models is shown in below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*vXefISdKCjkyQ2vk6oc7pA.jpeg" /><figcaption>Figure showing ROC plot of Xception vs VGG-19 vs VGG-16</figcaption></figure><p>As per the above plot, it is evident that Xception is flat 45-degree straight line which is equivalent to random guessing model while the area under the curve (AUC) for VGG-19 is 0.70 and VGG-16 is 0.80 somewhat better.</p><h4><strong>6. Conclusion</strong></h4><p>In this approach, I have tested only three transfer learning based pretrained models you can test others like ResNet, Inception V3 etc. while I also train the model for only 30 epochs which can be increased to 100 for increase in accuracy and sensitivity. Further, our dataset is somewhat small for building robust model in this problem domain you can use <a href="https://www.med.upenn.edu/cbica/brats2019/data.html"><strong>BraTS 2019 data</strong></a><strong>set </strong>which is a Multimodal Brain Tumor Segmentation Challenge 2019 dataset. In the next part, I will be discussing brain tumor segmentation using Mask-R CNN which is more comprehensive and interesting as it detects the region of interest (RoI) in brain MRI scans while predicting brain tumors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bbd8acef4b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Interpretability for Heart Disease Prediction]]></title>
            <link>https://medium.com/@sid321axn/machine-learning-interpretability-for-heart-disease-prediction-23d8d95a307b?source=rss-9579240f862------2</link>
            <guid isPermaLink="false">https://medium.com/p/23d8d95a307b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-tools]]></category>
            <category><![CDATA[heart-disease]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[interpretability]]></category>
            <dc:creator><![CDATA[Manu Siddhartha]]></dc:creator>
            <pubDate>Tue, 17 Sep 2019 11:12:23 GMT</pubDate>
            <atom:updated>2019-09-17T11:12:23.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*hj18nKHXLOD8H1jksQtN3A.png" /></figure><p>Heart disease is the deadliest disease, which is a leading cause of death for people in the United States, India and other Asian countries. According to the <a href="https://www.heart.org/-/media/data-import/downloadables/heart-disease-and-stroke-statistics-2018---at-a-glance-ucm_498848.pdf">American Heart Association</a>, approximately every 40 seconds an American will have a heart attack. The estimated annual incidence of heart attacks in the United States is 720,000 new attacks and 335,000 recurrent attacks.</p><p>There are numerous factors which are responsible for heart disease such as High Blood Pressure, High Cholestrol, smoking habit, Diabetes, Overweight and obesity, Poor diet, Physical inactivity, Excessive alcohol use etc.</p><p>Early detection of heart disease is crucial in saving the life of people. he chances of survival are greater when emergency treatment begins quickly. Good data-driven systems for predicting heart disease can improve the entire research and prevention process, making sure that more people can live healthy lives.</p><p>In this post, I will explore different machine learning approaches in predicting heart disease. But, the major problem in the practical scenario is acceptability of “<strong>black box</strong>” machine learning models. As medical practitioners generally give a diagnosis based on their experience and knowledge-based reasoning, it is somewhat difficult for them to accept vague and difficult to understand models in diagnosing the critical disease which involves the cost of human life. So, to deal with their dubiety I have designed an interpretable machine learning model which presents key attributes/features and their range of values responsible in predicting particular class type of heart disease.</p><h3>Dataset</h3><p>The dataset, I have used for this project is Heart Disease Data set hosted at <strong>UCI Machine Learning repository</strong> and available at <a href="https://archive.ics.uci.edu/ml/datasets/Heart+Disease">this link</a>.</p><p>It has total <strong>14</strong> features include target feature which is a binary field and refers to the presence of heart disease in the patient.</p><h3><strong>Model Building</strong></h3><p>As this post is focused towards exploring machine learning interpretation strategies so I will not discuss data preparation, data pre-processing, data-visualization steps. I will start my discussion from model building, evaluation and machine learning interpretation techniques.</p><p>In this step, I have built machine learning models starting from our base model which is <strong>logistic regression</strong>. The details and mathematics involve in logistic regression can be read from <a href="https://www.stat.cmu.edu/~cshalizi/uADA/12/lectures/ch12.pdf">here</a>.</p><p>The code for model development and fitting logistic regression model is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66bcd13f54ba9b0bf1c75d17d25df56f/href">https://medium.com/media/66bcd13f54ba9b0bf1c75d17d25df56f/href</a></iframe><p>As shown in the code above I have used the default parameters of logistic regression. Below I am sharing the code for model evaluation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59d9704061b7758bf461be5913506b67/href">https://medium.com/media/59d9704061b7758bf461be5913506b67/href</a></iframe><p>The result after running the above code is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*ASAsoflcKOA94fcF2Rr49w.png" /><figcaption><strong>Fig. Result of Model Evaluation of Logistic Regression</strong></figcaption></figure><p>Next machine learning algorithm I have used for model building is Random Forest. The theory and actual working of Random Forest can be read from this <a href="https://arxiv.org/pdf/1407.7502">link</a>.</p><p>The code for model development and evaluation of random forest model is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2edb863c8829d542ba8b1c15300184d3/href">https://medium.com/media/2edb863c8829d542ba8b1c15300184d3/href</a></iframe><p>The result after running the above code is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*o0ZyXce6XZnzqUSnt28JVw.png" /><figcaption><strong>Fig. Result of Model Evaluation of Random Forest</strong></figcaption></figure><p>As we can see from the above result random forest has equal F1 score, Precision, ROC and Recall with Logistic Regression but has lesser accuracy in comparison to Logistic Regression. But apart from that, we will be using Random forest for applying machine learning interpretation strategies. the major reason for selecting random forest is it is tree based algorithm which supports and compatible with most of the interpretation techniques.</p><p>So, next we will discuss about Model Interpretation techniques.</p><h3>Explaining Model</h3><p>In this step we will try to explain the model by applying different techniques and algorithms such as :</p><ol><li><a href="https://eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html">Permutation Importance (Eli5)</a></li><li><a href="https://www.kaggle.com/dansbecker/partial-dependence-plots">Partial dependency plotting (pdpbox)</a></li><li><a href="https://shap.readthedocs.io/en/latest/">SHapley Additive exPlanations (SHAP values)</a></li><li><a href="https://github.com/aerdem4/lofo-importance">LOFO Importance</a></li><li><a href="https://github.com/SeldonIO/alibi">Alibi</a></li><li><a href="https://github.com/marcotcr/lime">LIME</a></li><li><a href="https://github.com/MI2DataLab/pyBreakDown">pyBreakdown</a></li></ol><p>So, first we will start from <strong>Permutation Importance</strong> library.</p><h4><strong>1. Permutation Importance:</strong></h4><p><a href="https://eli5.readthedocs.io/en/latest/"><strong>eli5</strong></a> provides a way to compute feature importances for any black-box estimator by measuring how score decreases when a feature is not available; the method is also known as <strong>“permutation importance” or “Mean Decrease Accuracy (MDA)”</strong>.</p><p>The code for applying eli5 on random forest model is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7304506a85a24ffcde8ca267c95f575e/href">https://medium.com/media/7304506a85a24ffcde8ca267c95f575e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*I_5I33Fx9odnQOpjcZFY2w.png" /></figure><h4>Interpretations</h4><p>The values towards the top which are slightly dark in color are the most important features, and those towards the bottom having lighter shade matter least. The first number in each row shows how much model performance decreased with a random shuffling (in this case, using “accuracy” as the performance metric).Measurement of randomness in permutation importance calculation is performed by repeating the process with multiple shuffles. The number after the <strong>±</strong> measures how performance varied from one-reshuffling to the next.</p><p>Here, <strong>thalassemia_reversable defect</strong>, <strong>resting_blood_pressure</strong>, <strong>thalassemia_fixed defect</strong>, <strong>chest_pain_type_atypical angina</strong> and <strong>st_slope_flat</strong> are top 5 important features.</p><p>Next, to explain individual prediction by random forest model there is a method in eli5 library called <strong>show_prediction(). </strong>The code for model explanation by eli5 is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64cf5a66c206cfeed794b1091a770692/href">https://medium.com/media/64cf5a66c206cfeed794b1091a770692/href</a></iframe><p>As shown in the code above I have explained the the 50th record of test set having following prediction as shown in below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*mPzCn3xR9PG_GL73bqxkDA.png" /></figure><h4>Interpretations</h4><p>To make random forest predictions more interpretable, every prediction of the model can be presented as a sum of <strong>feature contributions</strong> (<strong>plus the bias</strong>), showing how the features lead to a particular prediction. In above plot, ELI5 does it by showing weights for each feature with their actual value depicting how influential it might have been in contributing to the final prediction decision across all trees. In the above individual prediction, the top 3 influential features seems to be, after the bias, the <strong>chest_pain_type_non-anginal pain</strong>, <strong>chest_pain_type_atypical angina</strong> and <strong>sex_male</strong>.</p><h4>2. Partial Dependence Plots (PDP):</h4><p>While permutation importance shows what variables most affect predictions, partial dependence plots show how a feature affects predictions. There is a well explained kaggle course on <a href="https://www.kaggle.com/learn/machine-learning-explainability"><strong>Machine Learning Explainability</strong></a><strong> </strong>in<strong> </strong>which partial dependence plots are clearly explained. The background and theory behind PDP can be read from <a href="https://arxiv.org/pdf/1309.6392.pdf">here</a>.</p><p>Like permutation importance, <strong>partial dependence plots are calculated after a model has been fit.</strong> The model is fit on real data that has not been artificially manipulated in any way.</p><p>There are many variants of PDP plot based on different purpose and intuition. Some of them are as follows :</p><p><strong>a.) PDP Isolation plot:</strong></p><p>Below is the code for plotting PDP isolation plot</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34f5bf584b4088624ca7c5c7c8adbfa2/href">https://medium.com/media/34f5bf584b4088624ca7c5c7c8adbfa2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*3lAm3_J_TeBo48GGLsV4ug.png" /></figure><p>A few items are worth pointing out as you interpret this plot</p><ul><li>The y axis is interpreted as <strong>change in the prediction</strong> from what it would be predicted at the baseline or leftmost value.</li><li>A blue shaded area indicates level of confidence</li></ul><p>From this particular graph, we see that reduced <strong>resting blood pressure</strong> reduces the chances of heart disease which is true in general, as high blood pressure levels increases the chance of heart disease.</p><p><strong>b.) Univariate ICE Plot:</strong></p><p>ICE plots are similar to PD plots but offer a more detailed view about the behavior of near similar clusters around the PD plot average curve. ICE algorithm gives the user insight into the several variants of conditional relationships estimated by the black box. The code for plotting ICE plot is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/530c4248f0d7830cfc6802e968ecbbc1/href">https://medium.com/media/530c4248f0d7830cfc6802e968ecbbc1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*MN7zp_BWuGLy6Kgpa_LHpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*npwK4yyeqJ2CtF7UVRDz8A.png" /></figure><p><strong>c.) PDP Interact Plot</strong></p><p>If you are curious about interactions between features, 2D partial dependence plots or PDP interact plots are also useful. An example may clarify this. Code for plotting PDP interact plot between <strong>resting blood pressure</strong> and <strong>age.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2a796a6e6f0b1be1600af1736b49492/href">https://medium.com/media/f2a796a6e6f0b1be1600af1736b49492/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*X8EAuosRUqH0S5e3o1m-2g.png" /></figure><p>As shown in figure above as age increases resting blood pressure also increases and at the point where normalized age is around 1 and resting blood pressure is greater than 0.25 the chances for heart disease prediction is highest.</p><p><strong>d.) Actual Prediction plot</strong></p><p>The code for plotting actual prediction plot is shared below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b10e6349876f0242947d357ed147149b/href">https://medium.com/media/b10e6349876f0242947d357ed147149b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*bIwCjm-bNjE27YbmbqdKXw.png" /></figure><p>Above plot shows the actual prediction plot under partial dependence library, here the bubble size is of less importance, since it pertains to the number of observations (times the incident occurred). The most important insight comes from the color of the bubble, with darker bubbles meaning higher probabilities of heart disease while lighter colors of bubble signifies healthy. This is a powerful tool to use since it has a deep insight on how much two variables of our choice affect the dependent variable.</p><h4>3. SHapley Additive exPlanations (SHAP Values):</h4><p>SHAP values can explain the output of any machine learning model but for complex ensemble models it can be slow. SHAP has c++ implementations supporting XGBoost, LightGBM, CatBoost, and scikit-learn tree models.</p><p>SHAP (SHapley Additive exPlanations) assigns each feature an importance value for a particular prediction. Its novel components include: the identification of a new class of additive feature importance measures, and theoretical results showing there is a unique solution in this class with a set of desirable properties. Typically, SHAP values try to explain the output of a model (function) as a sum of the effects of each feature being introduced into a conditional expectation. Importantly, for non-linear functions the order in which features are introduced matters. The SHAP values result from averaging over all possible orderings. Proofs from game theory show this is the only possible consistent approach.</p><p>An intuitive way to understand the Shapley value is the following: The feature values enter a room in random order. All feature values in the room participate in the game (= contribute to the prediction). The complete theory behind Shapley can be read from <a href="https://papers.nips.cc/paper/7062-a-unified-approach-to-interpreting-model-predictions.pdf">here</a>.</p><p>The code for plotting Shapley values for individual prediction is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5d87132fd4e146907c0b0cda743dc90/href">https://medium.com/media/c5d87132fd4e146907c0b0cda743dc90/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*mu8XcxYyRyVh_uXG0UcoWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*7V-U84S4t7XlQ0R0EDvmEg.png" /></figure><p><strong>Interpretations</strong></p><p>The above graph is generated when we applied SHAP algorithm on instance number 17 and 9 from our test set. In above plot, we predicted 0.80, whereas the base_value is 0.4517. Feature values causing increased predictions are in pink, and their visual size shows the magnitude of the feature’s effect. Feature values decreasing the prediction are in blue. The biggest impact comes sex_male being 0.435, while <strong>chest_pain_type_non-anginal </strong>pain value has the effect of decreasing the prediction.</p><p><strong>SHAP Feature Importance Plot</strong></p><p>The global mean(|Tree SHAP|) method applied to the heart disease prediction model. The x-axis is essentially the average magnitude change in model output when a feature is “hidden” from the model (for this model the output has log-odds units). See <a href="https://github.com/slundberg/shap">github repo</a> for details, but “hidden” means integrating the variable out of the model. Since the impact of hiding a feature changes depending on what other features are also hidden, Shapley values are used to enforce consistency and accuracy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac60f64b5528fc12e5aa2908d8971368/href">https://medium.com/media/ac60f64b5528fc12e5aa2908d8971368/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*LU-e0__pV2L2iigH5kff8A.png" /></figure><p><strong>SHAP Summary Plot</strong></p><p>To get an overview of which features are most important for a model we can plot the SHAP values of every feature for every sample. The plot below sorts features by the sum of SHAP value magnitudes over all samples, and uses SHAP values to show the distribution of the impacts each feature has on the model output. The color represents the feature value (red high, blue low).</p><p>The code for plotting summary plot is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8ed40db111d270ec5f486cb5be511c5/href">https://medium.com/media/b8ed40db111d270ec5f486cb5be511c5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*KdtsbKvxvv-CaGhnzjwwXA.png" /></figure><p><strong>Interpretaions</strong></p><p>SHAP summary plot of a 19 feature Random Forest heart disease prediction. The higher the SHAP value of a feature, the higher is the log odds of heart disease in this heart disease prediction model. Every patient in the dataset is run through the model and a dot is created for each feature attribution value, so one patient gets one dot on each feature’s line. Dot’s are colored by the feature’s value for that patient and pile up vertically to show density. In above plot we see that <strong>chest pain type non anginal pain</strong> is the most important risk factor for heart disease patients. The lower values of <strong>chest pain type non anginal pain</strong> leads to heart disease, whereas in non heart disease patients its contribution is mixture of higher and lower values. Higher values of <strong>thalasemia_fixed_defect</strong> increases the risk of heart disease whereas its lower values decreases the chances of heart disease.</p><h4>4. LOFO Importance:</h4><p>LOFO (Leave One Feature Out) Importance calculates the importances of a set of features based on a metric of choice, for a model of choice, by iteratively removing each feature from the set, and evaluating the performance of the model, with a validation scheme of choice, based on the chosen metric.</p><p>LOFO first evaluates the performance of the model with all the input features included, then iteratively removes one feature at a time, retrains the model, and evaluates its performance on a validation set. The mean and standard deviation (across the folds) of the importance of each feature is then reported.</p><p>If a model is not passed as an argument to LOFO Importance, it will run LightGBM as a default model.</p><p><strong>Advantages of LOFO Importance</strong></p><p>LOFO has several advantages compared to other importance types:</p><ol><li>It does not favor granular features</li><li>It generalises well to unseen test sets</li><li>It is model agnostic</li><li>It gives negative importance to features that hurt performance upon inclusion</li></ol><p>The code for plotting LOFO importance is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f6be514947662ed80241e47b9530eb/href">https://medium.com/media/87f6be514947662ed80241e47b9530eb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*vtwQvdIAtArMR6SU6Eo5og.png" /></figure><h4>5. Alibi</h4><p>Next comes another interesting library for machine learning interpretation <strong>Alibi</strong>. It is an open source Python library aimed at machine learning model inspection and interpretation. The initial focus on the library is on black-box, instance based model explanations.</p><p><strong>Method Used : Anchors</strong></p><p>The anchor algorithm is based on the Anchors: <a href="https://homes.cs.washington.edu/~marcotcr/aaai18.pdf">High-Precision Model-Agnostic Explanations</a> paper by Ribeiro et al. and builds on the <a href="https://github.com/marcotcr/anchor">open source code</a> from the paper’s first author.</p><p>The algorithm provides model-agnostic (black box) and human interpretable explanations suitable for classification models applied to images, text and tabular data. The idea behind anchors is to explain the behaviour of complex models with high-precision rules called anchors. These anchors are locally sufficient conditions to ensure a certain prediction with a high degree of confidence.</p><p><strong>Goals</strong></p><ol><li>Provide high quality reference implementations of black-box ML model explanation algorithms</li><li>Define a consistent API for interpretable ML methods.</li><li>Support multiple use cases (e.g. tabular, text and image data classification, regression)</li><li>Implement the latest model explanation, concept drift, algorithmic bias detection and other ML model monitoring and interpretation methods</li></ol><p>The code for applying Alibi is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4074a99bf9dce6f5fa64af03edf0ee51/href">https://medium.com/media/4074a99bf9dce6f5fa64af03edf0ee51/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*M-9c9UhmbZwASa8g8gvBFA.png" /></figure><h4>6. LIME</h4><p><strong>Local Interpretable Model-agnostic Explanations (LIME)</strong>. The overall goal of LIME is to identify an interpretable model over the interpretable representation that is locally faithful to the classifier.</p><p>The local explanation method LIME interprets an individual prediction by learning an interpretable model locally. The intuition behind LIME is that it samples instances both in the vicinity and far away from the interpretable representation of the original input. Then LIME takes the interpretable representation of these sample points, determines their predictions and builds a weighted linear model by minimizing the loss and complexity. The samples weighting is based on their distances from the original point. The points weights decrease as the points get farther away. The explanation is locally faithful, which means it represents the model prediction of vicinity instances.This is illustrated in below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*UnvKXpNYMHSggQSfXqdsow.png" /></figure><p>By explaining a prediction”, we mean presenting textual or visual artifacts that provide qualitative understanding of the relationship between the instance’s components (e.g. words in text, patches in an image) and the model’s prediction. We argue that explaining predictions is an important aspect in getting humans to trust and use machine learning effectively, if the explanations are faithful and intelligible. The process of explaining individual predictions is illustrated in Figure 1. It is clear that a doctor is much better positioned to make a decision with the help of a model if intelligible explanations are provided. In this case, an explanation is a small list of symptoms with relative weights {symptoms that either contribute to the prediction (in green) or are evidence against it (in red). Humans usually have prior knowledge about the application domain, which they can use to accept (trust) or reject a prediction if they understand the reasoning behind it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*Tc0m7PjY8-Uow7R4ssZzGA.png" /></figure><p>The code for applying LIME si shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40d628e00907245327fd5f3b5e052a50/href">https://medium.com/media/40d628e00907245327fd5f3b5e052a50/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*B5HHXd9MCj0SssCxhCbKwQ.png" /></figure><h4>7. pyBreakDown</h4><p>The <strong>pyBreakDown</strong> package is a model agnostic tool for decomposition of predictions from black boxes. <strong>pyBreakDown</strong> Table shows contributions of every variable to a final prediction. <strong>pyBreakDown</strong> Plot presents variable contributions in a concise graphical way. This package works for binary classifiers and general regression models.</p><p>you can install pyBreakDown package by running below compound.</p><pre>!pip install git+https://github.com/bondyra/pyBreakDown.git</pre><p>The code for applying pyBreakdown is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/270af8f98dc0e471db4ffa1718422d8c/href">https://medium.com/media/270af8f98dc0e471db4ffa1718422d8c/href</a></iframe><p>Below is the explanation which came as a output by running above code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*u-HK8iTvxQZ_l6GjR6djGg.png" /></figure><p>By running below code we can get visualization of explanation by pyBreakDown package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90d92d4b0c45714c773dc37fb98ab5c7/href">https://medium.com/media/90d92d4b0c45714c773dc37fb98ab5c7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*DUwH3URk9v8QDZJZ7VJYKg.png" /></figure><h3>Conclusion</h3><p>I have tried to implement and show the demo of really awesome machine learning explanation libraries. Some of the other great libraries which I didnt able to run on my local machine due to some dependency issues are as follows :</p><ol><li><strong>Microsoft’s Interpret-ml</strong></li><li><strong>Skater</strong></li><li><strong>fairml</strong></li><li><strong>Contrastive Explanation</strong></li><li><strong>Skope Rules</strong></li></ol><p>Apart from that there are some other more intuitive libraries are there which can help interpret machine learning model and really assist medical practitioners in believing the black box model</p><p>I hope you like this post about applying machine learning interpretation for prediction of heart disease.</p><p>If like, then don’t forget to <strong>clap</strong> this post. It will motivate me for sharing future posts.</p><h3>References</h3><ol><li><a href="https://github.com/jphall663/awesome-machine-learning-interpretability">List of AWESOME Machine learning Libraries</a></li><li><a href="https://towardsdatascience.com/human-interpretable-machine-learning-part-1-the-need-and-importance-of-model-interpretation-2ed758f5f476">The Importance of Macine Learning Interpretability by Dipanjan Sarkar</a></li><li><a href="https://christophm.github.io/interpretable-ml-book/">Interpretable Machine Learning by Christoph Molnar</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23d8d95a307b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Malaria cell detection using Convolution Neural Networks (CNN)]]></title>
            <link>https://medium.com/@sid321axn/malaria-cell-detection-using-convolution-neural-networks-cnn-5766d5599fbb?source=rss-9579240f862------2</link>
            <guid isPermaLink="false">https://medium.com/p/5766d5599fbb</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[malaria]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[healthcare-technology]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Manu Siddhartha]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 11:41:42 GMT</pubDate>
            <atom:updated>2019-09-10T11:41:42.533Z</atom:updated>
            <content:encoded><![CDATA[<h4>Application of Deep Learning in diagnosing Malaria cells in human blood sample — AI in Healthcare</h4><p>Malaria is a life-threatening mosquito-borne blood disease. It is caused by The <strong><em>Anopheles</em></strong><em> </em>mosquito transmits it to humans. Malaria is caused by <strong>Plasmodium</strong> parasites. The parasites are spread to people through the bites of infected female Anopheles mosquitoes, called “<strong>malaria vectors</strong>.” There are 5 parasite species that cause malaria in humans, and 2 of these species — <strong>P. falciparum</strong> and <strong>P. vivax </strong>— pose the greatest threat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Pj_RXT67y9eTNO35SnLpiA.jpeg" /><figcaption>Representational view of Malaria infected cell structure</figcaption></figure><p>Malaria must be diagnosed promptly in order to treat the patient in time and to prevent further spread of infection in the community via local mosquitoes. Delay in diagnosis and treatment is a leading cause of death in malaria patients in the United States. Malaria can be suspected based on various factors such as the patient’s travel history, symptoms, and the physical findings at examination. However, for a definitive diagnosis to be made, laboratory tests must demonstrate the malaria parasites or their components.</p><p>In this article, I will explain how I have applied Deep CNN approach in classifying malaria parasites in human blood sample. The dataset I have used in my analysis is carefully collected by researchers at the <strong>Lister Hill National Center for Biomedical Communications (LHNCBC)</strong>, part of <strong>National Library of Medicine (NLM) </strong>who have not only collected but also annotated this dataset of healthy and infected blood smear images. You can download the dataset available at their <a href="https://lhncbc.nlm.nih.gov/publication/pub9932"><strong><em>official website</em></strong></a>.</p><p>Now comes the hardware configuration which is a very crucial part for any deep learning project. For this project I have used <strong>Google colab</strong>, as it requires GPU, which is available here at free of cost. Apart from Google colab you can try other GPU providing platforms such as <strong>Kaggle</strong>, <strong>Floyd GPU</strong> etc.</p><p>I have used following steps in my journey of applying convolution neural network for malaria parasite detection.</p><ol><li><strong>Importing Libraries</strong></li><li><strong>Loading the data</strong></li><li><strong>Plotting sample images and its labels to understand how does an infected cell and uninfected cell looks like</strong></li><li><strong>Data Preparation</strong></li><li><strong>Train Test split</strong></li><li><strong>Normalization</strong></li><li><strong>Model Building (CNN)</strong></li><li><strong>Fitting Model</strong></li><li><strong>Model Evaluation</strong></li></ol><p>So, lets start by following step 1, which is importing essential libraries at one place.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9112dd85a02981f38e50323e2aeb92f0/href">https://medium.com/media/9112dd85a02981f38e50323e2aeb92f0/href</a></iframe><p>In step 2, we will load the images in two directories one for parasite infected images and one for storing uninfected images. Below is the code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2444171c45e66af52dcf6124d61e80d/href">https://medium.com/media/b2444171c45e66af52dcf6124d61e80d/href</a></iframe><p>Next, we will plot some sample images of uninfected images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32824965634706fdbd733e4ce297ef87/href">https://medium.com/media/32824965634706fdbd733e4ce297ef87/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*yB9y4K7l__vgeWYauD2a5A.jpeg" /></figure><p>As we can see the sample of uninfected images, all the samples are clean there is no stain or mark on it.</p><p>Now, lets see the parasite infected sample images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71b906d2f15e9ab8f9e8eb6d28566feb/href">https://medium.com/media/71b906d2f15e9ab8f9e8eb6d28566feb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*AZl_ZPVPZTMyo-pyfagh2A.jpeg" /></figure><p>From the above images, we can clearly see some minute marks or stains in infected samples.</p><p><strong>Data Preperation:</strong> Now, comes the data preparation part. In this step we will prepare the data before fitting it into the deep learning model. For this, we will make data and labels list where data will be image to array implementation which contains RGB values of each image and label will be class of cells here I will be taking 0 and 1 for two classes. We further resize the images into shape of 50 x 50.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb8d7036a82979968700baa378cede46/href">https://medium.com/media/cb8d7036a82979968700baa378cede46/href</a></iframe><p>Further, we will be saving and loading the data we prepared, so next time we can load it from saved .npy file</p><p>Next, we will split data into train and test split in 90:10 ratio, where 90% of images will be used for training and 10% of the images will used for evaluation purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/727e54ae18993d962ab6d25ea528222d/href">https://medium.com/media/727e54ae18993d962ab6d25ea528222d/href</a></iframe><p>Next, we will normalize the data before fitting it into the deep learning model. As we are normalizing the image data we will first convert data into float and then divide by 255.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d56aea434e5ad6c7c0db188fb4cb3cd1/href">https://medium.com/media/d56aea434e5ad6c7c0db188fb4cb3cd1/href</a></iframe><p>Next step is One Hot encoding, It is a binary classification problem, which has two classes so last output layer of neural network will have 2 neurons one for each class, One hot encoding will help us to change labels in binary format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26766611d4cccd51f76fdc3acf07cfeb/href">https://medium.com/media/26766611d4cccd51f76fdc3acf07cfeb/href</a></iframe><p>Now, comes the most interesting part model building. I have used keras library for making deep convolution network. Below is my model . In this model I have used <strong>relu</strong> activation function in input layer and <strong>softmax</strong> activation function in input layer which is a probabilistic function and normalize the probability of all classes to 1, means sum of probability of all the classes(2 in our case) will be 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75ce66e0a237d35b4008ab12a18bca0d/href">https://medium.com/media/75ce66e0a237d35b4008ab12a18bca0d/href</a></iframe><p><strong>Model Summary :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*FxGJggCMR30mSrZxvnopRw.jpeg" /><figcaption>Model summary</figcaption></figure><p>Next, we will compile our model before fitting. In model compilation we generally sets the loss which is “<strong>binary_crossentropy”</strong> in our case, optimizer “<strong>adam”</strong> in our case and metric which is “<strong>accuracy”</strong> in our case.</p><p>In the next step, we will set some callbacks such as <a href="https://machinelearningmastery.com/how-to-stop-training-deep-neural-networks-at-the-right-time-using-early-stopping/">Early Stopping</a> and <a href="https://machinelearningmastery.com/check-point-deep-learning-models-keras/">Model checkpoint</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/300c9b856beebe721ff16e92fb85d807/href">https://medium.com/media/300c9b856beebe721ff16e92fb85d807/href</a></iframe><p>Next, we will fit the model by inputting following parameters in code snippets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d6ccf2b89cb64e73ab9190878b8ad18/href">https://medium.com/media/8d6ccf2b89cb64e73ab9190878b8ad18/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*fIummy_T4E8L03tzSrc3ig.jpeg" /></figure><p>Next we have plotted model’s history plot how model training and validation accuracy improves after every epoch. As it is shown in figure below models training and validation accuracy become equal after 5 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*mTGUyUdUaXQnix2q0cR00Q.jpeg" /></figure><p>Further, we perform model evaluation by evaluating its performance on test images. For this we have calculated test accuracy of the model which comes around 95.82% . Further classification report is also shown in the figure below which shows it has greater recall, precision and f1-score of 0.96.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*QfA5nAQs9V22o-DX-LJHNA.jpeg" /></figure><p>Next we have plotted confusion matrix as shown in the below image. As observed from the below figure only 48 are those cases which are actually infected but the model predicted them as un infected while it correctly predicts 1275 infected cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*HwDqGvxHgNB1CemwHc5hEQ.png" /></figure><p>Next we have computed <strong>Area Under Curve (AUC) score </strong>which comes around <strong>0.9584</strong> and then we have plotted <strong>Receiver Operating Characterstic Curve (ROC) curve</strong> shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*UElGSZahFggwlMgixRYwyA.jpeg" /></figure><p>Below I have plotted some of the model’s prediction on test images. In the below image orange color captioned images are miss-classified images whereas blue captioned images are correctly predicted images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uveHLI6fyk8kFL3BxMCtSA.jpeg" /></figure><p>This is it !!!! hope you like this post. If like, don’ t forget to clap this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*ezDDAAHlg7dNlfCJPRsU-g.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5766d5599fbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skin Lesion Classification using Deep CNNs (A Step-wise Approach)]]></title>
            <link>https://medium.com/@sid321axn/skin-lesion-classification-using-deep-cnns-a-step-wise-approach-347d47868196?source=rss-9579240f862------2</link>
            <guid isPermaLink="false">https://medium.com/p/347d47868196</guid>
            <category><![CDATA[deep-neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[skin-cancer]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <dc:creator><![CDATA[Manu Siddhartha]]></dc:creator>
            <pubDate>Sat, 29 Jun 2019 10:04:49 GMT</pubDate>
            <atom:updated>2019-06-29T10:04:49.453Z</atom:updated>
            <content:encoded><![CDATA[<p>Skin cancer is the most common human malignancy, is primarily diagnosed visually, beginning with an initial clinical screening and followed potentially by dermoscopic analysis, a biopsy and histopathological examination. Automated classification of skin lesions using images is a challenging task owing to the fine-grained variability in the appearance of skin lesions.</p><p>But recently some of the researchers using deep convolution neural network outperformed the expert dermatologists. The CNN achieves performance on par with all tested experts across both tasks, demonstrating an artificial intelligence capable of classifying skin cancer with a level of competence comparable to dermatologists. Full article <a href="https://www.nature.com/articles/nature21056">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*vI4BrjDIQIcsDHOLiriYVw.png" /></figure><p>In this post, I will try to explain the stepwise approach to detect skin cancer types using deep convolution neural networks or CNN&#39;s. For this, I have used <strong>HAM10000 (“Human Against Machine with 10000 training images”)</strong> dataset. It consists of 10015 <strong>dermatoscopic</strong> images which are released as a training set for academic machine learning purposes and are publicly available through the <a href="https://www.isic-archive.com/#!/topWithHeader/wideContentTop/main">ISIC archive</a>. This benchmark dataset can be used for machine learning and for comparisons with human experts.</p><p>It has 7 different classes of skin cancer which are listed below :<br><strong>1. Melanocytic nevi <br>2. Melanoma <br>3. Benign keratosis-like lesions <br>4. Basal cell carcinoma <br>5. Actinic keratoses <br>6. Vascular lesions <br>7. Dermatofibroma</strong></p><p>To detect 7 different classes of skin cancer mentioned above I have used Convolution Neural Network with Keras tensorflow in backend and then analyze the result to see how the model can be useful in a practical scenario.</p><p>I will explain 14 steps which I have followed for model building and evaluation which are as follows :</p><p><strong>Step 1 : Importing Essential Libraries</strong><br><strong>Step 2: Making Dictionary of images and labels</strong> <br><strong>Step 3: Reading and Processing Data</strong> <br><strong>Step 4: Data Cleaning</strong> <br><strong>Step 5: Exploratory data analysis (EDA)</strong> <br><strong>Step 6: Loading &amp; Resizing of images </strong><br><strong>Step 7: Train Test Split</strong><br><strong>Step 8: Normalization</strong><br><strong>Step 9: Label Encoding</strong> <br><strong>Step 10: Train validation split</strong> <br><strong>Step 11: Model Building (CNN)</strong> <br><strong>Step 12: Setting Optimizer &amp; Annealing</strong> <br><strong>Step 13: Fitting the model</strong><br><strong>Step 14: Model Evaluation (Testing and validation accuracy, confusion matrix, analysis of misclassified instances)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfI5nScYGyo1gf0fGsQcaA.png" /><figcaption><strong>The architecture of Convolution Neural Network Model</strong></figcaption></figure><h3>Step 1: Importing Essential Libraries</h3><p>In this first step, I have imported essential libraries for data analysis, image handling, and model building process. Some of them are as follows :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc134c4589b109c8aef90d2b57886b31/href">https://medium.com/media/fc134c4589b109c8aef90d2b57886b31/href</a></iframe><h3>Step 2 : Making Dictionary of images and labels</h3><p>In this step I have made the image path dictionary by joining the folder path from base directory and merge the images in jpg format from both the folders <strong>HAM10000_images_part1.zip</strong> and <strong>HAM10000_images_part2.zip.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fee28a271a1eb9274739019cd7d8553c/href">https://medium.com/media/fee28a271a1eb9274739019cd7d8553c/href</a></iframe><h3>Step 3 : Reading &amp; Processing data</h3><p>In this step we have read the csv by joining the path of image folder which is the base folder where all the images are placed named base_skin_dir. After that we made some new columns which is easily understood for later reference such as we have made column path which contains the image_id, cell_type which contains the short name of lesion type and at last we have made the categorical column cell_type_idx in which we have categorize the lesion type in to codes from 0 to 6</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2439af06bfc28d15ba7a6d62446ebe9a/href">https://medium.com/media/2439af06bfc28d15ba7a6d62446ebe9a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*yaStzaaAnSAp98iL_otmCA.png" /></figure><h3>Step 4 : EDA</h3><p>In this step we will explore different features of the dataset , their distributions and actual counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*fmhFpc-ADix1LpR6jDI4XQ.png" /></figure><p>As we can see from the above plot, <strong>Melanocytic Nevi</strong> has the highest distribution of image samples which is the practical problem in real world dataset. Ideally for accurate classification the deep learning CNN model requires equal or nearly equal proportion of different classes of data. But if one class has majority of data sample then the model will not able to properly learn the pattern of other classes. So, in this situation when model tend to classify other classes which have minority presence then it lacks in accuracy and recall. One solution for this is to supply more data for training to make the model work properly in practical scenario.</p><p>Plotting of Technical Validation field (ground truth) which is dx_type to see the distribution of its 4 categories which are listed below :<br><strong>1. Histopathology(Histo):</strong> Histopathologic diagnoses of excised lesions have been performed by specialized dermatopathologists. <br><strong>2. Confocal:</strong> Reflectance confocal microscopy is an in-vivo imaging technique with a resolution at near-cellular level , and some facial benign with a grey-world assumption of all training-set images in Lab-color space before and after manual histogram changes.<br><strong>3. Follow-up:</strong> If nevi monitored by digital dermatoscopy did not show any changes during 3 follow-up visits or 1.5 years biologists accepted this as evidence of biologic benignity. Only nevi, but no other benign diagnoses were labeled with this type of ground-truth because dermatologists usually do not monitor dermatofibromas, seborrheic keratoses, or vascular lesions. <br><strong>4. Consensus:</strong> For typical benign cases without histopathology or followup biologists provide an expert-consensus rating of authors PT and HK. They applied the consensus label only if both authors independently gave the same unequivocal benign diagnosis. Lesions with this type of groundtruth were usually photographed for educational reasons and did not need further follow-up or biopsy for confirmation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*PVYVtYNEGPItXe1yj8k55Q.png" /></figure><p>Now we will see in which part of the body people usually have higher distribution of skin cancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*k7NhMQ_8lMEGI4vQQOlmmA.png" /></figure><p>It seems from the above plot, back , lower extremity,trunk and upper extremity are heavily compromised regions of skin cancer.</p><p>Now, checking the distribution of Age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*l9JRYIHe3irurXk4Rmnr4A.png" /></figure><p>It seems that there are larger instances of patients having age from 30 to 60.</p><p>Lets see the distribution of males and females.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*FefFr1hkani3PLl8CHWYhA.png" /></figure><p>It seems males have higher tendency of skin cancer than females.</p><h3>Step 5: Loading and resizing of images</h3><p>In this step images will be loaded into the column named image from the image path from the image folder. We also resize the images as the original dimension of images are 450 x 600 x3 which TensorFlow can’t handle, so that’s why we resize it into 100 x 75. As this step resize all the 10015 images dimensions into 100x 75 so be patient it will take some time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*n6CLAHvtY6j8SOFrNBobDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*6F_D1YI2M9hZi44N5deH0A.png" /></figure><p><strong>As we can see image column has been added in its color format code</strong></p><p>Most interesting part its always better to see sample of images Below we will show images of each cancer type with the following code to show 5 sample images of each cancer type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ea8613b68a10486fc7f0f66a346846/href">https://medium.com/media/b1ea8613b68a10486fc7f0f66a346846/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*K0k1t_FNh0U7WPzKh8LVuA.png" /></figure><p>After that we will segregate features and target variables using the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2bf54aee21968ff6d485c6c97e8edad/href">https://medium.com/media/d2bf54aee21968ff6d485c6c97e8edad/href</a></iframe><h3>Step 6 : Train Test Split</h3><p>In this step we have splitted the dataset into training and testing set in the ratio of 80:20 ratio with some randomness. It is always better to split the dataset randomly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2b9349c5d1feba737f4ce3a708ef10a/href">https://medium.com/media/c2b9349c5d1feba737f4ce3a708ef10a/href</a></iframe><h3>Step 7 : Normalization</h3><p>I chooses to normalize the <strong>x_train, x_test</strong> by subtracting from their <strong>mean</strong> values and then dividing by their <strong>standard deviation </strong>which is also known as<strong> z-score normalization.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c66ea9dec178b7136ded825272164f62/href">https://medium.com/media/c66ea9dec178b7136ded825272164f62/href</a></iframe><h4>Step 8: Label Encoding</h4><p>In this step we will encode labels which are 7 different classes of skin cancer types from 0 to 6. We need to encode these labels to <strong>one hot vectors.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/396e87524fdcc667adeea84f13a68c7d/href">https://medium.com/media/396e87524fdcc667adeea84f13a68c7d/href</a></iframe><h3>Step 9 : Splitting training and validation split</h3><p>I chooses to split the train set in two parts : a small fraction (10%) became the validation set which the model is evaluated and the rest (90%) is used to train the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e71a2ec7bde09809e3283b6cdf0ced19/href">https://medium.com/media/e71a2ec7bde09809e3283b6cdf0ced19/href</a></iframe><p>Now important part after this step is to reshape the images before fitting it into the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2a82896a58c09c2ec58612848fb11c1/href">https://medium.com/media/d2a82896a58c09c2ec58612848fb11c1/href</a></iframe><h3>Step 10: Model Building (CNN)</h3><p>In this step I will explain the whole architecture of my CNN model in short it is defined as follows :</p><p><strong>Input -&gt; [[Conv2D -&gt; relu] *2 -&gt; MaxPool2D -&gt; Dropout]*2 -&gt; Flatten -&gt; Dense -&gt; Dropout -&gt; Output</strong></p><p>Full description of model are as follows :</p><p>I used the <strong>Keras Sequential</strong> API, where you have just to add one layer at a time, starting from the input.</p><p>The first is the convolutional (Conv2D) layer. It is like a set of learnable filters. I choosed to set <strong>32 filters</strong> for the two firsts conv2D layers and <strong>64 filters</strong> for the two last ones. Each filter transforms a part of the image (defined by the kernel size) using the kernel filter. The kernel filter matrix is applied on the whole image. Filters can be seen as a transformation of the image.</p><p>The CNN can isolate features that are useful everywhere from these transformed images (feature maps).</p><p>The second important layer in CNN is the pooling (<strong>MaxPool2D</strong>) layer. This layer simply acts as a downsampling filter. It looks at the 2 neighboring pixels and picks the maximal value. These are used to reduce computational cost, and to some extent also reduce overfitting. We have to choose the pooling size (i.e the area size pooled each time) more the pooling dimension is high, more the downsampling is important.</p><p>Combining convolutional and pooling layers, CNN are able to combine local features and learn more global features of the image.</p><p><strong>Dropout</strong> is a regularization method, where a proportion of nodes in the layer are randomly ignored (setting their wieghts to zero) for each training sample. This drops randomly a propotion of the network and forces the network to learn features in a distributed way. This technique also improves generalization and reduces the overfitting.</p><p><strong>‘relu’</strong> is the rectifier (activation function max(0,x). The rectifier activation function is used to add non linearity to the network.</p><p>The Flatten layer is use to convert the final feature maps into a one single 1D vector. This flattening step is needed so that you can make use of fully connected layers after some convolutional/maxpool layers. It combines all the found local features of the previous convolutional layers.</p><p>In the end I used the features in two fully-connected (Dense) layers which is just artificial an neural networks (ANN) classifier. In the last layer(Dense(10,activation=”softmax”)) the net outputs distribution of probability of each class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a68dbaaed3a37c737e0aab9d0a9faf62/href">https://medium.com/media/a68dbaaed3a37c737e0aab9d0a9faf62/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*HaChGOCl_cdYwaPo92M9Ig.png" /></figure><h3>Step 11: Setting Optimizer and Annealer</h3><p>Once our layers are added to the model, we need to set up a score function, a loss function and an optimization algorithm. We define the loss function to measure how poorly our model performs on images with known labels. It is the error rate between the observed labels and the predicted ones. We use a specific form for categorical classifications (&gt;2 classes) called the “<strong>categorical_crossentropy</strong>”. The most important function is the optimizer. This function will iteratively improve parameters (filters kernel values, weights and bias of neurons …) in order to minimize the loss. I chooses <strong>Adam optimizer </strong>because it combines the advantages of two other extensions of stochastic gradient descent. Specifically:</p><ol><li><strong>Adaptive Gradient Algorithm (AdaGrad)</strong> that maintains a per-parameter learning rate that improves performance on problems with sparse gradients (e.g. natural language and computer vision problems).</li><li><strong>Root Mean Square Propagation (RMSProp)</strong> that also maintains per parameter learning rates that are adapted based on the average of recent magnitudes of the gradients for the weight (e.g. how quickly it is changing). This means the algorithm does well on online and non-stationary problems (e.g. noisy).</li></ol><p>Adam realizes the benefits of both AdaGrad and RMSProp.</p><p>Adam is a popular algorithm in the field of deep learning because it achieves good results fast.</p><p>The metric function “<strong>accuracy</strong>” is used is to evaluate the performance our model. This metric function is similar to the loss function, except that the results from the metric evaluation are not used when training the model (only for evaluation).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cd24175386da60451a5bbc5bcb3d446/href">https://medium.com/media/3cd24175386da60451a5bbc5bcb3d446/href</a></iframe><p>In order to make the optimizer converge faster and closest to the global minimum of the loss function, i used an annealing method of the learning rate (LR).</p><p>The LR is the step by which the optimizer walks through the ‘loss landscape’. The higher LR, the bigger are the steps and the quicker is the convergence. However the sampling is very poor with an high LR and the optimizer could probably fall into a local minima.</p><p>Its better to have a decreasing learning rate during the training to reach efficiently the global minimum of the loss function.</p><p>To keep the advantage of the fast computation time with a high LR, I have decreased the LR dynamically every X steps (epochs) depending if it is necessary (when accuracy is not improved).</p><p>With the <strong>ReduceLROnPlateau</strong> function from <strong>Keras.callbacks</strong>, I choose to reduce the LR by half if the accuracy is not improved after 3 epochs.</p><h3>Data Augmentation</h3><p>It is the optional step. In order to avoid overfitting problem, we need to expand artificially our HAM 10000 dataset. We can make your existing dataset even larger. The idea is to alter the training data with small transformations to reproduce the variations</p><p>Approaches that alter the training data in ways that change the array representation while keeping the label the same are known as data augmentation techniques. Some popular augmentations people use are <strong>grayscales</strong>, <strong>horizontal flips</strong>, <strong>vertical flips, random crops, color jitters, translations, rotations,</strong> and much more.</p><p>By applying just a couple of these transformations to our training data, we can easily double or triple the number of training examples and create a very robust model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4211e04663cf76ae1899a19da5cd1190/href">https://medium.com/media/4211e04663cf76ae1899a19da5cd1190/href</a></iframe><p>For the data augmentation, I have Randomly rotate some training images by <strong>10 degrees </strong>Randomly <strong>Zoom by 10%</strong> some training images Randomly shift images horizontally by 10% of the width <strong>Randomly shift</strong> images vertically by 10% of the height Once our model is ready, we fit the training dataset .</p><h3>Step 12: Fitting the model</h3><p>In this step, finally I fit the model into training set i.e., x_train, y_train. In this step I have choosen the batch size of 10 and 50 epochs. Reason for choosing such a small batch size is model will train more efficiently by closing watching small number of images at a time and I have tried 50 epochs to give the model sufficient iterations to train.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f18c6279360d370283021b67dfe6dc8b/href">https://medium.com/media/f18c6279360d370283021b67dfe6dc8b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*Rrqu4fU4Zvi-nBtNOsrH1g.png" /></figure><h3>Step 13: Model Evaluation</h3><p>In this step we will check the testing and validation accuracy of our model,plot confusion matrix and also check the miss classified images count of each cancer type to get the view how much robust our model is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/434e727fd53e63ead7c5e666ed744fcb/href">https://medium.com/media/434e727fd53e63ead7c5e666ed744fcb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*RbDu8ifa8TBk-SosAjWKsQ.png" /></figure><p>So our model’s accuracy is around 76.48% which is not bad, remember it is a real medical dataset and it is still under research how we will achieve more than 90% accuracy. But, with further optimization such as increasing epochs to 100, hit and trial with some other activation functions such as rmsprop,sgd etc we can achieve around 80 to 82 % accuracy.</p><p>Now we will plot model history to view models performance after 10 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*tIGyCW-O5CjBgk6sI8P8Hg.png" /></figure><p>Plotting confusion matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*NhRiK5wK1if2mgQVmMymkQ.png" /></figure><p>As we can see 4th number of cancer type which is <strong>Actinic keratoses </strong>has highest number of correct prediction i.e., <strong>518.</strong></p><p>Now we will see which of the categories got unclassified by our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*ZjjPvJYiAysDfCu-8Gu7WA.png" /></figure><h3>Conclusion</h3><p>It seems our model has maximum number of incorrect predictions for Basal cell carcinoma which has code 3, then second most missclassified type is Vascular lesions code 5 then Melanocytic nevi code 0 where as Actinic keratoses code 4 has least misclassified type.</p><p>We can also further tune our model to easily achieve the accuracy above 80% and I think still this model is efficient in comparison to detection with human eyes having <strong>76.48%</strong> accuracy.</p><p>Further we can use host our model into Google cloud or AWS using <strong>FLASK</strong> or we can also use <strong>tensorflow.js</strong> to get the prediction from the model on mobile browser because <strong>tensorflow.js</strong> is very lightweight framework to host deep learning models.</p><p>This post is truly inspired by my own kaggle kernel where I have actually train and implemented this model.</p><p><strong>If you really like this article kindly clap it and follow me!</strong></p><p><strong>You can check my </strong><a href="https://www.kaggle.com/sid321axn"><strong>Kaggle profile</strong></a><strong> or you can also connect with me on </strong><a href="https://www.linkedin.com/in/msid-0289/"><strong>LinkedIn!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=347d47868196" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>