<?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 Harsh Mishra on Medium]]></title>
        <description><![CDATA[Stories by Harsh Mishra on Medium]]></description>
        <link>https://medium.com/@harshmishraandheri?source=rss-20163b97eba3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*77yVY_BvgZnKTQvEx9ePEA.png</url>
            <title>Stories by Harsh Mishra on Medium</title>
            <link>https://medium.com/@harshmishraandheri?source=rss-20163b97eba3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:35:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshmishraandheri/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[Why Transfer Learning is a Game-Changer for AI Development]]></title>
            <link>https://harshmishraandheri.medium.com/why-transfer-learning-is-a-game-changer-for-ai-development-5b7005e18a35?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b7005e18a35</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 07:17:24 GMT</pubDate>
            <atom:updated>2023-03-30T21:06:26.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Lu0eTnGGDHNH2GE.png" /></figure><p>Hello people, I hope everyone is doing well. Today in this blog we will learn about transfer learning and how can you implement it using TensorFlow.</p><p>To train a machine learning model or a neural network that can yield the best results requires what?</p><ol><li>A large amount of Data</li><li>Enough training time</li><li>Hardware and Software infrastructure</li></ol><p>What if any of the above is missing? How can we train a neural network without having an ample amount of data, even if you have it can you afford to train a model for months? do you have that kind of supercomputer at your home or office and that time? Most of the time the answer to all these questions would be no… So what can we do?</p><p>We can use TRANSFER LEARNING.</p><h3><strong>What is Transfer Learning?</strong></h3><p>According to Wikipedia, “Transfer learning is a research problem in machine learning that focuses on storing knowledge gained while solving one problem and applying it to a different but related problem.”</p><p>Let me explain this in simple words. The name transfer learning comes from the process of using the learning from one problem to solve another. Learning is nothing but just getting the value of weights and biases for a neural network that gives you the desired result. Every epoch we change our weights and biases in the pursuit of reaching the truth value and we call that training (learning in our case). This takes time and requires huge data. What if we use the weights and biases of another network that is already trained on huge data, and that data is similar to ours? This is exactly what we call transfer learning. we use an already-trained model as a starting point and fine-tune it for our specific task. This approach allows us to train models on smaller datasets and achieve higher accuracy.</p><p>To understand this let’s take an example of a widely used neural network, <strong>CNN (Convolutional Neural Network)</strong></p><p>CNN is made of two parts:</p><ol><li>C — Convolution</li><li>NN — Neural Network</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lCC6JL3A6IU7FE0F.png" /></figure><p>The most important part of training is feature extraction which is done by the convolutional part of the CNN. The process although automatic is very time-consuming and computationally heavy. Also, you require a huge amount of image data to extract accurate features from them. Then Neural Network in CNN is just for the prediction part. Once your Convolutional has done the feature extraction your neural network will take those features’ output to make a decision.</p><p>In transfer learning, we skip the feature extraction part as we are using a <strong>pre-trained model</strong>. In the pre-trained model, we have already trained a model on a different huge dataset. We are using its convolutional layers knowing that they are trained well to identify features from the images and we add a neural network in front of that pre-trained convolutional layers. So when we train this model, we only train the neural network we added which saves us huge time, and also the need to have huge data. Whatever data we have would be sufficient to just train the neural network which can simply make a decision of predicting a class.</p><p>This is how transfer learning works. You can get a pre-trained neural network architecture on huge data and use it directly in any of your projects and get outstanding results with less amount of time and data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*aVJnor72jDxgzH2d.png" /></figure><p>The benefit of using transfer learning is that the pre-trained model already has learned important features that are useful for our new task. By fine-tuning the model on our specific dataset, we can adapt the pre-trained features to our specific problem, leading to higher accuracy and faster training times.</p><h3><strong>Tensorflow Keras Implementation</strong></h3><blockquote>Also all the code written in this blog is available in colab notebook: <a href="https://colab.research.google.com/drive/1U0Qt0wNMZr1_osgHTgAXmPQZeLqaYWS-?usp=sharing">https://colab.research.google.com/drive/1U0Qt0wNMZr1_osgHTgAXmPQZeLqaYWS-?usp=sharing</a></blockquote><blockquote>Link for the dataset used- <a href="https://www.kaggle.com/datasets/muhammadardiputra/potato-leaf-disease-dataset">https://www.kaggle.com/datasets/muhammadardiputra/potato-leaf-disease-dataset</a></blockquote><p>Here, we are creating a CNN model to classify three types of potato leaf: Healthy, Early Blight, and Late Blight. Early blight and late blight is a very common diseases found in potato crops.</p><pre><br>#importing necessary libraries<br>import tensorflow as tf<br>from tensorflow.keras import models, layers<br>import matplotlib.pyplot as plt<br>from keras.models import Model<br>from keras.layers import Input, Conv2D, MaxPooling2D, AveragePooling2D, Flatten, GlobalAveragePooling2D, Dense, Dropout<br>from keras.layers.merge import concatenate<br><br>#initializing some variables<br>IMAGE_SIZE = 256<br>BATCH_SIZE = 32<br>CHANNELS = 3<br>EPOCHS = 50<br><br>#importing training, testing and validation data from drive<br><br>train_ds = tf.keras.preprocessing.image_dataset_from_directory(<br>    &quot;/content/drive/MyDrive/DL sem7/Potato/Train&quot;,<br>    shuffle = True,<br>    image_size = (IMAGE_SIZE, IMAGE_SIZE),<br>    batch_size = BATCH_SIZE<br>)<br>val_ds = tf.keras.preprocessing.image_dataset_from_directory(<br>    &quot;/content/drive/MyDrive/DL sem7/Potato/Valid&quot;,<br>    shuffle = True,<br>    image_size = (IMAGE_SIZE, IMAGE_SIZE),<br>    batch_size = BATCH_SIZE<br>)<br>test_ds = tf.keras.preprocessing.image_dataset_from_directory(<br>    &quot;/content/drive/MyDrive/DL sem7/Potato/Test&quot;,<br>    shuffle = True,<br>    image_size = (IMAGE_SIZE, IMAGE_SIZE),<br>    batch_size = BATCH_SIZE<br>)<br><br>&#39;&#39;&#39;<br>These layers are for preprocessing and we will use it later while <br>model building. One is to resize the image and other divides<br>the size of 256 by 255 to get a number between 0 and 1<br>&#39;&#39;&#39;<br>resize_and_rescale = tf.keras.Sequential([<br>    layers.experimental.preprocessing.Resizing(IMAGE_SIZE,IMAGE_SIZE),<br>    layers.experimental.preprocessing.Rescaling(1.0/255)<br>])<br><br>&#39;&#39;&#39;<br>Data Augmentation is needed when we have less data, this boosts <br>the accuracy of our model by augmenting the data.<br>&#39;&#39;&#39;<br>data_augmentation = tf.keras.Sequential([<br>  layers.experimental.preprocessing.RandomFlip(&quot;horizontal_and_vertical&quot;),<br>  layers.experimental.preprocessing.RandomRotation(0.2),<br>])<br><br>input_shape = (IMAGE_SIZE, IMAGE_SIZE, CHANNELS)<br><br># lets start model building<br><br>resnet_model = tf.keras.models.Sequential()<br><br>&#39;&#39;&#39; this is the pre-trained mode resnet50 model. you can see that include_top<br>is set to false as we would be adding our own neural network on top of the <br>pre-trained convolutions of resnet50. Weights is set to imagenet (the dataset<br>on which this model is pre-trained)<br>&#39;&#39;&#39;<br>pretrained_model = tf.keras.applications.ResNet50(<br>                   include_top=False,<br>                   input_shape=input_shape,<br>                   pooling=&#39;avg&#39;,<br>                   classes=3,<br>                   weights=&#39;imagenet&#39;)<br>for layer in pretrained_model.layers:<br>        layer.trainable=False<br># lets add the neural network on top to complete the CNN model<br>resnet_model.add(resize_and_rescale)<br>resnet_model.add(data_augmentation)<br>resnet_model.add(pretrained_model)<br>resnet_model.add(layers.Flatten())<br>resnet_model.add(layers.Dense(512, activation=&#39;relu&#39;))<br>resnet_model.add(layers.Dense(3, activation=&#39;softmax&#39;))<br>resnet_model.build(input_shape = (32, 256, 256, 3))<br><br>resnet_model.compile(<br>    optimizer=&#39;adam&#39;,<br>    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),<br>    metrics=[&#39;accuracy&#39;]<br>)<br><br>history = resnet_model.fit(<br>    train_ds,<br>    batch_size=BATCH_SIZE,<br>    validation_data=val_ds,<br>    verbose=1,<br>    epochs=50,<br>)</pre><h3><strong>Popular Use Cases of Transfer Learning:</strong></h3><ol><li>Image Classification: Transfer learning has been widely used in image classification tasks. For example, a pre-trained model such as ResNet or VGG can be used as a starting point and fine-tuned on a specific dataset to classify images.</li><li>Natural Language Processing: Transfer learning has also been used in natural language processing tasks such as sentiment analysis, text classification, and language modeling. A pre-trained model such as BERT or GPT can be used as a starting point and fine-tuned on a specific dataset to perform these tasks.</li><li>Speech Recognition: Transfer learning has been used in speech recognition tasks where a pre-trained model such as DeepSpeech can be fine-tuned on a specific dataset to recognize speech.</li></ol><blockquote>So, this is the end of our project here. We used a pre-trained CNN architecture and understood the concept of transfer learning. And that is it for today guys.</blockquote><blockquote>I hope you guys got to learn something new and enjoyed this blog. If you do then like it, and share it with your friends. Take care. keep learning.</blockquote><blockquote>You could also reach me through my LinkedIn account- <a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/">https://www.linkedin.com/in/harsh-mishra-4b79031b3/</a></blockquote><p><a href="https://mlearning.substack.com/about"><strong>BECOME a WRITER at MLearning.ai</strong></a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b7005e18a35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first six months of learning Deep Learning. You can get started too!!!]]></title>
            <link>https://harshmishraandheri.medium.com/my-first-six-months-of-learning-deep-learning-you-can-get-started-too-7a8f376ec601?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a8f376ec601</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[journey]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 15:12:42 GMT</pubDate>
            <atom:updated>2022-10-14T15:41:15.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*CZ4fAkuin4IF2396.png" /></figure><p>Hello guys I hope you are doing fine. I am learning deep learning from about nearly half a dozen months now so I though it would be cool to share my experience with you all. In this blog I will be sharing all the experiences I got in the last six months while learning and implementing deep learning. I will be sharing all the useful links and resources of my knowledge that helped me a lot and may help you too. Also in the end I would be telling how you can get started in this exciting field of computer science.</p><h3>How it started?</h3><p>I have been learning and working in the domain of Data i.e. Data Science, Data Analytics and Machine Learning from the past 2.5 years and it all started with the outbreak of the pandemic.</p><p>In the course of time I had already heard about deep learning lot of times but somehow I was able to develop a feeling that it is something very difficult and very challenging and implementing it is not feasible as a student and by all this I always hesitated to get into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hFUklptFxCOrG55j.jpg" /></figure><p>One day I was scrolling through my YouTube feed and I saw a series based on AI which had RDJ as its host. The name of the series is “<a href="https://www.youtube.com/watch?v=UwsrzCVZAb8&amp;list=PLjq6DwYksrzz_fsWIpPcf6V7p2RNAneKc">Age of AI</a>”. There are all together 9 episodes and each talking about different applications of AI (majorly Deep Learning) in real world and how it is shaping the future. After I completed watching the series in a single weekend, I knew what’s the next thing I had to learn… Such was the impact</p><h3>“Passion”</h3><p>After watching the series on YouTube, I was highly motivated but that is not enough. I have seen many people and been in that position myself too that you are learning a technology not because you are passionate about it but just because everyone around you is learning that, this is very common in university and college students.</p><p>Fortunately as I kept learning about deep learning my interest kept increasing and very soon I was too intrigued to find myself ‘passionate’ enough to continue to learn and learn in this field.</p><h3>What I learned?</h3><p>I started learning about deep learning from a superb book of deep learning for absolute beginners — ‘<a href="https://www.amazon.in/Deep-Learning-Python-Fran%C3%A7ois-Chollet-ebook/dp/B0977ZRV1J/ref=sr_1_3?crid=2VSVSFXIGKT1A&amp;keywords=Deep+Learning+with+Python&amp;qid=1665756138&amp;qu=eyJxc2MiOiIyLjg2IiwicXNhIjoiMi4wMCIsInFzcCI6IjEuNjcifQ%3D%3D&amp;sprefix=deep+learning+with+python%2Caps%2C718&amp;sr=8-3">Deep Learning with Python</a>’ by <a href="https://fchollet.com/">Francois Chollet</a>. Now first of all I am a big fan of this book and I would recommend it to everyone, it’s the best resource to start with deep learning.</p><p>Francois Chollet is the author of very famous deep learning library named ‘<a href="https://keras.io/">Keras</a>’, so I have developed a bias for keras (since there is debate in the community about Keras vs Pytorch, which is better), so if you check my other projects on my <a href="https://github.com/HarshMishra2002">github</a>, every DL project is implemented using Keras. Keras is very simple and super fun to learn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ak8LM_yB1NRMRFex.png" /></figure><p>Apart from that I learned basics of Neural Network and different types of NN like ANN, CNN, RNN, LSTM, GRU and GANs. Also getting a brief knowledge on building blocks of deep learning like activation functions, loss functions, optimizers, transfer learning etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l9mGBj-gn8PmuLT3.png" /></figure><p>After having all this information and after having a hands-on experience I understood that CNN was the type of NN that I really worked to enjoy with which led me to work more and more on CNN projects and its applications.</p><h3>Role of DeepMind company in my journey:</h3><p><a href="https://www.deepmind.com/">DeepMind</a> company is a DL research organization which was bought by google in 2014. <a href="https://www.deepmind.com/research/highlighted-research/alphago">AlphaGo</a> and <a href="https://alphafold.ebi.ac.uk/">AlphaFold</a> is one of the best work done in this field by any research organization in this world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AzS7Q08lxrLJyKT9.jpeg" /></figure><p>Their <a href="https://www.youtube.com/c/DeepMind">YouTube</a> channel has also been a source of inspiration for me. The people working in their campus and the work culture they have is super inspiring. I recommend everyone to visit their YouTube channel once.</p><h3>Resources / Content Creators / YT channels:</h3><p>Here is the list of resources that helped me a lot and might help you to.</p><ol><li>‘<a href="https://www.amazon.in/Deep-Learning-Python-Fran%C3%A7ois-Chollet-ebook/dp/B0977ZRV1J/ref=sr_1_3?crid=2VSVSFXIGKT1A&amp;keywords=Deep+Learning+with+Python&amp;qid=1665756138&amp;qu=eyJxc2MiOiIyLjg2IiwicXNhIjoiMi4wMCIsInFzcCI6IjEuNjcifQ%3D%3D&amp;sprefix=deep+learning+with+python%2Caps%2C718&amp;sr=8-3">Deep Learning with Python</a>’ by <a href="https://fchollet.com/">Francois Chollet</a>.</li><li><a href="https://www.youtube.com/c/lexfridman">Lex Fridman YT channel</a> (MIT DL Professor)</li><li><a href="https://www.youtube.com/c/CampusX-official">CampusX YT channel</a></li><li><a href="https://www.youtube.com/c/codebasics">CodeBasics YT channel</a></li><li><a href="https://www.youtube.com/user/krishnaik06">Krish Naik YT channel</a></li><li><a href="https://www.youtube.com/c/DeepMind">DeepMind YT channel</a></li><li><a href="https://www.youtube.com/c/TheAIEpiphany">Aleksa Gordić — The AI Epiphany</a></li></ol><h3>How you can get started too:</h3><h4>Pre-requisites:</h4><ol><li>Maths</li><li>Statistics</li><li>Python</li><li>Machine Learning</li></ol><p>Also if you follow the above resources that I have mentioned, you could start in this amazing field too.</p><blockquote>I hope you guys got to learn something new and enjoyed this blog. If you do like it than share it with your friends. Take care. keep learning.</blockquote><blockquote>You could also reach me through my Linkedin account- <a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/">https://www.linkedin.com/in/harsh-mishra-4b79031b3/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a8f376ec601" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Olympic Data Analyzer Web App : End to End Streamlit Project]]></title>
            <link>https://harshmishraandheri.medium.com/olympic-data-analyzer-web-app-end-to-end-streamlit-project-db84fb4d1ff4?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/db84fb4d1ff4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[olympics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[streamlit-app]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Sat, 12 Feb 2022 11:55:06 GMT</pubDate>
            <atom:updated>2022-02-12T11:57:29.971Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Olympic Data Analyzer Web App : End to End Streamlit Project</strong></h3><p>Hello people, I hope everyone is doing well. Today in this blog we will be making a Olympic Analyzer Web App using Streamlit.</p><p>Streamlit is an open source app framework in Python language. It helps us <strong>create web apps for data science and machine learning in a short time</strong>. It is compatible with major Python libraries such as scikit-learn, Keras, PyTorch, SymPy(latex), NumPy, pandas, Matplotlib etc.</p><blockquote><em>Also all the code written in this blog is available in my github : </em><a href="https://github.com/HarshMishra2002/olympic_data_analysis">https://github.com/HarshMishra2002/olympic_data_analysis</a></blockquote><blockquote><em>The project is deployed using heroku: </em><a href="https://oly-analysis.herokuapp.com/">https://oly-analysis.herokuapp.com/</a></blockquote><blockquote><em>Link for the dataset used- </em><a href="https://www.kaggle.com/heesoo37/120-years-of-olympic-history-athletes-and-results">https://www.kaggle.com/heesoo37/120-years-of-olympic-history-athletes-and-results</a></blockquote><p>So lets start. we will be using python programming language for all the data analysis and pycharm would be used as IDE.</p><p>We would be creating 3 files in our project</p><ol><li>preprocessor.py : The input we take is olympics data so we need to do some preprocessing and get an specific dataframe out of it. This process would be done in this file.</li><li>app.py : This would be the main file where we would be creating the streamlit app.</li><li>helper.py : We would be making some functions in this file that would be used in the main app.py file.</li></ol><p>First lets create a stramlit app.</p><p>In app.py write the following code to create a streamlit app</p><pre>import streamlit as st</pre><p>Now we will import the dataset</p><pre>df = pd.read_csv(&quot;athlete_events.csv&quot;)<br>region_df = pd.read_csv(&quot;noc_regions.csv&quot;)</pre><p>Now we have got the data in variable named “df”. After that we will apply the preprocess function of the preprocessor.py file. So lets write the code of preprocessor.py file first</p><p>In preprocessor.py</p><pre>import pandas as pd<br><br><br>def perprocess(df, region_df):<br>    #filtering for summer olymppics<br>    df = df[df[&#39;Season&#39;] == &quot;Summer&quot;]<br>    #merge with region_df<br>    df = df.merge(region_df, on = &quot;NOC&quot;, how = &quot;left&quot;)<br>    #droping duplicates<br>    df.drop_duplicates(inplace=True)<br>    #one hot encoding medals<br>    df = pd.concat([df, pd.get_dummies(df[&quot;Medal&quot;])], axis=1)<br>    return df</pre><p>This is the end of preprocessor.py. Now we will use this in the main file app.py</p><p>In app.py</p><pre>df = preprocessor.perprocess(df, region_df)<br># creating a sidebar <br>st.sidebar.title(&quot;Olympics Analysis&quot;)<br>user_menu = st.sidebar.radio(<br>    &#39;Select an option&#39;,<br>    (&#39;Medal Tally&#39;, &#39;Overall Analysis&#39;, &#39;Country-wise Analysis&#39;, &#39;Athlete wise Analysis&#39;)<br>)</pre><p>Now we will create a function which will fetch the medal tally in helper.py file. We will provide the dataset, year and the country as an input and the function will return the number of medals of each type accordingly.</p><p>In helper.py</p><pre>def fetch_medal_tally(df, year, country):<br>    medal_df = df.drop_duplicates(subset=[&#39;Team&#39;, &#39;NOC&#39;, &#39;Games&#39;, &#39;Year&#39;, &#39;City&#39;, &#39;Sport&#39;, &#39;Event&#39;, &#39;Medal&#39;])<br>    flag = 0<br>    if year == &#39;Overall&#39; and country == &#39;Overall&#39;:<br>        temp_df = medal_df<br>    if year == &#39;Overall&#39; and country != &#39;Overall&#39;:<br>        flag = 1<br>        temp_df = medal_df[medal_df[&#39;region&#39;] == country]<br>    if year != &#39;Overall&#39; and country == &#39;Overall&#39;:<br>        temp_df = medal_df[medal_df[&#39;Year&#39;] == int(year)]<br>    if year != &#39;Overall&#39; and country != &#39;Overall&#39;:<br>        temp_df = medal_df[(medal_df[&#39;Year&#39;] == year) &amp; (medal_df[&#39;region&#39;] == country)]<br><br>    if flag == 1:<br>        x = temp_df.groupby(&#39;Year&#39;).sum()[[&#39;Gold&#39;, &#39;Silver&#39;, &#39;Bronze&#39;]].sort_values(&#39;Year&#39;).reset_index()<br>    else:<br>        x = temp_df.groupby(&#39;region&#39;).sum()[[&#39;Gold&#39;, &#39;Silver&#39;, &#39;Bronze&#39;]].sort_values(&#39;Gold&#39;, ascending=False).reset_index()<br><br>    x[&#39;total&#39;] = x[&#39;Gold&#39;] + x[&#39;Silver&#39;] + x[&#39;Bronze&#39;]<br><br>    x[&#39;Gold&#39;] = x[&#39;Gold&#39;].astype(&#39;int&#39;)<br>    x[&#39;Silver&#39;] = x[&#39;Silver&#39;].astype(&#39;int&#39;)<br>    x[&#39;Bronze&#39;] = x[&#39;Bronze&#39;].astype(&#39;int&#39;)<br>    x[&#39;total&#39;] = x[&#39;total&#39;].astype(&#39;int&#39;)<br><br>    return x</pre><pre># the below function is to simply get the list of countries participated in Olympics and years in which it was conducted. </pre><pre>def country_year_list(df):<br>    years = df[&#39;Year&#39;].unique().tolist()<br>    years.sort()<br>    years.insert(0, &#39;Overall&#39;)<br><br>    country = np.unique(df[&#39;region&#39;].dropna().values).tolist()<br>    country.sort()<br>    country.insert(0, &#39;Overall&#39;)<br><br>    return years, country</pre><p>Now we will use this function in app.py file. If the user has chosen medal tally in sidebar than he has to select the year and country from dropdown and the above function will give the medal tally.</p><p>In app.py</p><pre>if user_menu == &#39;Medal Tally&#39;:<br>    st.sidebar.header(&quot;Medal Tally&quot;)<br><br>    years, country = helper.country_year_list(df)<br><br>    selected_years = st.sidebar.selectbox(&quot;Select Years&quot;, years)<br>    selected_country = st.sidebar.selectbox(&quot;Select Country&quot;, country)<br><br>    medal_tally_df = helper.fetch_medal_tally(df, selected_years, selected_country)<br>    if selected_years == &#39;Overall&#39; and selected_country == &#39;Overall&#39;:<br>        st.title(&quot;Overall Tally&quot;)<br>    if selected_years != &#39;Overall&#39; and selected_country == &quot;Overall&quot;:<br>        st.title(&quot;Medal tally in &quot; + str(selected_years) + &quot; Olympics&quot;)<br>    if selected_years == &#39;Overall&#39; and selected_country != &quot;Overall&quot;:<br>        st.title(&quot;Medal tally of &quot; + str(selected_country))<br>    if selected_years != &#39;Overall&#39; and selected_country != &quot;Overall&quot;:<br>        st.title(&quot;Medal tally of &quot; + str(selected_country) + &quot; in &quot; + str(selected_years) + &quot; Olympics&quot;)<br><br>    st.table(medal_tally_df)</pre><p>Now in helper.py file we will add two more functions, one to get the data (like number of countries and athletes participating, etc) over time and other to get most successful atheltes in a soprt</p><p>In helper.py</p><pre>def data_over_time(df, col):<br>    nations_over_time = df.drop_duplicates([&#39;Year&#39;, col])[&#39;Year&#39;].value_counts().reset_index().sort_values(&#39;index&#39;)<br>    nations_over_time.rename(columns={&#39;index&#39;: &#39;Edition&#39;, &#39;Year&#39;: col}, inplace=True)<br>    return nations_over_time<br><br><br>def most_successful(df, sport):<br>    temp_df = df.dropna(subset=[&#39;Medal&#39;])<br><br>    if sport != &#39;Overall&#39;:<br>        temp_df = temp_df[temp_df[&#39;Sport&#39;] == sport]<br><br>    x = temp_df[&#39;Name&#39;].value_counts().reset_index().head(15).merge(df, left_on=&#39;index&#39;, right_on=&#39;Name&#39;, how=&#39;left&#39;)[<br>        [&#39;index&#39;, &#39;Name_x&#39;, &#39;Sport&#39;, &#39;region&#39;]].drop_duplicates(&#39;index&#39;)<br><br>    x.rename(columns={&#39;index&#39;: &#39;Name&#39;, &#39;Name_x&#39;: &#39;Medals&#39;}, inplace=True)<br>    return x</pre><p>Now in app.py we will get these functions to give the overall analysis</p><p>In app.py</p><pre>if user_menu == &#39;Overall Analysis&#39;:<br>    editions = df[&#39;Year&#39;].unique().shape[0] - 1<br>    cities = df[&#39;City&#39;].unique().shape[0]<br>    sports = df[&#39;Sport&#39;].unique().shape[0]<br>    events = df[&#39;Event&#39;].unique().shape[0]<br>    athletes = df[&#39;Name&#39;].unique().shape[0]<br>    nations = df[&#39;region&#39;].unique().shape[0]<br><br>    st.title(&quot;Top Statistics&quot;)<br><br>    col1, col2, col3 = st.columns(3)<br>    with col1:<br>        st.header(&quot;Editions&quot;)<br>        st.title(editions)<br><br>    with col2:<br>        st.header(&quot;Hosts&quot;)<br>        st.title(cities)<br><br>    with col3:<br>        st.header(&quot;Sports&quot;)<br>        st.title(sports)<br><br>    col1, col2, col3 = st.columns(3)<br>    with col1:<br>        st.header(&quot;Events&quot;)<br>        st.title(events)<br><br>    with col2:<br>        st.header(&quot;Nations&quot;)<br>        st.title(nations)<br><br>    with col3:<br>        st.header(&quot;Athletes&quot;)<br>        st.title(athletes)<br><br>    nations_over_time = helper.data_over_time(df, &#39;region&#39;)<br>    fig = px.line(nations_over_time, x=&quot;Edition&quot;, y=&quot;region&quot;)<br>    st.title(&quot;Participating Nations over the Year&quot;)<br>    st.plotly_chart(fig)<br><br>    events_over_time = helper.data_over_time(df, &#39;Event&#39;)<br>    fig = px.line(events_over_time, x=&quot;Edition&quot;, y=&quot;Event&quot;)<br>    st.title(&quot;Events over the Year&quot;)<br>    st.plotly_chart(fig)<br><br>    athlete_over_time = helper.data_over_time(df, &#39;Name&#39;)<br>    fig = px.line(athlete_over_time, x=&quot;Edition&quot;, y=&quot;Name&quot;)<br>    st.title(&quot;Athletes over the Year&quot;)<br>    st.plotly_chart(fig)<br><br>    st.title(&quot;No of Events over Time (Every Sport)&quot;)<br>    fig, ax = plt.subplots(figsize = (20, 20))<br>    x = df.drop_duplicates([&#39;Year&#39;, &#39;Sport&#39;, &#39;Event&#39;])<br>    ax = sns.heatmap(x.pivot_table(index=&#39;Sport&#39;, columns=&#39;Year&#39;, values=&#39;Event&#39;, aggfunc=&#39;count&#39;).fillna(0).astype(&#39;int&#39;), annot=True)<br>    st.pyplot(fig)<br><br>    st.title(&quot;Most successful Athletes&quot;)<br>    sport_list = df[&#39;Sport&#39;].unique().tolist()<br>    sport_list.sort()<br>    sport_list.insert(0, &#39;Overall&#39;)<br><br>    selected_sport = st.selectbox(&#39;Select a Sport&#39;, sport_list)<br>    x = helper.most_successful(df, selected_sport)<br>    st.table(x)</pre><p>Now in helper.py file we will create few functions that we will use in app.py to create athlete wise analysis and country wise analysis.</p><p>In helper.py</p><pre>def yearwise_mdeal_tally(df, country):<br>    temp_df = df.dropna(subset=[&#39;Medal&#39;])<br>    temp_df.drop_duplicates(subset=[&#39;Team&#39;, &#39;NOC&#39;, &#39;Games&#39;, &#39;Year&#39;, &#39;City&#39;, &#39;Sport&#39;, &#39;Event&#39;, &#39;Medal&#39;], inplace=True)<br>    new_df = temp_df[temp_df[&#39;region&#39;] == country]<br>    final_df = new_df.groupby(&#39;Year&#39;).count()[&#39;Medal&#39;].reset_index()<br>    return  final_df<br><br><br>def country_event_heatmap(df, country):<br>    temp_df = df.dropna(subset=[&#39;Medal&#39;])<br>    temp_df.drop_duplicates(subset=[&#39;Team&#39;, &#39;NOC&#39;, &#39;Games&#39;, &#39;Year&#39;, &#39;City&#39;, &#39;Sport&#39;, &#39;Event&#39;, &#39;Medal&#39;], inplace=True)<br>    new_df = temp_df[temp_df[&#39;region&#39;] == country]<br>    pt = new_df.pivot_table(index = &#39;Sport&#39;, columns = &#39;Year&#39;, values = &#39;Medal&#39;, aggfunc = &#39;count&#39;).fillna(0)<br>    return pt<br><br><br>def most_successful_countrywise(df, country):<br>    temp_df = df.dropna(subset=[&#39;Medal&#39;])<br><br>    temp_df = temp_df[temp_df[&#39;region&#39;] == country]<br><br>    x = temp_df[&#39;Name&#39;].value_counts().reset_index().head(10).merge(df, left_on=&#39;index&#39;, right_on=&#39;Name&#39;, how=&#39;left&#39;)[<br>        [&#39;index&#39;, &#39;Name_x&#39;, &#39;Sport&#39;, &#39;region&#39;]].drop_duplicates(&#39;index&#39;)<br><br>    x.rename(columns={&#39;index&#39;: &#39;Name&#39;, &#39;Name_x&#39;: &#39;Medals&#39;}, inplace=True)<br>    return x<br><br><br>def weight_v_height(df,sport):<br>    athlete_df = df.drop_duplicates(subset=[&#39;Name&#39;, &#39;region&#39;])<br>    athlete_df[&#39;Medal&#39;].fillna(&#39;No Medal&#39;, inplace=True)<br>    if sport != &#39;Overall&#39;:<br>        temp_df = athlete_df[athlete_df[&#39;Sport&#39;] == sport]<br>        return temp_df<br>    else:<br>        return athlete_df<br><br><br>def men_vs_women(df):<br>    athlete_df = df.drop_duplicates(subset=[&#39;Name&#39;, &#39;region&#39;])<br><br>    men = athlete_df[athlete_df[&#39;Sex&#39;] == &#39;M&#39;].groupby(&#39;Year&#39;).count()[&#39;Name&#39;].reset_index()<br>    women = athlete_df[athlete_df[&#39;Sex&#39;] == &#39;F&#39;].groupby(&#39;Year&#39;).count()[&#39;Name&#39;].reset_index()<br><br>    final = men.merge(women, on=&#39;Year&#39;, how=&#39;left&#39;)<br>    final.rename(columns={&#39;Name_x&#39;: &#39;Male&#39;, &#39;Name_y&#39;: &#39;Female&#39;}, inplace=True)<br><br>    final.fillna(0, inplace=True)<br><br>    return final</pre><p>Almost all the above functions are easy to understand and are self explanatory so we will move on app.py file to import these functions are complete the web app.</p><p>In app.py</p><pre>if user_menu == &#39;Country-wise Analysis&#39;:<br><br>    st.sidebar.title(&#39;Country-wise Analysis&#39;)<br><br>    country_list = df[&#39;region&#39;].dropna().unique().tolist()<br>    country_list.sort()<br><br>    selected_country = st.sidebar.selectbox(&#39;Select Country&#39;, country_list)<br><br>    country_df = helper.yearwise_mdeal_tally(df, selected_country)<br>    fig = px.line(country_df, x=&quot;Year&quot;, y=&quot;Medal&quot;)<br>    st.title(selected_country + &quot; Medal Tally over the Year&quot;)<br>    st.plotly_chart(fig)<br><br>    st.title(selected_country + &quot; excels in the following sports&quot;)<br>    pt = helper.country_event_heatmap(df, selected_country)<br>    fig, ax = plt.subplots(figsize=(20, 20))<br>    ax = sns.heatmap(pt, annot=True)<br>    st.pyplot(fig)<br><br>    st.title(&quot;Top 10 athletes of &quot; + selected_country)<br>    top10_df = helper.most_successful_countrywise(df, selected_country)<br>    st.table(top10_df)<br><br>if user_menu == &#39;Athlete wise Analysis&#39;:<br>    athlete_df = df.drop_duplicates(subset=[&#39;Name&#39;, &#39;region&#39;])<br><br>    x1 = athlete_df[&#39;Age&#39;].dropna()<br>    x2 = athlete_df[athlete_df[&#39;Medal&#39;] == &#39;Gold&#39;][&#39;Age&#39;].dropna()<br>    x3 = athlete_df[athlete_df[&#39;Medal&#39;] == &#39;Silver&#39;][&#39;Age&#39;].dropna()<br>    x4 = athlete_df[athlete_df[&#39;Medal&#39;] == &#39;Bronze&#39;][&#39;Age&#39;].dropna()<br><br>    fig = ff.create_distplot([x1, x2, x3, x4], [&#39;Overall Age&#39;, &#39;Gold Medalist&#39;, &#39;Silver Medalist&#39;, &#39;Bronze Medalist&#39;],show_hist=False, show_rug=False)<br>    fig.update_layout(autosize=False,width=1000,height=600)<br>    st.title(&quot;Distribution of Age&quot;)<br>    st.plotly_chart(fig)<br><br>    x = []<br>    name = []<br>    famous_sports = [&#39;Basketball&#39;, &#39;Judo&#39;, &#39;Football&#39;, &#39;Tug-Of-War&#39;, &#39;Athletics&#39;,<br>                     &#39;Swimming&#39;, &#39;Badminton&#39;, &#39;Sailing&#39;, &#39;Gymnastics&#39;,<br>                     &#39;Art Competitions&#39;, &#39;Handball&#39;, &#39;Weightlifting&#39;, &#39;Wrestling&#39;,<br>                     &#39;Water Polo&#39;, &#39;Hockey&#39;, &#39;Rowing&#39;, &#39;Fencing&#39;,<br>                     &#39;Shooting&#39;, &#39;Boxing&#39;, &#39;Taekwondo&#39;, &#39;Cycling&#39;, &#39;Diving&#39;, &#39;Canoeing&#39;,<br>                     &#39;Tennis&#39;, &#39;Golf&#39;, &#39;Softball&#39;, &#39;Archery&#39;,<br>                     &#39;Volleyball&#39;, &#39;Synchronized Swimming&#39;, &#39;Table Tennis&#39;, &#39;Baseball&#39;,<br>                     &#39;Rhythmic Gymnastics&#39;, &#39;Rugby Sevens&#39;,<br>                     &#39;Beach Volleyball&#39;, &#39;Triathlon&#39;, &#39;Rugby&#39;, &#39;Polo&#39;, &#39;Ice Hockey&#39;]<br>    for sport in famous_sports:<br>        temp_df = athlete_df[athlete_df[&#39;Sport&#39;] == sport]<br>        x.append(temp_df[temp_df[&#39;Medal&#39;] == &#39;Gold&#39;][&#39;Age&#39;].dropna())<br>        name.append(sport)<br><br>    fig = ff.create_distplot(x, name, show_hist=False, show_rug=False)<br>    fig.update_layout(autosize=False, width=1000, height=600)<br>    st.title(&quot;Distribution of Age wrt Sports(Gold Medalist)&quot;)<br>    st.plotly_chart(fig)<br><br>    sport_list = df[&#39;Sport&#39;].unique().tolist()<br>    sport_list.sort()<br>    sport_list.insert(0, &#39;Overall&#39;)<br><br>    st.title(&#39;Height Vs Weight&#39;)<br>    selected_sport = st.selectbox(&#39;Select a Sport&#39;, sport_list)<br>    temp_df = helper.weight_v_height(df,selected_sport)<br>    fig,ax = plt.subplots()<br>    ax = sns.scatterplot(temp_df[&#39;Weight&#39;],temp_df[&#39;Height&#39;],hue=temp_df[&#39;Medal&#39;],style=temp_df[&#39;Sex&#39;],s=60)<br>    st.pyplot(fig)<br><br>    st.title(&quot;Men Vs Women Participation Over the Years&quot;)<br>    final = helper.men_vs_women(df)<br>    fig = px.line(final, x=&quot;Year&quot;, y=[&quot;Male&quot;, &quot;Female&quot;])<br>    fig.update_layout(autosize=False, width=1000, height=600)<br>    st.plotly_chart(fig)<br></pre><blockquote>Here are some screenshots of our web app:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hT_aquLeI391zidR3yW5Zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjLCLVDZEHx-a_psAcG3Kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qC7OlMbXMX6kflxHG00m8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QUYxmqtn-7kpwfnXV1-yA.png" /></figure><blockquote><em>So, this is the end of our project here. We created a Olympic data analyzer web app end to end in this blog using stramlit. And that is it for today guys.</em></blockquote><blockquote><em>I hope you guys got to learn something new and enjoyed this blog. If you do like it than share it with your friends. Take care. keep learning.</em></blockquote><blockquote><em>You could also reach me through my Linkedin account- </em><a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/"><em>https://www.linkedin.com/in/harsh-mishra-4b79031b3/</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db84fb4d1ff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Glassdoor Data Science Jobs Data: End to End Data Science Project]]></title>
            <link>https://python.plainenglish.io/glassdoor-data-science-jobs-data-end-to-end-data-science-project-d71084390892?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71084390892</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[glassdoor]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 13:22:29 GMT</pubDate>
            <atom:updated>2022-01-21T05:22:38.908Z</atom:updated>
            <content:encoded><![CDATA[<h4>Perform Data Cleaning, Data Analysis, and Salary prediction for the data science job.</h4><p>Hello people, I hope everyone is doing well. Today in this blog we would perform Data Cleaning, Data Analysis, and Salary prediction for the data science job.</p><p>So the end job is to create a machine learning model which can predict the salary offered for different jobs in the data science domain considering a lot of factors regarding company and job.</p><p>All the code written in this blog is on my GitHub:</p><p><a href="https://github.com/HarshMishra2002/dsjob_salary_project">GitHub - HarshMishra2002/dsjob_salary_project</a></p><p>Link for the dataset used:</p><p><a href="https://www.kaggle.com/harshmishraandheri/glassdoor-data-science-jobs-datasets">https://www.kaggle.com/harshmishraandheri/glassdoor-data-science-jobs-datasets</a></p><p>Let&#39;s start the project. The complete project is in Python language and Jupyter notebook is used as an IDE.</p><p>First, we will import the dataset and have an overview of it:</p><pre>import pandas as pd</pre><pre>import numpy as np</pre><pre>df = pd.read_csv(‘glassdoor_jobs.csv’)</pre><pre>df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trt6rM00bq62B96HG1Xcyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rI0n7UadsrMlxkb-drtd1g.png" /></figure><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*4ZiYQPOTRzTUg_gnko4oBw.png" /></figure><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*g41po6rJEqENYqpOap8O4A.png" /></figure><p>Now all these functions are just to get some basic information about the dataset on which we are working. Now let’s see if we have any null values or missing values in the data.</p><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*Gq2__nzxky8y8MiuvBE1iA.png" /></figure><p>So we are lucky enough to not have any missing values. Let’s start with</p><h3><strong>DATA CLEANING</strong></h3><p>We have 5 things to do in this section:</p><p>#Salary parsing<br>#company name text only<br>#state field<br>#age of company<br>#parsing of job description (python, etc..)</p><p>#Salary parsing</p><p>Here the task is to convert the current salary format from “53K−91K (Glassdoor est.)” in the salary estimate column to “72.0” as an average of the range.</p><pre># This will remove the text part of the salary which is (Glassdoor est.)<br>salary = df[‘Salary Estimate’].apply(lambda x: x.split(‘(‘)[0])</pre><pre># Now we want to remove the dollar sign and k which represents the thousands<br> minus_kd = salary.apply(lambda x: x.replace(&#39;K&#39;, &#39;&#39;).replace(&#39;$&#39;, &#39;&#39;))</pre><pre># There are some columns which has &#39;per hour&#39; in the salary to represent that the salary is provided on hourly basis, so we create another column for it<br>df[&#39;hourly&#39;] = df[&#39;Salary Estimate&#39;].apply(lambda x: 1 if &#39;per hour&#39; in x.lower() else 0)</pre><pre># There are some columns which has &#39;employer provided salary&#39; in the salary, so we create another column for it<br>df[&#39;employer_provided&#39;] = df[&#39;Salary Estimate&#39;].apply(lambda x: 1 if &#39;employer provided salary:&#39; in x.lower() else 0)</pre><pre># Now we remove both &#39;per hour&#39; and &#39;employer provided salary&#39; from the original one<br>min_hr = minus_kd.apply(lambda x: x.lower().replace(&#39;per hour&#39;, &#39;&#39;).replace(&#39;employer provided salary:&#39;, &#39;&#39;))</pre><pre># Now we will find the minimum, maximum and the average salary and with this our first part of data cleaning comes to an end<br>df[&#39;min_salary&#39;] = min_hr.apply(lambda x : int(x.split(&#39;-&#39;)[0]))<br>df[&#39;max_salary&#39;] = min_hr.apply(lambda x : int(x.split(&#39;-&#39;)[1]))<br>df[&#39;avg_salary&#39;] = (df.min_salary + df.max_salary)/2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOgxArh_TVyYBJZqkUDbQA.png" /></figure><p>#company name text only</p><p>This is an easy process where we will remove all the unnecessary things from the name of the comapny</p><pre>df[‘company_txt’] = df.apply(lambda x : x[‘Company Name’] if x[‘Rating’] &lt; 0 else x[‘Company Name’][:-4], axis = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*t_SIr_p1dQwV6kPpzwBGvQ.png" /></figure><p>#state field</p><p>We will just find the state in which company has it’s physical existence</p><pre>df[‘job_state’] = df[‘Location’].apply(lambda x : x.split(‘,’)[1])</pre><pre># 1 where ever the job location is in the headquaters itself<br>df[&#39;same_state&#39;] = df.apply(lambda x : 1 if x[&#39;Location&#39;] == x[&#39;Headquarters&#39;] else 0, axis = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rL2GCB6mB2Jp888GZdVBeA.png" /></figure><p>#age of company</p><p>Let&#39;s figure out how old is the company bcoz the salaries offered by start-ups and big companies differ a lot so this might be an important factor</p><pre>df[‘age’] = df[‘Founded’].apply(lambda x : x if x &lt; 1 else 2021 — x)</pre><p>#parsing of job description (python, etc.)</p><p>In the job description, we would be looking for some words like:</p><p>#python<br>#r studio<br>#spark<br>#aws<br>#excel</p><pre>df[‘python_yn’] = df[‘Job Description’].apply(lambda x: 1 if ‘python’ in x.lower() else 0)</pre><pre>df[&#39;R_yn&#39;] = df[&#39;Job Description&#39;].apply(lambda x: 1 if &#39;r studio&#39; in x.lower() or &#39;r-studio&#39; in x.lower() else 0)</pre><pre>df[&#39;spark_yn&#39;] = df[&#39;Job Description&#39;].apply(lambda x: 1 if &#39;spark&#39; in x.lower() else 0)</pre><pre>df[&#39;aws&#39;] = df[&#39;Job Description&#39;].apply(lambda x: 1 if &#39;aws&#39; in x.lower() else 0)</pre><pre>df[&#39;excel&#39;] = df[&#39;Job Description&#39;].apply(lambda x: 1 if &#39;excel&#39; in x.lower() else 0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zsea9hanCICTXIn0BsVWqA.png" /></figure><p>This marks the end of our Data cleaning process. Only one small part is left, that is removing the first column which is named as ‘Unnamed: 0’</p><pre>df_out = df.drop([‘Unnamed: 0’], axis = 1)</pre><pre>df_out.to_csv(‘salary_data_cleaned.csv’, index = False)</pre><pre>df = pd.read_csv(‘salary_data_cleaned.csv’)</pre><p>Before we move to EDA, still there are a few things remaining to get fixed. So let’s quickly finish that part. We want to simplify the ‘job title’ column by replacing it with consistent similar words of what it represents. As we will make a column which will decide the seniority level of the job.</p><pre>def title_simplifier(title):<br> if ‘data scientist’ in title.lower():<br> return ‘data scientist’<br> elif ‘data engineer’ in title.lower():<br> return ‘data engineer’<br> elif ‘analyst’ in title.lower():<br> return ‘analyst’<br> elif ‘machine learning’ in title.lower():<br> return ‘machine learning’<br> elif ‘manager’ in title.lower():<br> return ‘manager’<br> elif ‘director’ in title.lower():<br> return ‘director’<br> else:<br> return ‘na’<br> <br>def seniority(title):<br> if ‘sr’ in title.lower() or ‘senior’ in title.lower() or ‘sr.’ in title.lower() or ‘lead’ in title.lower() or ‘principal’ in title.lower():<br> return ‘senior’<br> elif ‘jr’ in title.lower() or ‘jr.’ in title.lower():<br> return ‘jr’<br> else:<br> return ‘na’</pre><pre>df[&#39;job_simp&#39;] = df[&#39;Job Title&#39;].apply(title_simplifier)</pre><pre>df[&#39;seniority&#39;] = df[&#39;Job Title&#39;].apply(seniority)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*1oeki0YI0usslVNeLofNsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*rqD-1X2DdKiacXp6a0hMxg.png" /></figure><pre># Job description length<br>df[‘desc_length’] = df[‘Job Description’].apply(lambda x : len(x))</pre><pre># competitors count<br>df[&#39;num_comp&#39;] = df[&#39;Competitors&#39;].apply(lambda x: len(x.split(&#39;,&#39;)) if x != -1 else 0)</pre><pre>#hourly wage to annual<br>df[&#39;min_salary&#39;] = df.apply(lambda x: x.min_salary*2 if x[&#39;hourly&#39;] == 1 else x.min_salary, axis = 1)<br>df[&#39;max_salary&#39;] = df.apply(lambda x: x.max_salary*2 if x[&#39;hourly&#39;] == 1 else x.max_salary, axis = 1)</pre><p>Now it&#39;s time for the second part of the project.</p><h3><strong>EDA- Exploratory Data Analysis</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*jInXhdaMWVRZcsV5Ft22tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*ZVJZ0CW6wc_HPqjCkbaAzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*yJXsY5IXxeX8UkatocH5Ag.png" /></figure><p>All these histograms give us some info. We can see in that maximum times the rating of the company is 3,4 or 5 which is pretty cool. Also, many companies are quite young as we see around 400 companies have age 0 to 50 and very few are older than 100 years.</p><p>Now you can also plot some boxplots to check outliers but I leave that to you. If you want to know more about outliers and outlier handling you can visit my blog:</p><p><a href="https://medium.com/@harshmishraandheri/everything-you-need-to-know-about-outliers-75adac679726">Everything you need to know about Outliers</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jv9C14uS0b41Ri8RzWDqWQ.png" /></figure><pre># This is finding the co-relation of all the features having categorical values <br>df_cat = df[[‘Location’, ‘Headquarters’, ‘Size’, ‘Type of ownership’, ‘Industry’, ‘Sector’, ‘Revenue’, ‘company_txt’, ‘job_state’,’same_state’,’python_yn’, ‘R_yn’,<br> ‘spark_yn’, ‘aws’, ‘excel’, ‘job_simp’, ‘seniority’]]</pre><pre>for i in df_cat.columns:<br>    cat_num  = df_cat[i].value_counts()<br>    print(&quot;Graph for %s: total = %d&quot; % (i, len(cat_num)))<br>    chart = sns.barplot(x=cat_num.index, y=cat_num)<br>    chart.set_xticklabels(chart.get_xticklabels() ,rotation=90)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*WflqR5HGBv8OkeE1Aurmlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*bSH8BWEg0uCMff6n0qWcLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*4mkUO-5TR3-ZpgI5PAuQSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*2AD-5Wm8zQbwUftfm15-Ww.png" /></figure><pre>for i in df_cat[[‘Location’, ‘Headquarters’, ‘company_txt’]].columns:<br> cat_num = df_cat[i].value_counts()[:20]<br> print(“Graph for %s: total = %d” % (i, len(cat_num)))<br> chart = sns.barplot(x=cat_num.index, y=cat_num)<br> chart.set_xticklabels(chart.get_xticklabels() ,rotation=90)<br> plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*2p1ZSlxfMtO5k4ymKAOg3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*vOekOhwNHCjpoB5gStXCVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*OQiFVkpXRG5OBodvsKH0tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*lIBT7Q7u0Bh0gGAD76hHEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*1pmUyp1JLiL_LHZdUUsTGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LnEvePtdEtwMCpyBve7KQ.png" /></figure><p>Now, these are some common EDA techniques. I will say you should try more and do experiments to find some more insights into the data:</p><h3><strong>MODEL BUILDING</strong></h3><p># choose relevant columns</p><pre>df_model = df[[‘avg_salary’ ,’Rating’, ‘Size’, ‘Type of ownership’, ‘Industry’,<br> ‘Sector’,’Revenue’, ‘hourly’, ‘employer_provided’, ‘job_state’, ‘same_state’, ‘age’, ‘python_yn’, ‘aws’, ‘excel’, ‘job_simp’, ‘seniority’, ‘desc_length’,’num_comp’ ]]</pre><p># get dummy data for categorical data</p><pre># get dummy data for categorical data to convert it in 0 and 1</pre><pre>df_dum = pd.get_dummies(df_model)</pre><p># train test split</p><pre>from sklearn.model_selection import train_test_split<br>X = df_dum.drop(&#39;avg_salary&#39;, axis = 1)<br>y = df_dum.avg_salary.values<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7QqvaoULMJ-nXp6s50Quw.png" /></figure><p># multiple linear regression</p><pre>import statsmodels.api as sm<br>X_sm = X = sm.add_constant(X)<br>model = sm.OLS(y_train, X_train)</pre><pre>model.fit().summary()<br># R-squared value is good - 0.711 our model explains 70% of the variation in dataset<br># p-value less than 0.05 is significant for our model<br># by looking at the p value we can see which feature is important and which is not</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*mEhbsal2GNTaoDp2taUnYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*KLbfb-rE4Atjt7rKBlKtOA.png" /></figure><p>#LinearRegression</p><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.model_selection import cross_val_score</pre><pre>lm = LinearRegression()<br>lm.fit(X_train, y_train)</pre><pre># neg_mean_absolute_error shows how much we are off from general prediction on average<br># The output means 20k$<br>np.mean(cross_val_score(lm, X_train, y_train, scoring = &#39;neg_mean_absolute_error&#39;, cv = 3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uebD2k0v-QKE05-wzPodQ.png" /></figure><p># lasso regression</p><pre>from sklearn.linear_model import Lasso<br>lm_1 = Lasso()</pre><pre># its worse.. Lol<br>np.mean(cross_val_score(lm_1, X_train, y_train, scoring = &#39;neg_mean_absolute_error&#39;, cv = 3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFxbU-gKOQ9wEdQ1ZwjnTg.png" /></figure><p># Random forest</p><pre>from sklearn.ensemble import RandomForestRegressor<br>rf = RandomForestRegressor()</pre><pre>np.mean(cross_val_score(rf, X_train, y_train, scoring = ‘neg_mean_absolute_error’, cv = 3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18DHj24Sy7vNLR3HqJN07A.png" /></figure><p># tune models using GridsearchCV</p><pre>from sklearn.model_selection import GridSearchCV</pre><pre>parameters = {‘n_estimators’:range(10, 300, 10), ‘criterion’:(‘mse’, ‘mae’), ‘max_features’ : (‘auto’, ‘sqrt’, ‘log2’)}</pre><pre>gs = GridSearchCV(rf, parameters, scoring = &#39;neg_mean_absolute_error&#39;, cv = 3)</pre><pre>gs.fit(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*JTUdjwe292zXn8hi4znFxg.png" /></figure><p>#test ensembels</p><pre>tpred = lm.predict(X_test)<br>tpred_lml = lm_1.predict(X_test)<br>tpred_rf = gs.best_estimator_.predict(X_test)</pre><pre>from sklearn.metrics import mean_absolute_error<br>print(mean_absolute_error(y_test, tpred))<br>print(mean_absolute_error(y_test, tpred_lml))<br>print(mean_absolute_error(y_test, tpred_rf))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*RWXwhTN7KenHTLf2skp0gA.png" /></figure><p><strong># Tuned Random Forest Regressor gave us the best results</strong></p><p><em>That’s all from my side for today.</em></p><p><em>I hope you guys got to learn something new and enjoyed this blog. If you do like it then share it with your friends. Take care. keep learning.</em></p><p><em>You could also reach me through my Linkedin account:</em></p><p><a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/">Harsh Mishra - Frontend Developer - AY International | LinkedIn</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71084390892" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/glassdoor-data-science-jobs-data-end-to-end-data-science-project-d71084390892">Glassdoor Data Science Jobs Data: End to End Data Science Project</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 reasons Why Should you become a Data Scientist???]]></title>
            <link>https://harshmishraandheri.medium.com/5-reasons-why-should-you-become-a-data-scientist-58111244f195?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/58111244f195</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Sat, 25 Dec 2021 13:55:58 GMT</pubDate>
            <atom:updated>2021-12-25T13:55:58.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TgdHMgCRW5T2xbdC" /></figure><p>Data Science has been hailed as the “sexiest job of 21st Century” by Harvard Business Review. But what makes Data Science so important? Why are Data Scientists some of the highly paid professionals?</p><p>And most importantly, why learn Data Science? In this article, we will walk through some of the main reasons as to why Data Science has become the most sought after job in the market.</p><p>Glassdoor has ranked Data Science as its topmost profession. What has made Data Science so relevant today? The answer lies in the massive exponential increase of data. <em>Data is the fuel that drives industries</em>.</p><p>Big Data has revolutionized companies and has given them an edge in competition. These companies need specialized people who are proficient at handling, managing, analyzing and understanding trends in data.</p><p>For example — A company that wants to maximize its sales revenue would hire a Data Scientist to analyze its performance and provide decisions to maximize it.</p><p>This has created a pressing need for hiring more Data Scientists. So, why must you learn Data Science?</p><p>The answer lies in the fact that there is a huge discrepancy in the demand and supply of Data Scientists. There are more vacant positions than the number of Data Scientists in this world.</p><p>Since there is a huge demand, <em>companies pay astronomical figures for these positions</em>. Therefore, you should learn Data Science in order to tap this opportunity and enrich your career.</p><h3>Why Learn Data Science?</h3><p>Here are the reasons that will surely convince you to make a career in Data Science</p><h3>1. A fuel of 21st Century</h3><p>In the last century, oil was considered as the ‘black gold’. But, with the industrial revolution and the emergence of the automotive industry, <em>oil became the main driving source of human civilization</em>.</p><p>However, with time, its value dwindled due to the gradual exhaustion and resorting to alternative renewable sources of energy.</p><p>In the 21st century, the new driving force behind industries is Data. As a matter of fact, even automobile industries are using data to impart autonomy and improve the safety of their vehicles. The idea is to create powerful machines that think in the form of data.</p><p>Data Science is also the electricity that powers the industries of today. Industries need data to improve their performance, make their business grow and provide better products to their customers.</p><h3>2. Problem of Demand &amp; Supply</h3><p>As discussed above, there is a huge abundance of data. However, there aren’t enough resources to convert this data into useful products.</p><p>That is, there aren’t enough people who possess the required skills to help companies utilize the potential that data holds. Due to this reason, there is a dearth in the supply of Data Scientists.</p><p>Much of this is contributed by the infancy of Data Science as a field. There is a lack of ‘data-literacy’ in the market. In order to fill this vacuum in supply, you need to learn Data Science and its underlying fields.</p><h3>3. A Lucrative Career</h3><p>According to Glassdoor, the <em>average salary for a Data Scientist is $117,345/yr</em>. This is above the national average of $44,564. Therefore, a Data Scientist makes 163% more than the national average salary.</p><p>This makes Data Science a highly lucrative career choice. It is mainly due to the dearth in Data Scientists resulting in a huge income bubble.</p><p>Since Data Science requires a person to be proficient and knowledgeable in several fields like Statistics, Mathematics and Computer Science, the learning curve is quite steep. Therefore, the value of a Data Scientist is very high in the market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*CVvhg6dwMsz2rxYS9gptRw.png" /></figure><h3>4. Data Science can make the World a Better Place</h3><p>Big Data &amp; Data Science is beyond being a tool of Business Intelligence. Various philanthropic and social organizations are using data to create products for social good. Also, various health-care organizations are using data for helping doctors to have better insights about their patient’s health.</p><h3>5. Data Science is the Career of Tomorrow</h3><p><em>Data Science is the career of the future</em>. Industries are becoming data-driven and new innovations are being made every day. The field of technology has become dynamic and with more and more people interacting with the internet, more data is being generated.</p><p>Industries require data-scientists to assist them in making smarter decisions and creating better products. Data perceives as the electricity of modern gadgets and applications. It makes products smart and empowers them with autonomy.</p><p>In today’s world, it has become a necessity to possess data-literacy. We must learn how crude data can transform into meaningful products. We must learn the techniques and understand the requirements to analyze and draw insights from the data.</p><p>Data holds an untapped potential that must be realized in order to develop useful products. With the advent of machine learning technologies, it is now possible to predict and intelligently classify information. <em>Big Data and Data Science hold the key to the future</em>.</p><blockquote><em>I hope you guys got to learn something new and enjoyed this blog. If you do like it than share it with your friends. Take care. keep learning.</em></blockquote><blockquote><em>You could also reach me through my Linkedin account- </em><a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/"><em>https://www.linkedin.com/in/harsh-mishra-4b79031b3/</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58111244f195" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classify MNIST Digits Using Convolutional Neural Network in Keras.]]></title>
            <link>https://harshmishraandheri.medium.com/classify-mnist-digits-using-convolutional-neural-network-in-keras-9d9a93b0785e?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9a93b0785e</guid>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mnist-dataset]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Sun, 19 Dec 2021 13:29:35 GMT</pubDate>
            <atom:updated>2021-12-19T13:29:35.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>Classify MNIST Digits Using Convolutional Neural Network in Keras. End to End Beginner level Deep Learning Project.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*49ESzbFQMwTZJj2B-W60fQ.png" /></figure><p>Hello everyone, I hope you all are doing well. In this blog we will be making a very basic convolutional neural network (convnent) using keras library of python programming language to classify MNIST digits.</p><p>All the code written in this blog is present in my github- <a href="https://github.com/HarshMishra2002/mnist-digit-basic-convnent">https://github.com/HarshMishra2002/mnist-digit-basic-convnent</a></p><p>convnet is a stack of Conv2D and MaxPooling2D layers.</p><p>Lets start our work…</p><pre>from keras import layers<br>from keras import models</pre><pre>model = models.Sequential()<br>model.add(layers.Conv2D(32, (3,3), activation = ‘relu’, input_shape = (28,28,1)))</pre><pre>model.add(layers.MaxPooling2D((2,2)))</pre><pre>model.add(layers.Conv2D(64, (3,3), activation = ‘relu’))</pre><pre>model.add(layers.MaxPooling2D((2,2)))</pre><pre>model.add(layers.Conv2D(64, (3,3), activation = ‘relu’))</pre><p>Importantly, a convnet takes as input tensors of shape (image_height, image_width, image_channels) (not including the batch dimension). In this case, we’ll configure the convnet to process inputs of size (28, 28, 1), which is the format of MNIST images. We’ll do this by passing the argument input_shape=(28, 28, 1) to the first layer.</p><p>Let’s display the architecture of the convnet so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jvlqr8hsrL0npuxjk4Qzg.png" /></figure><p>You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink.</p><p>as you go deeper in the network. The number of channels is controlled by the first argument passed to the Conv2D layers (32 or 64). The next step is to feed the last output tensor (of shape (3, 3, 64)) into a densely connected classifier network : a stack of Dense layers. These classifiers process vectors, which are 1D, whereas the current output is a 3D tensor. First we have to flatten the 3D outputs to 1D, and then add a few Dense layers on top.</p><pre>model.add(layers.Flatten()) </pre><pre>model.add(layers.Dense(64, activation=’relu’)) </pre><pre>model.add(layers.Dense(10, activation=’softmax’))</pre><p>We’ll do 10-way classification, using a final layer with 10 outputs and a softmax activation.</p><p>Here’s what the network looks like now:</p><pre>model.summary() </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTqHf9pP9pAJLbuTkz-Hrg.png" /></figure><p>As you can see, the (3, 3, 64) outputs are flattened into vectors of shape (576,) before going through two Dense layers. Now, let’s train the convnet on the MNIST digits.</p><pre>from keras.datasets import mnist </pre><pre>from keras.utils import to_categorical </pre><pre>(train_images, train_labels), (test_images, test_labels) = mnist.load_data()</pre><pre>train_images = train_images.reshape((60000, 28, 28, 1)) </pre><pre>train_images = train_images.astype(‘float32’) / 255 </pre><pre>test_images = test_images.reshape((10000, 28, 28, 1)) </pre><pre>test_images = test_images.astype(‘float32’) / 255 </pre><pre>train_labels = to_categorical(train_labels) </pre><pre>test_labels = to_categorical(test_labels) model.compile(optimizer=’rmsprop’, loss=’categorical_crossentropy’, metrics=[‘accuracy’]) </pre><pre>model.fit(train_images, train_labels, epochs=5, batch_size=64)</pre><p>Let’s evaluate the model on the test data:</p><pre>model.fit(train_images, train_labels, epochs= 5, batch_size = 64)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5sFKb3zh5BKffS-JK-Zug.png" /></figure><blockquote>So, this is the end of our project here. We created a MNIST Digit classifier in this blog using keras. And that is it for today guys.</blockquote><blockquote>I hope you guys got to learn something new and enjoyed this blog. If you do like it than share it with your friends. Take care. keep learning.</blockquote><blockquote>You could also reach me through my Linkedin account- <a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/">https://www.linkedin.com/in/harsh-mishra-4b79031b3/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9a93b0785e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Whatsapp Chat Analyzer Web App : End to End Streamlit Project]]></title>
            <link>https://faun.pub/whatsapp-chat-analyzer-web-app-end-to-end-streamlit-project-d6b3dfb12115?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b3dfb12115</guid>
            <category><![CDATA[what]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[web-apps]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Sun, 12 Dec 2021 11:10:13 GMT</pubDate>
            <atom:updated>2021-12-13T13:57:39.854Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Whatsapp Chat Analyzer Web App : End to End Streamlit Project</strong></p><p>Hello people, I hope everyone is doing well. Today in this blog we will be making a Whatsapp Chat Analyzer Web App using Streamlit.</p><p>Streamlit is an open source app framework in Python language. It helps us <strong>create web apps for data science and machine learning in a short time</strong>. It is compatible with major Python libraries such as scikit-learn, Keras, PyTorch, SymPy(latex), NumPy, pandas, Matplotlib etc.</p><blockquote>Also all the code written in this blog is available in my github : <a href="https://github.com/HarshMishra2002/whatsapp-chat-analyzer">https://github.com/HarshMishra2002/whatsapp-chat-analyzer</a></blockquote><blockquote>The project is deployed using heroku: <a href="https://whatsapp-chat-analyzer-harsh.herokuapp.com/">https://whatsapp-chat-analyzer-harsh.herokuapp.com/</a></blockquote><p>So lets start. we will be using python programming language for all the data analysis and pycharm would be used as IDE.</p><p>We would be creating 3 files in our project</p><ol><li>preprocessor.py : The input we take is a text file consisting of the chats (group chat or personal) so we need to do some preprocessing and get an dataframe out of it. This process would be done in this file.</li><li>app.py : This would be the main file where we would be creating the streamlit app.</li><li>helper.py : We would be making some functions in this file that would be used in the main app.py file.</li></ol><p>How to Get the whatsapp chat:</p><ol><li>Open whatsapp in your mobile</li><li>Go to that group or personal chat whose chat details you want to extract</li><li>Click on the 3 dot icon and go to more options</li><li>Choose ‘export chat’ and select without media option.</li><li>Now you have the dataset and ready to go….</li></ol><p>So let’s start:</p><p>First lets create a stramlit app.</p><p>In app.py write the following code to create a streamlit app</p><pre>import streamlit as st</pre><p>Now we will create a sidebar and ask for an input file</p><pre>st.sidebar.title(&quot;Whatsapp Chat Analyzer&quot;)<br><br>uploaded_file = st.sidebar.file_uploader(&quot;Choose a file&quot;)<br>if uploaded_file is not None:<br>     bytes_data = uploaded_file.getvalue()<br>     data = bytes_data.decode(&quot;utf-8&quot;)</pre><p>Now we have got the data in variable named “data”. After that we will apply the preprocess function of the preprocessor.py file. So lets write the code of preprocessor.py file first</p><p>In preprocessor.py</p><pre>import pandas as pd<br>import re<br><br>def preprocess(data):<br>    pattern = &#39;\d{1,2}/\d{1,2}/\d{2,4},\s\d{1,2}:\d{2}\s-\s&#39;<br>    messages = re.split(pattern, data)[1:]<br>    dates = re.findall(pattern, data)<br>    df = pd.DataFrame({&#39;user_message&#39;: messages, &#39;message_date&#39;: dates})</pre><p>If you look at the whatsapp chat, it comes in a particular format. I have created a particular pattern using regex to extract the messages and the date from the raw data. It may happen that you might need to change it accordingly if whatsapp changes its file format.</p><p>This is how messages and dates look right now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pybrFVoIxRPihoe1KQEHwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OE0ihMQCFjWe0ETUSG68Ew.png" /></figure><p>and we have a dataframe df which has the dates and messages.</p><pre>df[&#39;message_date&#39;] = pd.to_datetime(df[&#39;message_date&#39;], format=&#39;%m/%d/%y, %H:%M - &#39;)<br><br>df.rename(columns={&#39;message_date&#39;: &#39;date&#39;}, inplace=True)<br>users = []</pre><p>This will make out job easier as dates are now in datetime format and not a string anymore. Now we will extract the user name (person who is texting) from his msg and create a separate column for both</p><pre>users = []<br>messages = []<br><br>for message in df[&#39;user_message&#39;]:<br>    entry = re.split(&#39;([\w\W]+?):\s&#39;, message)<br>    if entry[1:]:<br>        users.append(entry[1])<br>        messages.append(entry[2])<br>    else:<br>        users.append(&#39;group_notification&#39;)<br>        messages.append(entry[0])<br><br>df[&#39;user&#39;] = users<br>df[&#39;message&#39;] = messages<br>df.drop(columns=[&#39;user_message&#39;], inplace=True)</pre><p>At this point our df looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*XtZhXEMNDfg5SOkQFlk1yQ.png" /></figure><p>Since our date column is in datetime format we can use many attributes of it to add some more useful columns in our dataframe.</p><pre>df[&#39;year&#39;] = df[&#39;date&#39;].dt.year<br>df[&#39;month&#39;] = df[&#39;date&#39;].dt.month_name()<br>df[&#39;day&#39;] = df[&#39;date&#39;].dt.day<br>df[&#39;hour&#39;] = df[&#39;date&#39;].dt.hour<br>df[&#39;minute&#39;] = df[&#39;date&#39;].dt.minute<br>df[&#39;month_num&#39;] = df[&#39;date&#39;].dt.month<br>df[&#39;only_date&#39;] = df[&#39;date&#39;].dt.date<br>df[&#39;day_name&#39;] = df[&#39;date&#39;].dt.day_name()<br><br>period = []<br><br>for hour in df[[&#39;day_name&#39;, &#39;hour&#39;]][&#39;hour&#39;]:<br>    if hour == 23:<br>        period.append(str(hour) + &quot;-&quot; + str(&#39;00&#39;))<br>    elif hour == 0:<br>        period.append(str(&#39;00&#39;) + &quot;-&quot; + str(hour + 1))<br>    else:<br>        period.append(str(hour) + &quot;-&quot; + str(hour + 1))<br><br>df[&#39;period&#39;] = period<br><br>return df</pre><p>This is the end of preprocessor.py. We wrote the function that takes a text file of whatsapp chat and returns a dataframe which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVyZeHU0ralvjIqb4TNEBA.png" /></figure><p>Now lets go back on our app.py file and use this preprocess function to the input file we took from the user</p><pre>import preprocessor<br>df = preprocessor.preprocess(data)<br><br>st.dataframe(df)</pre><p>Out of the dataframe we have now, lets create a list of group participants and for that we will write this piece of code in app.py</p><pre>#fetch unique users<br><br>user_list = df[&#39;user&#39;].unique().tolist()<br>user_list.remove(&#39;group_notification&#39;)<br>user_list.sort()<br>user_list.insert(0, &quot;Overall&quot;)<br>selected_user = st.sidebar.selectbox(&quot;Show analysis wrt&quot;, user_list)</pre><p>Now we will show some overview at the start like total number of messages, total media shared, total links shared.</p><p>So we would create function in helper.py and then use it in app.py</p><p>In helper.py :</p><pre>from urlextract import URLExtract<br>def fetch_stats(selected_user, df):<br><br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    num_messages = df.shape[0]<br>    words = []<br>    for message in df[&#39;message&#39;]:<br>        words.extend(message.split())<br><br>    num_media_msgs = df[df[&#39;message&#39;] == &#39;&lt;Media omitted&gt;\n&#39;].shape[0]<br><br>    links = []<br><br>    for message in df[&#39;message&#39;]:<br>        links.extend(extract.find_urls(message))<br>    return num_messages, len(words), num_media_msgs, len(links)</pre><p>This function will return the number of messages, number of words, number of media files shared and number of links shared which we will display in app.py</p><p>In app.py :</p><pre>if st.sidebar.button(&quot;Show Analysis&quot;):<br><br>     num_msgs, words, num_media_msgs, num_links = helper.fetch_stats(selected_user, df)<br>     st.title(&quot;Top Statistics&quot;)<br>     col1, col2, col3, col4 = st.columns(4)<br><br>     with col1:<br>          st.header(&quot;Total Messages&quot;)<br>          st.title(num_msgs)<br><br>     with col2:<br>          st.header(&quot;Total Words&quot;)<br>          st.title(words)<br><br>     with col3:<br>          st.header(&quot;Media Shared&quot;)<br>          st.title(num_media_msgs)<br><br>     with col4:<br>          st.header(&quot;Links Shared&quot;)<br>          st.title(num_links)</pre><p>So our app looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGKZdPJmkf30rlBRNI4UNw.png" /></figure><p>Now we will be working with some timeline. First we will plot two graphs showing number of messages month wise and day wise. Again for that we would be creating a function in helper.py and using it in app.py</p><p>In helper.py :</p><pre>def monthly_timeline(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    timeline = df.groupby([&#39;year&#39;, &#39;month_num&#39;, &#39;month&#39;]).count()[&#39;message&#39;].reset_index()<br>    time = []<br>    for i in range(timeline.shape[0]):<br>        time.append(timeline[&#39;month&#39;][i] + &quot;-&quot; + str(timeline[&#39;year&#39;][i]))<br>    timeline[&#39;time&#39;] = time<br>    return timeline<br><br>def daily_timeline(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    daily_timeline = df.groupby(&#39;only_date&#39;).count()[&#39;message&#39;].reset_index()<br>    return daily_timeline</pre><p>In app.py :</p><pre># timeline<br>st.title(&quot;Monthly Timeline&quot;)<br>timeline = helper.monthly_timeline(selected_user, df)<br>fig, ax = plt.subplots()<br>ax.plot(timeline[&#39;time&#39;], timeline[&#39;message&#39;], color = &#39;green&#39;)<br>plt.xticks(rotation=&#39;vertical&#39;)<br>st.pyplot(fig)<br><br>st.title(&quot;Daily Timeline&quot;)<br>daily_timeline = helper.daily_timeline(selected_user, df)<br>fig, ax = plt.subplots()<br>ax.plot(daily_timeline[&#39;only_date&#39;], daily_timeline[&#39;message&#39;], color=&#39;green&#39;)<br>plt.xticks(rotation=&#39;vertical&#39;)<br>st.pyplot(fig)</pre><p>So this analysis looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*jUVhDF_-LzGT8zrHVbUSHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*EYwkRI-HTKBl3WlzOnFm1w.png" /></figure><p>After this, we want to see the busiest day and month</p><p>In helper.py :</p><pre>def week_activity_map(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    return df[&#39;day_name&#39;].value_counts()<br><br>def month_activity_map(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    return df[&#39;month&#39;].value_counts()</pre><p>In app.py :</p><pre># activity map<br>st.title(&quot;Activity Map&quot;)<br>col1, col2 = st.columns(2)<br><br>with col1:<br>     st.header(&quot;Most busy day&quot;)<br>     busy_day = helper.week_activity_map(selected_user, df)<br>     fig, ax = plt.subplots()<br>     ax.bar(busy_day.index, busy_day.values, color=&#39;green&#39;)<br>     st.pyplot(fig)<br><br>with col2:<br>     st.header(&quot;Most busy month&quot;)<br>     busy_month = helper.month_activity_map(selected_user, df)<br>     fig, ax = plt.subplots()<br>     ax.bar(busy_month.index, busy_month.values, color=&#39;orange&#39;)<br>     st.pyplot(fig)</pre><p>And now this is how our app looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byliL65gZ0SlvF8FO3VpZw.png" /></figure><p>After this, we would show the heatmap where we will see the time range of chats and what time which day the chatting happens the most, least, and everything in between.</p><p>In helper.py :</p><pre>def activity_heatmap(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    activity_heatmap = df.pivot_table(index=&#39;day_name&#39;, columns=&#39;period&#39;, values=&#39;message&#39;, aggfunc=&#39;count&#39;).fillna(0)<br>    return activity_heatmap</pre><p>In app.py :</p><pre>st.title(&quot;Weekly Activity Map&quot;)<br>user_heatmap = helper.activity_heatmap(selected_user, df)<br>fig, ax = plt.subplots()<br>ax = sns.heatmap(user_heatmap)<br>st.pyplot(fig)</pre><p>The results are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*AE_YB6d9k4opG7QKLfN8Sg.png" /></figure><p>Now let&#39;s find out the busiest users</p><p>In helper.py :</p><pre>def fetch_most_busy_users(df):<br>    x = df[&#39;user&#39;].value_counts().head()<br>    df = round((df[&#39;user&#39;].value_counts() / df.shape[0]) * 100, 2).reset_index().rename(<br>        columns={&#39;index&#39;: &#39;name&#39;, &#39;user&#39;: &#39;percent&#39;})<br>    return x, df</pre><p>In app.py :</p><pre># finding the busiest user in the group<br>if selected_user == &#39;Overall&#39;:<br>     st.title(&quot;Most Busy Users&quot;)<br>     x, new_df = helper.fetch_most_busy_users(df)<br>     fig, ax = plt.subplots()<br><br>     col1, col2 = st.columns(2)<br><br>     with col1:<br>          ax.bar(x.index, x.values, color = &#39;red&#39;)<br>          plt.xticks(rotation = &#39;vertical&#39;)<br>          st.pyplot(fig)<br><br>     with col2:<br>          st.dataframe(new_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jc4z2Vq1F8jg_fBFhJwDEg.png" /></figure><p>Now we will create wordcloud</p><p>In helper.py :</p><pre>def create_word_cloud(selected_user,df):<br><br>    f = open(&#39;stop_hinglish.txt&#39;, &#39;r&#39;)<br>    stop_words = f.read()<br><br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    temp = df[df[&#39;user&#39;] != &#39;group_notification&#39;]<br>    temp = temp[temp[&#39;message&#39;] != &#39;&lt;Media omitted&gt;\n&#39;]<br><br>    def remove_stop_words(message):<br>        y = []<br>        for word in message.lower().split():<br>            if word not in stop_words:<br>                y.append(word)<br>        return &quot; &quot;.join(y)<br><br>    wc = WordCloud(width=500,height=500,min_font_size=10,background_color=&#39;white&#39;)<br>    temp[&#39;message&#39;] = temp[&#39;message&#39;].apply(remove_stop_words)<br>    df_wc = wc.generate(temp[&#39;message&#39;].str.cat(sep=&quot; &quot;))<br>    return df_wc</pre><p>In app.py :</p><pre># wordcloud<br>st.title(&quot;Wordcloud&quot;)<br>df_wc = helper.create_word_cloud(selected_user, df)<br>fig, ax = plt.subplots()<br>ax.imshow(df_wc)<br>st.pyplot(fig)</pre><p>Results :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*MHjq66N6DhjWyMNc.png" /></figure><p>And now similarly we will find the most common words and emojis used</p><p>In helper.py :</p><pre>def most_common_words(selected_user,df):<br><br>    f = open(&#39;stop_hinglish.txt&#39;,&#39;r&#39;)<br>    stop_words = f.read()<br><br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    temp = df[df[&#39;user&#39;] != &#39;group_notification&#39;]<br>    temp = temp[temp[&#39;message&#39;] != &#39;&lt;Media omitted&gt;\n&#39;]<br><br>    words = []<br><br>    for message in temp[&#39;message&#39;]:<br>        for word in message.lower().split():<br>            if word not in stop_words:<br>                words.append(word)<br><br>    most_common_df = pd.DataFrame(Counter(words).most_common(20))<br>    return most_common_df<br><br>def emoji_helper(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br>    emojis = []<br>    for message in df[&#39;message&#39;]:<br>        emojis.extend([c for c in message if c in emoji.UNICODE_EMOJI[&#39;en&#39;]])<br>    emoji_df = pd.DataFrame(Counter(emojis).most_common(20))<br>    return emoji_df</pre><p>In app.py :</p><pre># most common words<br>st.title(&quot;Most Common Words&quot;)<br>most_common_df = helper.most_common_words(selected_user, df)<br>fig, ax = plt.subplots()<br>ax.barh(most_common_df[0], most_common_df[1])<br>plt.xticks(rotation=&#39;vertical&#39;)<br>st.pyplot(fig)<br><br>#emoji analysis<br>emoji_df = helper.emoji_helper(selected_user, df)<br>st.title(&quot;Emojis Analysis&quot;)<br><br>col1, col2 = st.columns(2)<br><br>with col1:<br>     st.dataframe(emoji_df)<br>with col2:<br>     fig, ax = plt.subplots()<br>     ax.pie(emoji_df[1].head(), labels = emoji_df[0].head(), autopct = &quot;%0.2f&quot;)<br>     st.pyplot(fig)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mnN2YOX7-Z636kOG.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qFaAJgF4fOpUVQOWsJ5DA.png" /></figure><blockquote>So, this is the end of our project here. We created a whatsapp chat analyzer web app end to end in this blog using stramlit. And that is it for today guys.</blockquote><blockquote>I hope you guys got to learn something new and enjoyed this blog. If you do like it than share it with your friends. Take care. keep learning.</blockquote><blockquote>You could also reach me through my Linkedin account- <a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/">https://www.linkedin.com/in/harsh-mishra-4b79031b3/</a></blockquote><figure><a href="https://faun.to/bP1m5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCiLLad3dvZLwBa-B5cAVQ.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b3dfb12115" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/whatsapp-chat-analyzer-web-app-end-to-end-streamlit-project-d6b3dfb12115">Whatsapp Chat Analyzer Web App : End to End Streamlit Project</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PCA: The Principal Component of Machine Learning]]></title>
            <link>https://harshmishraandheri.medium.com/pca-the-principal-component-of-machine-learning-80dca607380d?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/80dca607380d</guid>
            <category><![CDATA[principal-component]]></category>
            <category><![CDATA[feature-extraction]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Sat, 04 Dec 2021 16:20:28 GMT</pubDate>
            <atom:updated>2021-12-04T16:20:28.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*IxapLrU1m35Cyq5j" /></figure><p>Hello everyone, in this blog we will learn about PCA- Principal Component Analysis in detail. First we will get a strong geometric intuition about it then we will se how to apply it step by step and finally a python code implementation of it.</p><blockquote><em>All the code written in this blog is in my github- </em><a href="https://github.com/HarshMishra2002/pca">https://github.com/HarshMishra2002/pca</a></blockquote><p>First of all, PCA is a Feature extraction technique. It reduces the dimension of your data and rescues you from the curse of dimensionality.</p><blockquote>According to <a href="https://en.wikipedia.org/wiki/Principal_component_analysis">wikipedia</a></blockquote><blockquote>PCA was invented in 1901 by <a href="https://en.wikipedia.org/wiki/Karl_Pearson">Karl Pearson</a>, as an analogue of the <a href="https://en.wikipedia.org/wiki/Principal_axis_theorem">principal axis theorem</a> in mechanics; it was later independently developed and named by <a href="https://en.wikipedia.org/wiki/Harold_Hotelling">Harold Hotelling</a> in the 1930s.</blockquote><p>This shows how old this technique is actually but still today it is the first choice option when it comes to feature extraction especially when you are dealing with very high dimension data.</p><p><strong>GEOMETRIC INTUITION:</strong></p><p>First we need to understand how feature selection works. It completely depends on variance of data. For example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*_yML3ofvvkYhZKF397pjJg.png" /></figure><p>If we look at the above graph: We can clearly see that d &gt;&gt; d1 i.e. the variance of the data on x-axis is more than the data on y-axis so we will choose the feature which is on x-axis and drop which is on y-axis. But this technique of feature selection seems to fail when data on both axis have similar variation.</p><p>for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*yNN3JVBkyfZm7g9GuwL-DA.png" /></figure><p>now in this case d = d1 so the variance of data columns on each axis is same. Its not possible to use the above technique to select one data feature and reject another. So here comes PCA.</p><p>what we do is rotate the original axis so that we achieve maximum variance at an axis. Those new axis are called Principal Components. Then we project the original data on principal component to get our new data points and these data points is our new dataset which has critical information about the data. In PCA we create new data instead of dropping some and keeping some.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*XHgJ4VJgz1RN2xpx4GX7cQ.png" /></figure><p>Here you can see. After rotating the original axis we got new axis i.e. Principal Axis 1 and Principal axis 2 and now for the new data points (which we achieved by projecting the old ones to PC) we have different variations i.e. d new &gt;&gt; d1 new.</p><p>Now since we have got the geometric intuition, lets see how we actually find these principal components using python as programming language.</p><p><strong>Step By Step Solution with Python Implementation:</strong></p><p><strong>Step 0: Having a data</strong></p><p>Here I have a 3D data with me i.e. 3 input features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eDDVjbUrGdWaJ57n5cTXDQ.png" /></figure><p><strong>Step 1: Scaling data (Mean Centering)</strong></p><p>We scale the data i.e. we bring all the columns in a similar range of value. Here we will apply standardscaler library from sklearn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJAqf8qBNvyVy7nclSeDSA.png" /></figure><p><strong>Step 2 : Finding covariance matrix</strong></p><p>The drawback of finding a variance is that I can find variance of one column with only one axis. SO when it comes to find the relation between two variables we use something called as covariance.</p><p>A covariance matrix is a square matrix giving the covariance between each pair of elements of a given random vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7l6LXyEyu7YxVd7w_P4pHg.png" /></figure><p><strong>Step 3 : Finding Eigen Vectors and Eigen Values</strong></p><p>Eigen vectors are those vectors when we apply any transformation on it, only the size changes and not the direction.</p><p>Eigen values are the measure of shrink or stretch of Eigen vector after transformation.</p><p>The transformation here which is been discussed is the transformation applied on the covariance matrix. Basically we find eigen vectors and eigen values of the covariance matrix we found above.</p><p><em>Each eigen vector has one eigen value, the vector with the highest value is our PC 1 (first principal component) and so on..</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7c3nUTpmMm5SkUWtc37Zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*Od6KxIr9Ypuu7hUufdz_aA.png" /></figure><p><strong>Step 4 : Selecting the PC and transforming the old data accordingly</strong></p><p>Here I will choose the first two PC that is I am converting my 3D data in 2D data. Then we will transform the old data by projecting it on the new axis (PC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mty-mEKIhq1KSiT_1HU3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqqTSubA4KZCGtHUZJKqoQ.png" /></figure><blockquote><em>So here we end our very basic first PCA implementation. And that is it for today guys.</em></blockquote><blockquote><em>I hope you guys got to learn something new and enjoyed this blog. If you do like it than share it with your friends. Take care. keep learning.</em></blockquote><blockquote><em>You could also reach me through my Linkedin account- </em><a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/"><em>https://www.linkedin.com/in/harsh-mishra-4b79031b3/</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80dca607380d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Neural Netwok? Start your Deep Learning Journey today !!!]]></title>
            <link>https://harshmishraandheri.medium.com/what-is-a-neural-netwok-start-your-deep-learning-journey-today-9ea88fe69d9b?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ea88fe69d9b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Sat, 27 Nov 2021 15:45:18 GMT</pubDate>
            <atom:updated>2021-11-27T17:48:58.041Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a Neural Network? Start your Deep Learning Journey today !!!</h3><p>Hello everyone, I hope you all are doing well. Today, in this blog we will try to get a strong intuition of neural network which is very important to start with Deep Learning. Also we will make a beginner level project to solidate our learnings.</p><blockquote>All the code written in this blog is in my github- <a href="https://github.com/HarshMishra2002/movie_review_classification_DL">https://github.com/HarshMishra2002/movie_review_classification_DL</a></blockquote><p><strong>The “Deep” in Deep Learning</strong></p><p>In general terms, Deep learning is a system of successive layers to predict the output based on the provided input features. <em>Each layer extracts some meaningful information out of the data and creates a meaningful representation of data</em>. The deep in deep learning doesn’t means to have any kind of a deeper understanding; rather it stands for this idea of successive layers of representation. How many layers contribute to a model of the data is called the <em>depth </em>of the data.</p><p>In deep learning, these layered representations are learned via models called <strong>neural networks.</strong></p><p>So neural network means building a network that has set of layers (as mentioned above) where each layer has certain number of nodes to hold data. Final goal is to understand data and give the desired output. The output of one layer becomes the input for the next layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*NIkyjs_3ozg9U1OnrsvBSg.png" /></figure><p><strong>Anatomy of a neural network</strong></p><p>Neural network mainly revolves around these four things:</p><ol><li>Layers</li><li>Input data and corresponding targets</li><li>Loss function</li><li>Optimizer</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*plc-nHY9pEkdQAmfJ9z4uw.png" /></figure><p><strong>Layers</strong>: Layer is a data-processing module that takes as input one or more tensors and that output one or more tensors {The word tensor comes from the Latin word tendere meaning “to stretch”. A tensor of order zero (zeroth-order tensor) is a scalar (simple number). A tensor of order one (first-order tensor) is a linear map that maps every vector into a scalar. A vector is a tensor of order one.} and that outputs one or more tensors.</p><p>For different tensor formats (Input data) we need different types of layers</p><p>2D tensor (sample, features) → Dense Layers</p><p>3D tensor (samples, timestamps, features) → LSTM layers</p><p>4D tensor (Image data) → 2D convolutional layers</p><p><strong>Loss function and optimizers</strong>: Loss function represents a measure of success for the task at hand. This quantity would be minimized during training. Optimizers determines how the network will be updated based on loss function.</p><p>Now we have enough information to start with the project. We would be implementing everything in python and will be using keras library.</p><p><strong>Movie Reviews Classification</strong></p><p>About the dataset:</p><p>You’ll work with the IMDB dataset: a set of 50,000 highly polarized reviews from the Internet Movie Database. They’re split into 25,000 reviews for training and 25,000 reviews for testing, each set consisting of 50% negative and 50% positive reviews.</p><p>lets first import the dataset and keras library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rV_R84PN9P_OFD2mYxbSCg.png" /></figure><p>The argument num_words=10000 means you’ll only keep the top 10,000 most frequently occurring words in the training data. Rare words will be discarded.</p><p>As we have see earlier, layers of a neural network accept only tensors as input but in the data we have right now it is a list of integers. Our next task is to transform that list of integers to a tensor.</p><p>The best way to do that is one-hot-encoding. It will turn our list in vectors of 0s and 1s. This would mean, for instance, turning the sequence [3, 5] into a 10,000-dimensional vector that would be all 0s except for indices 3 and 5, which would be 1s. Then you could use as the first layer in your network a Dense layer, capable of handling floating-point vector data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_ICDv6HLiViRshvDmvnaw.png" /></figure><p>vectorizing labels would be quite straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-ahIGupuQBaCtn12E-vIg.png" /></figure><p>Now its time to build our network. We have seen earlier that Dense layers would be the preferred ones according to our data. We will be using ‘relu’ as our activation function. Dense(16, activation=’relu’). The argument being passed to each Dense layer (16) is the number of hidden units (nodes)of the layer. A hidden unit is a dimension in the representation space of the layer.</p><p>Dense layer with a relu activation implements the following chain of tensor operations: <em>output = relu(dot(W, input) + b).</em> Having 16 hidden units means the weight matrix W will have shape (input_dimension, 16): the dot product with W will project the input data onto a 16-dimensional representation space (and then you’ll add the bias vector b and apply the relu operation). You can intuitively understand the dimensionality of your representation space as “how much freedom you’re allowing the network to have when learning internal representations.” Having more hidden units (a higher-dimensional representation space) allows your network to learn more-complex representations, but it makes the network more computationally expensive and may lead to learning unwanted patterns.</p><p>There are two key architecture decisions to be made about such a stack of Dense layers: </p><p>How many layers to use </p><p>How many hidden units to choose for each layer</p><p>For the time being, you’ll have to trust me with the following architecture choice: </p><p>Two intermediate layers with 16 hidden units each </p><p>A third layer that will output the scalar prediction regarding the sentiment of the current review</p><p>The intermediate layers will use relu as their activation function, and the final layer will use a sigmoid activation so as to output a probability (a score between 0 and 1, indicating how likely the sample is to have the target “1”: how likely the review is to be positive)</p><p>A relu (rectified linear unit) is a function meant to zero out negative values, whereas a sigmoid “squashes” arbitrary values into the [0, 1] interval, outputting something that can be interpreted as a probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*Eirk6vNEeHNw2D7n_hyRpA.png" /></figure><p>So our network would be looking something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*1g1UpXv8V8M2BmzM34HP9w.png" /></figure><p><strong>What are activation functions and why are they necessary?</strong></p><p>without activation functions like relu, the dense layer would only have two linear operations to work with and that is dot product and addition</p><p>output= dot(w, input) + b</p><p>so the layer could only learn linear transformations of the data. The <em>hypothesis space</em> of such layer would consist of set of all possible linear transformations of the input data into a 16-dimensional space. Such a hypothesis space is too restricted and wouldn’t benefit from multiple layers of representations, because a deep stack of linear layers would still implement a linear operation: adding more layers wouldn’t extend the hypothesis space. In order to get access to a much richer hypothesis space that would benefit from deep representations, you need a non-linearity, or activation function</p><p>Now back to our project, we finally need to choose a loss function and an optimizer. For the models that output a probability crossentropy loss would be the best option to choose. crossentropy is difference between the actual output and model’s prediction. For optimization we will use rmsprop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYJHSgp-gbvGayfXTafcEQ.png" /></figure><p>In order to monitor during training the accuracy of the model on data it has never seen before, we will create a validation set by setting apart 10,000 samples from the original training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vDVUQ5pA_fv1Yl2r_Ij0Q.png" /></figure><p>we’ll now train the model for 20 epochs (20 iterations over all samples in the x_train and y_train tensors), in mini-batches of 512 samples. At the same time, we’ll monitor loss and accuracy on the 10,000 samples that you set apart. You do so by passing the validation data as the validation_data argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWlDD4rbn8Akqeh6GLBDYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHxjxqAiCGSDC4Obgh5Ckw.png" /></figure><p>history variable has stored all the info while training the data like accuracy after every epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BeZqCXYxY0SjOZnyEh4WA.png" /></figure><p>let’s use Matplotlib to plot the training and validation loss side by side, as well as the training and validation accuracy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiC2fQQ2BUtONXnVH79D6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WzKwiQbaZ36jyq6hN3Qf2Q.png" /></figure><p>We look at the validation loss, after 4 epoch it starts increasing rather than decreasing. Similarly the validation accuracy decreases. So after 4th epoch we are facing the issue of <strong>overfitting.</strong></p><p>Now again we will train our model but with only 4 epoch this time and input data would be the entire training data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Kp7v7fQMtG7NPHayChi3w.png" /></figure><p>we are getting an accuracy of 88%. Now we will predict on the test data by using predict method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uL71_7wTRmqtDHgqB99qPw.png" /></figure><blockquote>So here we end our very basic first deep learning project. And that is it for today guys.</blockquote><blockquote>I hope you guys got to learn something new and enjoyed this blog. If you do like it than share it with your friends. Take care. keep learning.</blockquote><blockquote>You could also reach me through my Linkedin account- <a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/">https://www.linkedin.com/in/harsh-mishra-4b79031b3/</a></blockquote><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ea88fe69d9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[T20 Cricket Score Predictor — End to End ML project]]></title>
            <link>https://harshmishraandheri.medium.com/t20-cricket-score-predictor-end-to-end-ml-project-fbb3ec67dbb1?source=rss-20163b97eba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbb3ec67dbb1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cricket]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Harsh Mishra]]></dc:creator>
            <pubDate>Sat, 20 Nov 2021 11:05:49 GMT</pubDate>
            <atom:updated>2021-11-20T12:15:41.357Z</atom:updated>
            <content:encoded><![CDATA[<h3>T20 Cricket Score Predictor — End to End ML project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*TNd8UjA8CZPhrcbA.jpg" /></figure><p>Hello everyone, I hope you all are doing well. T20 cricket season is going on and since past 4 months we are continuously witnessing some really incredible t20 matches so I think this is the best time to make and end to end machine learning project on it.</p><p>Today in this blog we will be making a score predictor. Our model will predict the total score at the end of an innings by taking some factors in consideration.</p><blockquote><em>All the code written in this blog is in my github- </em><a href="https://github.com/HarshMishra2002/cricket_score_pred">https://github.com/HarshMishra2002/cricket_score_pred</a></blockquote><blockquote><em>link for the dataset used- </em><a href="https://www.kaggle.com/harshmishraandheri/t20i-cricket-matches-ball-by-ball-info-dataset">https://www.kaggle.com/harshmishraandheri/t20i-cricket-matches-ball-by-ball-info-dataset</a></blockquote><p>Lets start the Project. Complete project is in python language and Jupiter notebook is used as an IDE.</p><p>first we will import the dataset and have an overview of it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cmBXO1wi7O0TOlPKT4Mdw.png" /></figure><p>So this is that dataset we have. We need to create some columns and extract few to get the desired data. Eventually we want our data to have columns:</p><p>batting team<br>bowling team<br>city<br>current_score<br>balls left<br>wickets_left<br>current_run_rate<br>last five</p><p>Now we already have few columns as we want it in our dataset. Batting team and bowling team data we already have. we also have city column but it has some null values which we need to figure out how to handle that. For rest all we need do some manipulation.</p><p>Now we will start our feature extraction from the city column. To fill the empty values we will use venue column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWWyoCiTYRtUDhVHNF1yuQ.png" /></figure><p>Here we are checking the values in ‘venue’ column where city column has null values. If we notice carefully the first word in venue is actually the name of the city where the venue exists for e.g. Dubai in Dubai International Cricket Stadium or Melbourne in Melbourne Cricket Ground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8oBlnGgXk6s6g3YW0M_EiQ.png" /></figure><p>So we store all the first word of venue column in variable named cities and then use it to fill the the city column. Now there are no null values in our dataset. But still there is one more thing left. Our dataset is a ball-by-ball dataset which means if there are 63000 rows that means that many balls have been bowled and played.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n19zJFD0dHSy23sm27cxMw.png" /></figure><p>This shows that there are certain cities where very few deliveries have been played. So we can ignore those cities and only consider the ones which have at least 600 deliveries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFTNqFucNUUAFRm9tSiFjA.png" /></figure><p>Now our city column is complete. Coming to current_runs column which is very easy to extract from the runs column. A simple cumsum() function (used to find the cumulative sum of a column) will do the work for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fugXACO4ee1hgfGX9Fa2Vg.png" /></figure><p>Now our next target is to create a ‘balls_left’ column for which firstly we would be creating to new columns: ‘overs’ and ‘balls’ which tells us how many overs have been completed and how many balls of the current over has been bowled respectively. The code is very simple for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufDM-t0V7c1HoVrycsVNdw.png" /></figure><p>Now by using a simple formula we can create a ‘balls_bowled’ column that is how many balls have been bowled. Formula would be</p><p>balls_bowled = (overs * 6) + balls</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_lOyu_DuxndyIoK2JKVcQ.png" /></figure><p>And now finally we can create our desired column ‘balls_left’ by subtracting balls_bowled from 120 because there are total 120 balls in an innings. sometimes because of extras (wide, no ball …) the ball count exceeds 120 so in such case we can simply give the value of 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CyoA5z0k5ldUtIAXgUPeQ.png" /></figure><p>Now if we look at the ‘player_dismissed’ column it has either value 0 or name of the player got out at that particular ball. First we will replace all the names with 1 and then apply the cumsum() function on it so we can get the total wickets gone and we will subtract it from 10 to get the ‘wickets_left’ column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n56rq0HMLCUuvqaN-S8TSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofGTfUcjHklU51Tbkcr_6Q.png" /></figure><p>Now we will create current run rate column which is very easy to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-eTO5TvFSx1GwCBaSdLHnw.png" /></figure><p>Now we need a column that has total runs scored in last five overs. Obviously we will have null values in this column for first 5 overs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBZlCkDzDxfJJL_gG24UJw.png" /></figure><p>Now we have to create a last column which would be our target column. Total runs scored in that innings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MAms4ggcjNCbo2Xk4FtFg.png" /></figure><p>Now we will drop all the columns which we dont want to have for our model and keep those which we created just now. Also we will shuffle the data to avoid any kind of bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnK8eOHVjEFKEcUcZBwK-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WRe0z_Q38y6t-N0CmgUOA.png" /></figure><p>With this we end out feature extraction part of the project. So after lot of work we finally have the exact required data we wanted at the start.</p><p>So lets now begin with model building process. For that first we will divide our dataset in training set and testing set using train_test_split module of sklearn library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOIng2Alt-uw5FwZC4PfRQ.png" /></figure><p>Some preprocessing steps are required here. We will apply one hot encoding on the categorical features (batting_team, bowling_team and city) then we will create a pipleline which would be having our ml model. Also we will apply scaling on our data so that all values come in one range.</p><p>Here four our model I will be using xgboost algorithm. Of course you can use any other regression algorithm and choose that gives the best result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYhPA7dY-uRHSmUGTWqrdQ.png" /></figure><p>So now our model is ready and its time to check its r2 score and see how it is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yW76gYfn_miETwgQZlXHwQ.png" /></figure><p>This is Incredible. R2 score of 0.98. Now honestly it make me worry about the case of overfitting. Now I keep this open to you all to tune the hyperparameters and see how it affects our model.</p><p>I have used Streamlit to deploy this model. Here is the quick demo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KerGjUUQfg1Ic3LuC_4Ueg.png" /></figure><blockquote>That’s all from my side for today.</blockquote><blockquote>I hope you guys got to learn something new and enjoyed this blog. If you do like it than share it with your friends. Take care. keep learning.</blockquote><blockquote>You could also reach me through my Linkedin account- <a href="https://www.linkedin.com/in/harsh-mishra-4b79031b3/">https://www.linkedin.com/in/harsh-mishra-4b79031b3/</a></blockquote><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb3ec67dbb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>