<?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 Kaushikpandav on Medium]]></title>
        <description><![CDATA[Stories by Kaushikpandav on Medium]]></description>
        <link>https://medium.com/@kaushikpandav16?source=rss-101d0e750e5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*COCDlKiCYyUQXfdx</url>
            <title>Stories by Kaushikpandav on Medium</title>
            <link>https://medium.com/@kaushikpandav16?source=rss-101d0e750e5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:34:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaushikpandav16/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[AI for ALL]]></title>
            <link>https://medium.com/@kaushikpandav16/ai-for-all-d9b9624a6cb6?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9b9624a6cb6</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[dl]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 21:05:35 GMT</pubDate>
            <atom:updated>2024-08-27T21:05:35.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwWwr9Z5Svhs13Ja6lkkgQ.png" /></figure><p>This certificate recognizes the successful completion of the ‘AI for All: From Basics to GenAI Practice’ course.</p><p>The course provided an in-depth understanding of artificial intelligence, covering fundamental concepts to advanced applications in Generative AI. Through rigorous practice and hands-on projects, the recipient has demonstrated a strong grasp of AI principles and their practical implementation, positioning themselves as a proficient practitioner in the AI landscape.</p><p>This achievement reflects a commitment to continuous learning and a passion for harnessing technology to solve real-world problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9b9624a6cb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[T20 worldcup team Score Predictor]]></title>
            <link>https://medium.com/@kaushikpandav16/introduction-60cfddc66edb?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/60cfddc66edb</guid>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[t20-world-cup]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:55:24 GMT</pubDate>
            <atom:updated>2024-07-13T18:56:06.260Z</atom:updated>
            <content:encoded><![CDATA[<p>Hellow everyOne</p><p>Have you ever tried to guess the final score of a cricket match while watching it? It’s fun, right? Well, I’ve taken this fun to the next level by creating a Cricket Score Predictor using some cool tech tools.</p><p>This web app lets you input details like which teams are playing, the city, the current score, how many overs have been bowled, how many wickets have fallen, and the runs scored in the last five overs. Then, with a click of a button, it predicts the final score of the match!</p><h3>Why Did I Make This?</h3><p>I love cricket and wanted to create something that combines my passion for the game with my interest in technology. Predicting scores can be exciting and adds an extra layer of enjoyment while watching a match. Plus, it’s a great way to learn and apply some machine learning!</p><p>Cricket is full of surprises, and guessing the final score can be a fun challenge. I created a Cricket Score Predictor that uses machine learning to predict the final score of a match. Let me show you how it works!</p><h3>How Does It Work?</h3><p>I used a machine learning model called XGBoost, which is great at making predictions. I trained this model with historical cricket match data. Then, I built a simple web app using Streamlit, which allows you to input match details and see the predicted score instantly.</p><p>I’ll walk you through how I built this app, the tools I used, and how you can use it too. Whether you’re a cricket enthusiast, a tech geek, or just curious, I hope you find this project as fun and interesting as I do.</p><h3>Tools and Technologies Used</h3><p>To build this app, I used:</p><ul><li><strong>Streamlit</strong>: A tool to create the web app.</li><li><strong>Pandas and NumPy</strong>: Libraries to handle data.</li><li><strong>RandomForest:</strong> A machine learning tool.</li><li><strong>Pickle</strong>: To save and load the trained model.</li></ul><h3>How the App Works</h3><p>The core of the app is a machine-learning model trained using RandomForest. This model was trained on historical cricket match data and can predict scores based on the input features.</p><h3>The Code</h3><p>Here’s the code for the app:</p><pre>import streamlit as st<br>import pickle<br>import pandas as pd<br>import numpy as np<br>import xgboost<br>from xgboost import XGBRegressor</pre><pre>pipe = pickle.load(open(&#39;pipe.pkl&#39;,&#39;rb&#39;))</pre><pre>teams = [&#39;Australia&#39;,<br> &#39;India&#39;,<br> &#39;Bangladesh&#39;,<br> &#39;New Zealand&#39;,<br> &#39;South Africa&#39;,<br> &#39;England&#39;,<br> &#39;West Indies&#39;,<br> &#39;Afghanistan&#39;,<br> &#39;Pakistan&#39;,<br> &#39;Sri Lanka&#39;]</pre><pre>cities = [&#39;Colombo&#39;,<br> &#39;Mirpur&#39;,<br> &#39;Johannesburg&#39;,<br> &#39;Dubai&#39;,<br> &#39;Auckland&#39;,<br> &#39;Cape Town&#39;,<br> &#39;London&#39;,<br> &#39;Pallekele&#39;,<br> &#39;Barbados&#39;,<br> &#39;Sydney&#39;,<br> &#39;Melbourne&#39;,<br> &#39;Durban&#39;,<br> &#39;St Lucia&#39;,<br> &#39;Wellington&#39;,<br> &#39;Lauderhill&#39;,<br> &#39;Hamilton&#39;,<br> &#39;Centurion&#39;,<br> &#39;Manchester&#39;,<br> &#39;Abu Dhabi&#39;,<br> &#39;Mumbai&#39;,<br> &#39;Nottingham&#39;,<br> &#39;Southampton&#39;,<br> &#39;Mount Maunganui&#39;,<br> &#39;Chittagong&#39;,<br> &#39;Kolkata&#39;,<br> &#39;Lahore&#39;,<br> &#39;Delhi&#39;,<br> &#39;Nagpur&#39;,<br> &#39;Chandigarh&#39;,<br> &#39;Adelaide&#39;,<br> &#39;Bangalore&#39;,<br> &#39;St Kitts&#39;,<br> &#39;Cardiff&#39;,<br> &#39;Christchurch&#39;,<br> &#39;Trinidad&#39;]</pre><pre>st.title(&#39;Cricket Score Predictor&#39;)</pre><pre>col1, col2 = st.columns(2)</pre><pre>with col1:<br>    batting_team = st.selectbox(&#39;Select batting team&#39;,sorted(teams))<br>with col2:<br>    bowling_team = st.selectbox(&#39;Select bowling team&#39;, sorted(teams))</pre><pre>city = st.selectbox(&#39;Select city&#39;,sorted(cities))</pre><pre>col3,col4,col5 = st.columns(3)</pre><pre>with col3:<br>    current_score = st.number_input(&#39;Current Score&#39;)<br>with col4:<br>    overs = st.number_input(&#39;Overs done(works for over&gt;5)&#39;)<br>with col5:<br>    wickets = st.number_input(&#39;Wickets out&#39;)</pre><pre>last_five = st.number_input(&#39;Runs scored in last 5 overs&#39;)</pre><pre>if st.button(&#39;Predict Score&#39;):<br>    balls_left = 120 - (overs*6)<br>    wickets_left = 10 -wickets<br>    crr = current_score/overs</pre><pre>    input_df = pd.DataFrame(<br>     {&#39;batting_team&#39;: [batting_team], &#39;bowling_team&#39;: [bowling_team],&#39;city&#39;:city, &#39;current_score&#39;: [current_score],&#39;balls_left&#39;: [balls_left], &#39;wickets_left&#39;: [wickets], &#39;crr&#39;: [crr], &#39;last_five&#39;: [last_five]})<br>    result = pipe.predict(input_df)<br>    st.header(&quot;Predicted Score - &quot; + str(int(result[0])))</pre><h3>How It Works</h3><ol><li><strong>User Input</strong>: You select the batting team, bowling team, and city. You also enter the current score, overs bowled, wickets lost, and runs scored in the last five overs.</li><li><strong>Feature Calculation</strong>: The app calculates balls left and current run rate (CRR).</li><li><strong>Prediction</strong>: The model predicts the final score using these inputs.</li></ol><p>Like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*AyZuUYMNNbcjFMph.png" /></figure><p>Let’s try it,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*730XSjJvSEYQjiDm.png" /></figure><h3>Conclusion</h3><p>I’ve created the Cricket Score Predictor, blending my passion for cricket with machine learning and web development.</p><p>It’s a handy tool for cricket enthusiasts to predict match scores. Give it a try and see how it performs with your favorite matches! Your feedback and support mean a lot to me, so stay tuned for more updates.</p><p>stay Home, And watch T20 Worldcup champions 🥳🥳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60cfddc66edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face-Mask Detection Using TensorFlow]]></title>
            <link>https://medium.com/@kaushikpandav16/face-mask-detection-using-tenserflow-646e24c3e2af?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/646e24c3e2af</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[face-mask-detection]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:45:21 GMT</pubDate>
            <atom:updated>2024-07-13T18:45:54.079Z</atom:updated>
            <content:encoded><![CDATA[<p>Face mask detection application combines machine learning, computer vision, and web development. In this guide, I’ll guide you through building a face mask detection app using Streamlit, OpenCV, and TensorFlow. This app enables users to upload images or use their webcam to detect whether individuals in photos are wearing face masks.</p><h3>Getting Started</h3><p>Before diving into the code, make sure you have the following libraries installed:</p><ul><li>Streamlit: for creating the web application</li><li>OpenCV: for image processing</li><li>TensorFlow: for loading the pre-trained model</li><li>PIL (Python Imaging Library): for image manipulation</li><li>NumPy: for numerical operations</li></ul><p>You can install these libraries using pip:</p><pre>pip install streamlit opencv-python tensorflow pillow numpy</pre><h3>Setting the Project</h3><p>First, let’s set up the main structure of our Streamlit app. Create a file called app.py and start by importing the necessary libraries and configuring Streamlit:</p><pre>import streamlit as st<br>from PIL import Image<br>import numpy as np<br>import cv2<br>import os<br>from tensorflow.keras.applications.mobilenet_v2 import preprocess_input<br>from tensorflow.keras.preprocessing.image import img_to_array<br>from tensorflow.keras.models import load_model</pre><pre># Set up the page configuration<br>st.set_page_config(page_title=&#39;Face Mask Detector&#39;, page_icon=&#39;😷&#39;, layout=&#39;centered&#39;, initial_sidebar_state=&#39;expanded&#39;)</pre><h3>Add Custom CSS</h3><p>To make our app look more polished, we can add some custom CSS:</p><pre>def local_css(file_name):<br>    with open(file_name) as f:<br>        st.markdown(f&#39;&lt;style&gt;{f.read()}&lt;/style&gt;&#39;, unsafe_allow_html=True)</pre><h3>Loading and Processing Images</h3><p>We need a function to handle image processing. This function will detect faces in an image and determine whether they are wearing masks using a pre-trained model:</p><pre>def mask_image(image_path):<br>    # Load our serialized face detector model from disk<br>    base_path = &#39;face_detector&#39;<br>    prototxtPath = os.path.join(base_path, &#39;deploy.prototxt&#39;)<br>    weightsPath = os.path.join(base_path, &#39;res10_300x300_ssd_iter_140000.caffemodel&#39;)<br>    <br>    if not os.path.exists(prototxtPath) or not os.path.exists(weightsPath):<br>        st.error(&quot;Face detector model files not found. Please check the paths.&quot;)<br>        return None</pre><pre>    net = cv2.dnn.readNet(prototxtPath, weightsPath)</pre><pre>    # Load the face mask detector model from disk<br>    model = load_model(&quot;mask_detector.h5&quot;)</pre><pre>    # Load the input image from disk and grab the image spatial dimensions<br>    st.write(f&quot;Trying to read image from: {image_path}&quot;)<br>    image = cv2.imread(image_path)<br>    if image is None:<br>        st.error(&quot;Image not found. Please upload an image first.&quot;)<br>        return None<br>    <br>    (h, w) = image.shape[:2]</pre><pre>    # Construct a blob from the image<br>    blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0))</pre><pre>    # Pass the blob through the network and obtain the face detections<br>    net.setInput(blob)<br>    detections = net.forward()</pre><pre>    # Loop over the detections<br>    for i in range(0, detections.shape[2]):<br>        confidence = detections[0, 0, i, 2]</pre><pre>        if confidence &gt; 0.5:<br>            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])<br>            (startX, startY, endX, endY) = box.astype(&quot;int&quot;)<br>            (startX, startY) = (max(0, startX), max(0, startY))<br>            (endX, endY) = (min(w - 1, endX), min(h - 1, endY))</pre><pre>            face = image[startY:endY, startX:endX]<br>            face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)<br>            face = cv2.resize(face, (224, 224))<br>            face = img_to_array(face)<br>            face = preprocess_input(face)<br>            face = np.expand_dims(face, axis=0)</pre><pre>            (mask, withoutMask) = model.predict(face)[0]</pre><pre>            label = &quot;Mask&quot; if mask &gt; withoutMask else &quot;No Mask&quot;<br>            color = (0, 255, 0) if label == &quot;Mask&quot; else (238, 130, 238)  # Violet color</pre><pre>            label = &quot;{}: {:.2f}%&quot;.format(label, max(mask, withoutMask) * 100)</pre><pre>            cv2.putText(image, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)<br>            cv2.rectangle(image, (startX, startY), (endX, endY), color, 2)<br>    <br>    return image</pre><h3>Creating the Streamlit Interface</h3><p>Next, we need to build the interface for our app. This interface will allow users to choose between uploading an image or using their webcam for mask detection:</p><pre>def mask_detection():<br>    st.markdown(&#39;&lt;h1 align=&quot;center&quot;&gt;😷 Face Mask Detection&lt;/h1&gt;&#39;, unsafe_allow_html=True)<br>    activities = [&quot;Image&quot;, &quot;Webcam&quot;]<br>    st.set_option(&#39;deprecation.showfileUploaderEncoding&#39;, False)<br>    st.sidebar.markdown(&quot;# Mask Detection on?&quot;)<br>    choice = st.sidebar.selectbox(&quot;Choose among the given options:&quot;, activities)</pre><pre>    if choice == &#39;Image&#39;:<br>        st.markdown(&#39;&lt;h2 align=&quot;center&quot;&gt;Detection on Image&lt;/h2&gt;&#39;, unsafe_allow_html=True)<br>        st.markdown(&quot;### Upload your image here ⬇&quot;)<br>        image_file = st.file_uploader(&quot;&quot;, type=[&#39;jpg&#39;, &#39;jpeg&#39;, &#39;png&#39;])  # upload image<br>        if image_file is not None:<br>            our_image = Image.open(image_file)  # making compatible to PIL<br>            # Ensure the images directory exists<br>            if not os.path.exists(&#39;./images&#39;):<br>                os.makedirs(&#39;./images&#39;)<br>            image_path = &#39;./images/out.jpg&#39;<br>            our_image.save(image_path)<br>            st.image(image_file, caption=&#39;&#39;, use_column_width=True)<br>            st.markdown(&#39;&lt;h3 align=&quot;center&quot;&gt;Image uploaded successfully!&lt;/h3&gt;&#39;, unsafe_allow_html=True)<br>            if st.button(&#39;Process&#39;):<br>                result_image = mask_image(image_path)<br>                if result_image is not None:<br>                    st.image(result_image, use_column_width=True)</pre><pre>    if choice == &#39;Webcam&#39;:<br>        st.markdown(&#39;&lt;h2 align=&quot;center&quot;&gt;Detection on Webcam&lt;/h2&gt;&#39;, unsafe_allow_html=True)<br>        run_webcam()</pre><pre>def run_webcam():<br>    # Initialize webcam<br>    cap = cv2.VideoCapture(0)<br>    stframe = st.empty()<br>    <br>    base_path = &#39;face_detector&#39;<br>    prototxtPath = os.path.join(base_path, &#39;deploy.prototxt&#39;)<br>    weightsPath = os.path.join(base_path, &#39;res10_300x300_ssd_iter_140000.caffemodel&#39;)<br>    <br>    if not os.path.exists(prototxtPath) or not os.path.exists(weightsPath):<br>        st.error(&quot;Face detector model files not found. Please check the paths.&quot;)<br>        return</pre><pre>    net = cv2.dnn.readNet(prototxtPath, weightsPath)<br>    model = load_model(&quot;mask_detector.h5&quot;)</pre><pre>    while cap.isOpened():<br>        ret, frame = cap.read()<br>        if not ret:<br>            st.error(&quot;Failed to capture image from webcam.&quot;)<br>            break</pre><pre>        (h, w) = frame.shape[:2]<br>        blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104.0, 177.0, 123.0))<br>        net.setInput(blob)<br>        detections = net.forward()</pre><pre>        for i in range(0, detections.shape[2]):<br>            confidence = detections[0, 0, i, 2]<br>            if confidence &gt; 0.5:<br>                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])<br>                (startX, startY, endX, endY) = box.astype(&quot;int&quot;)<br>                (startX, startY) = (max(0, startX), max(0, startY))<br>                (endX, endY) = (min(w - 1, endX), min(h - 1, endY))</pre><pre>                face = frame[startY:endY, startX:endX]<br>                face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)<br>                face = cv2.resize(face, (224, 224))<br>                face = img_to_array(face)<br>                face = preprocess_input(face)<br>                face = np.expand_dims(face, axis=0)</pre><pre>                (mask, withoutMask) = model.predict(face)[0]</pre><pre>                label = &quot;Mask&quot; if mask &gt; withoutMask else &quot;No Mask&quot;<br>                color = (0, 255, 0) if label == &quot;Mask&quot; else (238, 130, 238)</pre><pre>                label = &quot;{}: {:.2f}%&quot;.format(label, max(mask, withoutMask) * 100)</pre><pre>                cv2.putText(frame, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)<br>                cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)</pre><pre>        stframe.image(frame, channels=&quot;BGR&quot;, use_column_width=True)</pre><pre>    cap.release()<br>    cv2.destroyAllWindows()</pre><pre>mask_detection()</pre><h3>Running the Webcam for Real-Time Detection</h3><p>To enable real-time mask detection using the webcam, we use OpenCV to capture video frames and apply the face mask detection model to each frame:</p><pre>def run_webcam():<br>    cap = cv2.VideoCapture(0)<br>    stframe = st.empty()<br>    <br>    base_path = &#39;face_detector&#39;<br>    prototxtPath = os.path.join(base_path, &#39;deploy.prototxt&#39;)<br>    weightsPath = os.path.join(base_path, &#39;res10_300x300_ssd_iter_140000.caffemodel&#39;)<br>    <br>    if not os.path.exists(prototxtPath) or not os.path.exists(weightsPath):<br>        st.error(&quot;Face detector model files not found. Please check the paths.&quot;)<br>        return</pre><pre>    net = cv2.dnn.readNet(prototxtPath, weightsPath)<br>    model = load_model(&quot;mask_detector.h5&quot;)</pre><pre>    while cap.isOpened():<br>        ret, frame = cap.read()<br>        if not ret:<br>            st.error(&quot;Failed to capture image from webcam.&quot;)<br>            break</pre><pre>        (h, w) = frame.shape[:2]<br>        blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104.0, 177.0, 123.0))<br>        net.setInput(blob)<br>        detections = net.forward()</pre><pre>        for i in range(0, detections.shape[2]):<br>            confidence = detections[0, 0, i, 2]<br>            if confidence &gt; 0.5:<br>                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])<br>                (startX, startY, endX, endY) = box.astype(&quot;int&quot;)<br>                (startX, startY) = (max(0, startX), max(0, startY))<br>                (endX, endY) = (min(w - 1, endX), min(h - 1, endY))</pre><pre>                face = frame[startY:endY, startX:endX]<br>                face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)<br>                face = cv2.resize(face, (224, 224))<br>                face = img_to_array(face)<br>                face = preprocess_input(face)<br>                face = np.expand_dims(face, axis=0)</pre><pre>                (mask, withoutMask) = model.predict(face)[0]</pre><pre>                label = &quot;Mask&quot; if mask &gt; withoutMask else &quot;No Mask&quot;<br>                color = (0, 255, 0) if label == &quot;Mask&quot; else (238, 130, 238)</pre><pre>                label = &quot;{}: {:.2f}%&quot;.format(label, max(mask, withoutMask) * 100)</pre><pre>                cv2.putText(frame, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)<br>                cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)</pre><pre>        stframe.image(frame, channels=&quot;BGR&quot;, use_column_width=True)</pre><pre>    cap.release()<br>    cv2.destroy</pre><h3>Summary</h3><ul><li><strong>Page Configuration</strong>: Sets up the page with a custom title, icon, and layout.</li><li><strong>Custom CSS</strong>: Allows for custom styling of the app.</li><li><strong>Mask Image Function</strong>: Handles image processing, face detection, and mask prediction.</li><li><strong>Mask Detection Function</strong>: Provides a user interface for choosing between image and webcam detection.</li><li><strong>Webcam Detection Function</strong>: Handles real-time face mask detection using the webcam.</li><li><strong>Main Function Call</strong>: Initiates the mask detection process.</li></ul><h3>Preview of this</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*_nU65Gl0alM1FAas.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*7xu3Ry9SHgKEVp9b.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*fbZXlNW6239l-z9m.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*p9yGoy6SavfXsEyF.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*9DXSyrraCUcI_Z-Q.png" /></figure><h3>Conclusion</h3><p>The Face Mask Detection app offers an easy way to spot face masks in photos and live webcam streams. By using advanced deep learning models and Streamlit’s interactive design,</p><p>it ensures precise and effective mask detection. It memorise thing of 2020 😅😅.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=646e24c3e2af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Posture Detection]]></title>
            <link>https://medium.com/@kaushikpandav16/posture-detection-37ef428993fd?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/37ef428993fd</guid>
            <category><![CDATA[ml-project]]></category>
            <category><![CDATA[posture-detection]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:38:08 GMT</pubDate>
            <atom:updated>2024-07-13T18:38:08.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>this interactive posture detection system uses PoseNet, a state-of-the-art pose estimation model, along with the p5.js library. This system will use a webcam to capture live video, detect key points on the human body, and overlay images and graphics on these points in real time.</p><h3>Technologies Used</h3><ul><li><strong>Posenet</strong>: A machine learning model that allows for real-time human pose estimation.</li><li><strong>p5.js</strong>: A JavaScript library that makes coding accessible for artists, designers, educators, and beginners.</li><li><strong>ml5.js</strong>: A friendly high-level interface to TensorFlow.js, which simplifies the integration of machine learning models into web applications.</li></ul><h3>Application Overview</h3><p>The posture detection system captures live video from a webcam, processes it through the PoseNet model to detect key points on the body, and then visualizes these points along with skeletal connections. Additionally, we can overlay custom images, like glasses or hats, on specific key points, such as the nose or eyes.<br>Like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K4PD-3dpLm7s1Ezr.png" /></figure><h3>Code Implementation</h3><p><strong>sketch.js</strong></p><pre>let capture;<br>let posenet;<br>let noseX, noseY;<br>let reyeX, reyeY;<br>let leyeX, leyeY;<br>let singlePose, skeleton;<br>let face;<br>let specs;</pre><pre>function setup() {<br>    createCanvas(600, 500);<br>    capture = createCapture(VIDEO);<br>    capture.hide();</pre><pre>    posenet = ml5.poseNet(capture, modelLoaded);<br>    posenet.on(&#39;pose&#39;, receivedPoses);</pre><pre>    face = loadImage(&#39;images/face.png&#39;);<br>    specs = loadImage(&#39;images/specs.png&#39;);<br>}</pre><pre>function receivedPoses(poses){<br>    console.log(poses);</pre><pre>    if(poses.length &gt; 0){<br>        singlePose = poses[0].pose;<br>        skeleton = poses[0].skeleton;<br>    }<br>}</pre><pre>function modelLoaded(){<br>    console.log(&#39;Model has loaded&#39;);<br>}</pre><pre>function draw(){<br>    image(capture, 0, 0);<br>    fill(0, 0, 255);</pre><pre>    if(singlePose){<br>        for(let i = 0; i &lt; singlePose.keypoints.length; i++){<br>            ellipse(singlePose.keypoints[i].position.x, singlePose.keypoints[i].position.y, 20);<br>        }</pre><pre>        stroke(255, 255, 255); <br>        strokeWeight(3);<br>        for(let j = 0; j &lt; skeleton.length; j++){<br>            line(skeleton[j][0].position.x, skeleton[j][0].position.y, skeleton[j][1].position.x, skeleton[j][1].position.y);<br>        }</pre><pre>        image(specs, singlePose.nose.x - 80, singlePose.nose.y - 80, 160, 70);<br>    }<br>}</pre><p><strong>sample.js</strong></p><pre>let capture;<br>let posenet;<br>let noseX, noseY;<br>let reyeX, reyeY;<br>let leyeX, leyeY;<br>let singlePose, skeleton;<br>let face;<br>let specs;</pre><pre>function setup() {<br>    createCanvas(600, 500);<br>    capture = createCapture(VIDEO);<br>    capture.hide();</pre><pre>    posenet = ml5.poseNet(capture, modelLoaded);<br>    posenet.on(&#39;pose&#39;, receivedPoses)</pre><pre>    // image<br>    // taj_mahal =  loadImage(&#39;images/taj.jpeg&#39;)<br>    face =  loadImage(&#39;images/face.png&#39;)<br>    specs =  loadImage(&#39;images/specs.png&#39;)<br>    <br>}</pre><pre>function receivedPoses(poses){<br>    console.log(poses);</pre><pre>    if(poses.length &gt; 0){<br>        singlePose = poses[0].pose;</pre><pre>        skeleton = poses[0].skeleton;<br>    }<br>}</pre><pre>function modelLoaded(){<br>    console.log(&#39;Model has loaded&#39;);<br>}</pre><pre>function draw(){</pre><pre>    // image &amp; videos(webcam)<br>    image(capture, 0, 0);<br>    fill(0, 0, 255);</pre><pre>    if(singlePose){<br>        for(let i=0; i&lt;singlePose.keypoints.length; i++){<br>            ellipse(singlePose.keypoints[i].position.x, singlePose.keypoints[i].position.y, 20);<br>        }</pre><pre>        stroke(255,255,255); <br>        strokeWeight(3);<br>        for(let j=0; j&lt;skeleton.length; j++){<br>            line(skeleton[j][0].position.x, skeleton[j][0].position.y, skeleton[j][1].position.x, skeleton[j][1].position.y);<br>        }</pre><pre>        image(specs, singlePose.nose.x-80, singlePose.nose.y-80, 160, 70);<br>    }<br>    <br>}</pre><h3>HTML Structure</h3><p>The HTML file sets up the environment for the p5.js sketch and includes the necessary scripts for ml5.js and p5.js.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;Posture Detection&lt;/title&gt;<br>    &lt;script src=&quot;https://unpkg.com/ml5@latest/dist/ml5.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/p5@1.9.4/lib/p5.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;sketch.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Hello, It is Posture Detection.&lt;/h1&gt; <br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Conclusion</h3><p>Creating a posture detection system with Posenet and p5.js is an exciting way to explore the capabilities of real-time machine learning and computer vision.</p><p>This project demonstrates how accessible these technologies have become, allowing developers to build interactive and engaging applications that can understand and respond to human movements.</p><p>By further customizing and expanding this setup, a wide range of applications can be developed, from fitness trackers to interactive art installations, So also you can all those checkouts.</p><p>thank you guys, for your interaction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37ef428993fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Recommender System Using ML]]></title>
            <link>https://medium.com/@kaushikpandav16/book-recommender-system-using-ml-9f27a4f9b043?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f27a4f9b043</guid>
            <category><![CDATA[ai-ml-development]]></category>
            <category><![CDATA[book-recommendations]]></category>
            <category><![CDATA[ml-project]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:30:33 GMT</pubDate>
            <atom:updated>2024-07-13T18:30:33.638Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog dives into the development of a Book Recommender System powered by data science and machine learning. Utilizing Streamlit, a versatile Python framework known for its ability to create interactive web applications, alongside Pickle for storing and accessing trained models, we explore how such systems revolutionize the way readers discover and engage with books tailored to their unique preferences.</p><h3>Overview of the Project</h3><p>The project focuses on developing a Book Recommender System that allows users to discover new books based on their preferences and similarities to other books. It employs collaborative filtering techniques, where the system recommends items (books, in this case) by identifying patterns from the preferences or behaviors of multiple users.</p><h3>Implementation Details</h3><p><strong>1. Technologies Used:</strong></p><ul><li><strong>Streamlit:</strong> A Python library for creating web applications with minimal effort, used here for the user interface.</li><li><strong>Pickle:</strong> Python’s serialization module for saving and loading machine learning models and data structures.</li><li><strong>Numpy:</strong> For numerical operations and array manipulations.</li></ul><p><strong>2. Components of the System:</strong></p><ul><li><strong>Data Preparation:</strong> Initially, the system processes and prepares book data, including titles, authors, images, and user ratings.</li><li><strong>Model Building:</strong> The core of the system involves building a collaborative filtering model that calculates similarities between books based on user ratings.</li><li><strong>Interactive Interface:</strong> Using Streamlit, the system provides a user-friendly interface where users can input a book title and receive recommendations of similar books.</li></ul><p><strong>3. User Experience:</strong></p><ul><li><strong>Home Page:</strong> The application features a home page with a welcoming interface showcasing top-rated books. Each book is displayed with its title, author, cover image, and user ratings.</li><li><strong>Recommender Page:</strong> Users can interact with the recommender system by entering a book title of interest. The system then retrieves and displays a list of recommended books based on similarity scores derived from collaborative filtering.</li></ul><p><strong>4. Technical Challenges and Solutions:</strong></p><ul><li><strong>Data Handling:</strong> Managing and preprocessing large datasets of books and user ratings.</li><li><strong>Model Deployment:</strong> Integrating the machine learning model into the Streamlit application and ensuring real-time responsiveness.</li><li><strong>User Interface Design:</strong> Designing an intuitive and visually appealing interface that enhances user engagement.</li></ul><h3>Building a Book Recommender System</h3><p>To begin, let’s outline the foundational steps involved in constructing our Book Recommender System:</p><p><strong>1.Data Acquisition and Preparation</strong>:</p><pre>import pandas as pd<br>import numpy as np<br>import pickle</pre><pre># Load preprocessed data and models<br>final_rating = pickle.load(open(&#39;models/final_rating.pkl&#39;, &#39;rb&#39;))<br>book_pivot = pickle.load(open(&#39;models/book_pivot.pkl&#39;, &#39;rb&#39;))<br>books = pickle.load(open(&#39;models/books.pkl&#39;, &#39;rb&#39;))<br>similarity_scores = pickle.load(open(&#39;models/similarity_scores.pkl&#39;, &#39;rb&#39;))</pre><ul><li>Here, we load the necessary datasets and pre-trained models using pickle for seamless integration into our application.</li></ul><p><strong>2.Interactive Web Interface with Streamlit</strong>:</p><pre>import streamlit as st</pre><pre># Set up Streamlit configuration<br>st.set_page_config(<br>    page_title=&quot;Book Recommender&quot;,<br>    page_icon=&quot;book&quot;,<br>    layout=&quot;wide&quot;<br>)</pre><pre>def main():<br>    with st.sidebar:<br>        selected_mode = st.radio(&quot;Select Mode&quot;, [&quot;Home&quot;, &quot;Recommender&quot;])</pre><pre>    if selected_mode == &quot;Home&quot;:<br>        st.title(&quot;Book Recommender System&quot;)<br>        # Display introductory content and top books<br>        st.write(&quot;Welcome to our Book Recommender System!&quot;)<br>        st.write(&quot;Here are some of the top-rated books:&quot;)<br>        for title, author, img_url, votes in zip(final_rating[&#39;title&#39;], final_rating[&#39;author&#39;], final_rating[&#39;img_url_m&#39;], final_rating[&#39;no_of_rating&#39;]):<br>            st.image(img_url, width=100)<br>            st.write(f&quot;**{title}** by {author}&quot;)<br>            st.write(f&quot;Votes: {votes}&quot;)<br>            st.write(&quot;---&quot;)</pre><pre>    elif selected_mode == &quot;Recommender&quot;:<br>        st.title(&quot;Book Recommender Tool&quot;)<br>        user_input = st.text_input(&quot;Enter a book title&quot;)<br>        # Perform book recommendation based on user input<br>        if user_input:<br>            try:<br>                index = np.where(book_pivot.index == user_input)[0][0]<br>                similar_items = sorted(<br>                    list(enumerate(similarity_scores[index])),<br>                    key=lambda x: x[1],<br>                    reverse=True<br>                )[1:5]</pre><pre>                st.write(&quot;### Recommended Books&quot;)<br>                for i in similar_items:<br>                    temp_df = books[books[&#39;title&#39;] == book_pivot.index[i[0]]]<br>                    title = temp_df[&#39;title&#39;].values[0]<br>                    author = temp_df[&#39;author&#39;].values[0]<br>                    img_url = temp_df[&#39;img_url_m&#39;].values[0]<br>                    st.image(img_url, width=100)<br>                    st.write(f&quot;**{title}** by {author}&quot;)<br>                    st.write(&quot;---&quot;)<br>            except IndexError:<br>                st.write(&quot;Book not found. Please check the title and try again.&quot;)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>3.User Interaction and Output</strong>:</p><ul><li><strong>Home Mode</strong>: Displays an introduction to the recommender system and showcases top-rated books based on user ratings.</li><li><strong>Recommender Mode</strong>: Allows users to input a book title of interest, which triggers the system to recommend similar books based on collaborative filtering.</li></ul><p>It’s look like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*0nsNFk91MsPJ8ps9.png" /></figure><p>On ‘Recommender’ section,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*9Fbig7_jsPZtBORw.png" /></figure><p>That’s it.</p><h3>Conclusion</h3><p>This bookRecommender System not only boosts user engagement but also showcases the practical application of data science. Whether discovering new books or enjoying personalized recommendations, this system demonstrates how technology enhances the digital reading experience.</p><p>Thank you for your time; it’s been a rewarding experience</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f27a4f9b043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction:]]></title>
            <link>https://medium.com/@kaushikpandav16/introduction-564ec190acb7?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/564ec190acb7</guid>
            <category><![CDATA[ipl-data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ml-project]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:23:32 GMT</pubDate>
            <atom:updated>2024-07-13T18:24:28.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>IPL win probabilities: using ML</h3><p>In the dynamic realm of IPL cricket, predicting match outcomes isn’t merely a pastime — it’s a scientific endeavor! Employing cutting-edge machine learning techniques, we set out to forecast which team gains the advantage in pivotal match scenarios.</p><p>Our journey began with compiling extensive IPL match data, meticulously recording every delivery, run scored, and the wicket has fallen. We curated our dataset to encompass complete matches without rain interruptions, ensuring the accuracy and reliability of our analysis.</p><p>Used dataset : <a href="https://www.kaggle.com/datasets/ramjidoolla/ipl-data-set">https://www.kaggle.com/datasets/ramjidoolla/ipl-data-set</a></p><p>Dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*wd_XngcNukeMiXh6.png" /></figure><h3>Preprocessing on data and Feature Engineering</h3><p>Cleaning and preparing the data was no small feat. We engineered features like current run rate (CRR), required run rate (RRR), and innings progress indicators to capture the evolving dynamics of each match.</p><h3>Machine Learning Model</h3><p>Deploying a sophisticated Logistic Regression model trained on historical match data, we built a robust predictor. This model learned from past performances of teams, considering factors like batting strength, bowling prowess, and even the influence of playing cities.</p><h3>Interactive Web Application</h3><p>To bring our findings to life, we developed an interactive web app using Streamlit. This app allows cricket enthusiasts to input live match parameters — such as current score, overs bowled, and wickets fallen — to instantly get predictions on the likelihood of each team’s victory.</p><p>app.py:</p><pre>import streamlit as st<br>import pickle<br>import pandas as pd</pre><pre>teams = [&#39;Sunrisers Hyderabad&#39;,<br> &#39;Mumbai Indians&#39;,<br> &#39;Royal Challengers Bangalore&#39;,<br> &#39;Kolkata Knight Riders&#39;,<br> &#39;Kings XI Punjab&#39;,<br> &#39;Chennai Super Kings&#39;,<br> &#39;Rajasthan Royals&#39;,<br> &#39;Delhi Capitals&#39;]</pre><pre>cities = [&#39;Hyderabad&#39;, &#39;Bangalore&#39;, &#39;Mumbai&#39;, &#39;Indore&#39;, &#39;Kolkata&#39;, &#39;Delhi&#39;,<br>       &#39;Chandigarh&#39;, &#39;Jaipur&#39;, &#39;Chennai&#39;, &#39;Cape Town&#39;, &#39;Port Elizabeth&#39;,<br>       &#39;Durban&#39;, &#39;Centurion&#39;, &#39;East London&#39;, &#39;Johannesburg&#39;, &#39;Kimberley&#39;,<br>       &#39;Bloemfontein&#39;, &#39;Ahmedabad&#39;, &#39;Cuttack&#39;, &#39;Nagpur&#39;, &#39;Dharamsala&#39;,<br>       &#39;Visakhapatnam&#39;, &#39;Pune&#39;, &#39;Raipur&#39;, &#39;Ranchi&#39;, &#39;Abu Dhabi&#39;,<br>       &#39;Sharjah&#39;, &#39;Mohali&#39;, &#39;Bengaluru&#39;]</pre><pre>pipe = pickle.load(open(&#39;pipe.pkl&#39;,&#39;rb&#39;))<br>st.title(&#39;IPL Win Predictor&#39;)</pre><pre>col1, col2 = st.columns(2)</pre><pre>with col1:<br>    batting_team = st.selectbox(&#39;Select the batting team&#39;,sorted(teams))<br>with col2:<br>    bowling_team = st.selectbox(&#39;Select the bowling team&#39;,sorted(teams))</pre><pre>selected_city = st.selectbox(&#39;Select host city&#39;,sorted(cities))</pre><pre>target = st.number_input(&#39;Target&#39;)</pre><pre>col3,col4,col5 = st.columns(3)</pre><pre>with col3:<br>    score = st.number_input(&#39;Score&#39;)<br>with col4:<br>    overs = st.number_input(&#39;Overs completed&#39;)<br>with col5:<br>    wickets = st.number_input(&#39;Wickets out&#39;)</pre><pre>if st.button(&#39;Predict Probability&#39;):<br>    runs_left = target - score<br>    balls_left = 120 - (overs*6)<br>    wickets = 10 - wickets<br>    crr = score/overs<br>    rrr = (runs_left*6)/balls_left</pre><pre>    input_df = pd.DataFrame({&#39;batting_team&#39;:[batting_team],&#39;bowling_team&#39;:[bowling_team],&#39;city&#39;:[selected_city],&#39;runs_left&#39;:[runs_left],&#39;balls_left&#39;:[balls_left],&#39;wickets&#39;:[wickets],&#39;total_runs_x&#39;:[target],&#39;crr&#39;:[crr],&#39;rrr&#39;:[rrr]})</pre><pre>    result = pipe.predict_proba(input_df)<br>    loss = result[0][0]<br>    win = result[0][1]<br>    st.header(batting_team + &quot;- &quot; + str(round(win*100)) + &quot;%&quot;)<br>    st.header(bowling_team + &quot;- &quot; + str(round(loss*100)) + &quot;%&quot;)</pre><h3>Visualizing Match Dynamics</h3><p>Through compelling visualizations, we illustrated the nail-biting tension of IPL matches. Graphs dynamically displayed the fluctuating fortunes — runs scored, wickets taken, and win probabilities shifting in real-time as matches progressed.</p><p>Let’s see,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*g_bNeOqUBuUWR9Sj.png" /></figure><p>Do changes on this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*8_2gBEmUNopAumyK.png" /></figure><p>Uhh that’s it of my side, you can also give some suggestions I’m waiting for it.</p><h3>Conclusion</h3><p>Our journey into predicting IPL match outcomes wasn’t just about numbers — it was about decoding the pulse of cricketing battles. Whether you’re a fan, analyst, or team strategist, our predictive insights offer a fascinating glimpse into the future of sports analytics.</p><h3>Future Endeavors</h3><p>Looking ahead, we aim to enhance our model with more nuanced features and explore ensemble techniques for even sharper predictions. The evolution of cricket analytics continues, and we’re excited to be at the forefront.</p><p>Jio Dhan Dhanadhan 😅😅, interact with the app and dive deeper into the stats.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=564ec190acb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Laptop Prices: A Machine Learning project]]></title>
            <link>https://medium.com/@kaushikpandav16/predicting-laptop-prices-a-machine-learning-project-8eb0a0282457?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eb0a0282457</guid>
            <category><![CDATA[laptop-price]]></category>
            <category><![CDATA[ml-project]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:15:37 GMT</pubDate>
            <atom:updated>2024-07-13T18:15:37.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the world of laptops, understanding the factors that influence pricing can be complex yet crucial for both consumers and manufacturers. This project aims to predict laptop prices using machine learning techniques, leveraging a dataset that includes various specifications such as RAM, weight, screen size, CPU type, storage options, GPU brand, and operating system.</p><h3>Dataset Overview</h3><p>The dataset used for this project contains detailed information about different laptop models, including their specifications and prices. It was processed to handle missing values, convert categorical variables into numeric representations, and engineer new features like PPI (Pixels Per Inch), which helps quantify display quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*QQLIXB7EiCV2K4G_.png" /></figure><h3>Exploratory Data Analysis (EDA)</h3><p>The EDA section involved exploring key characteristics of the dataset:</p><ul><li><strong>Data Cleaning:</strong> Removed unnecessary columns and cleaned up textual data like RAM and weight.</li><li><strong>Visualization:</strong> Utilized visualizations (bar plots, histograms, heatmaps) to understand the distribution and relationships between variables such as laptop prices across different brands, types, and operating systems.</li></ul><h3>Feature Engineering</h3><p>Transformed the dataset by creating new features such as touchscreen availability, IPS display, and separating storage into HDD and SSD categories. Additionally, the resolution data was parsed to calculate PPI for each laptop model.</p><h3>Model Deployment</h3><p>The best-performing model (Stacking Regressor) was selected and deployed using Streamlit, allowing users to input laptop specifications such as brand, type, RAM, weight, etc., and receive a predicted price based on the trained model.</p><p>App.py:</p><pre>import streamlit as st<br>import pickle<br>import numpy as np</pre><pre># import the model<br>pipe = pickle.load(open(&#39;pipe.pkl&#39;,&#39;rb&#39;))<br>df = pickle.load(open(&#39;df.pkl&#39;,&#39;rb&#39;))</pre><pre>st.title(&quot;Laptop Predictor&quot;)</pre><pre># brand<br>company = st.selectbox(&#39;Brand&#39;,df[&#39;Company&#39;].unique())</pre><pre># type of laptop<br>type = st.selectbox(&#39;Type&#39;,df[&#39;TypeName&#39;].unique())</pre><pre># Ram<br>ram = st.selectbox(&#39;RAM(in GB)&#39;,[2,4,6,8,12,16,24,32,64])</pre><pre># weight<br>weight = st.number_input(&#39;Weight of the Laptop&#39;)</pre><pre># Touchscreen<br>touchscreen = st.selectbox(&#39;Touchscreen&#39;,[&#39;No&#39;,&#39;Yes&#39;])</pre><pre># IPS<br>ips = st.selectbox(&#39;IPS&#39;,[&#39;No&#39;,&#39;Yes&#39;])</pre><pre># screen size<br>screen_size = st.number_input(&#39;Screen Size&#39;)</pre><pre># resolution<br>resolution = st.selectbox(&#39;Screen Resolution&#39;,[&#39;1920x1080&#39;,&#39;1366x768&#39;,&#39;1600x900&#39;,&#39;3840x2160&#39;,&#39;3200x1800&#39;,&#39;2880x1800&#39;,&#39;2560x1600&#39;,&#39;2560x1440&#39;,&#39;2304x1440&#39;])</pre><pre>#cpu<br>cpu = st.selectbox(&#39;CPU&#39;,df[&#39;Cpu brand&#39;].unique())</pre><pre>hdd = st.selectbox(&#39;HDD(in GB)&#39;,[0,128,256,512,1024,2048])</pre><pre>ssd = st.selectbox(&#39;SSD(in GB)&#39;,[0,8,128,256,512,1024])</pre><pre>gpu = st.selectbox(&#39;GPU&#39;,df[&#39;Gpu brand&#39;].unique())</pre><pre>os = st.selectbox(&#39;OS&#39;,df[&#39;os&#39;].unique())</pre><pre>if st.button(&#39;Predict Price&#39;):<br>    # query<br>    ppi = None<br>    if touchscreen == &#39;Yes&#39;:<br>        touchscreen = 1<br>    else:<br>        touchscreen = 0</pre><pre>    if ips == &#39;Yes&#39;:<br>        ips = 1<br>    else:<br>        ips = 0</pre><pre>    X_res = int(resolution.split(&#39;x&#39;)[0])<br>    Y_res = int(resolution.split(&#39;x&#39;)[1])<br>    ppi = ((X_res**2) + (Y_res**2))**0.5/screen_size<br>    query = np.array([company,type,ram,weight,touchscreen,ips,ppi,cpu,hdd,ssd,gpu,os])</pre><pre>    query = query.reshape(1,12)<br>    st.title(&quot;The predicted price of this configuration is &quot; + str(int(np.exp(pipe.predict(query)[0]))))</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*K80Xx7RhloIfPWZB.png" /></figure><p>Check price,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*H0eNVMvltANUM4G2.png" /></figure><p>Then go and check your laptop price.</p><h3>Conclusion</h3><p>This project demonstrates the application of machine learning techniques in predicting laptop prices, providing valuable insights into how different specifications influence pricing. By leveraging advanced regression models and streamlining the deployment through Streamlit, this tool offers a practical solution for both consumers and manufacturers in the laptop industry.</p><p>stay safe, and check specifications 😅😅</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eb0a0282457" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game of Thrones Personality Matcher with Machine Learning]]></title>
            <link>https://medium.com/@kaushikpandav16/game-of-thrones-personality-matcher-with-machine-learning-af4b66ab514a?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/af4b66ab514a</guid>
            <category><![CDATA[mlblogs]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlposts]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[game-of-thrones]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:10:19 GMT</pubDate>
            <atom:updated>2024-07-13T18:10:19.863Z</atom:updated>
            <content:encoded><![CDATA[<p>Game of Thrones, one of the most popular TV series of all time, has a vast array of intriguing characters. Wouldn’t it be fascinating to know which character from the series closely matches your personality? In this project, we’ll create a “Game of Thrones Personality Matcher” using Streamlit. This app allows users to select a character and find another character who closely matches them based on certain attributes. We’ll also use an API to fetch character images to enhance the visual appeal of our app.</p><h3>Dataset and Preprocessing</h3><p>For this project, we’ll use a dataset containing various attributes of Game of Thrones characters. Additionally, we’ll use the ThronesAPI to fetch images of the characters.</p><p>Dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*hSt-aw1he7CpXQ5g.png" /></figure><p>We start by loading and preprocessing the dataset:</p><pre>import streamlit as st<br>import pickle<br>import requests<br>import numpy as np</pre><pre># Load the ThronesAPI data<br>api_data = requests.get(&quot;https://thronesapi.com/api/v2/Characters&quot;).json()</pre><pre># Load the dataset<br>df = pickle.load(open(&#39;new_data.pkl&#39;,&#39;rb&#39;))<br>df = df.head(25)</pre><pre># Preprocess character names<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Jaime&#39;,&#39;Jamie&#39;)<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Lord Varys&#39;,&#39;Varys&#39;)<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Bronn&#39;,&#39;Lord Bronn&#39;)<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Sandor Clegane&#39;,&#39;The Hound&#39;)<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Robb Stark&#39;,&#39;Rob Stark&#39;)</pre><h3>Fetching Character Images</h3><p>We use the ThronesAPI to fetch images of the characters. The fetch_image function retrieves the image URL of a given character:</p><pre>def fetch_image(name, api_data):<br>    for item in api_data:<br>        if item[&#39;fullName&#39;] == name:<br>            return item[&#39;imageUrl&#39;]</pre><h3>Streamlit App</h3><p>We create the Streamlit app with a dropdown to select a character and display the closest match based on the 2D coordinates:</p><pre>st.title(&quot;Game Of Thrones Personality Matcher&quot;)</pre><pre>characters = df[&#39;character&#39;].values</pre><pre>selected_character = st.selectbox(&quot;Select a character&quot;,characters)</pre><pre># fetch closest match<br>character_id = np.where(df[&#39;character&#39;].values == selected_character)[0][0]<br>x = df[[&#39;x&#39;,&#39;y&#39;]].values</pre><pre>distances = []<br>for i in range(len(x)):<br>    distances.append(np.linalg.norm(x[character_id] - x[i]))</pre><pre>recommended_id = sorted(list(enumerate(distances)),key=lambda x:x[1])[1][0]<br>recommended_character = df[&#39;character&#39;].values[recommended_id]</pre><pre>image_url = fetch_image(selected_character,api_data)<br>recommended_character_image_url = fetch_image(recommended_character,api_data)<br>col1, col2 = st.columns(2)</pre><pre>with col1:<br>    st.header(selected_character)<br>    st.image(image_url)<br>with col2:<br>    st.header(recommended_character)<br>    st.image(recommended_character_image_url)</pre><p>App.py</p><pre>import streamlit as st<br>import pickle<br>import requests<br>import numpy as np</pre><pre>api_data = requests.get(&quot;https://thronesapi.com/api/v2/Characters&quot;).json()</pre><pre>df = pickle.load(open(&#39;new_data.pkl&#39;,&#39;rb&#39;))<br>df = df.head(25)</pre><pre>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Jaime&#39;,&#39;Jamie&#39;)<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Lord Varys&#39;,&#39;Varys&#39;)<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Bronn&#39;,&#39;Lord Bronn&#39;)<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Sandor Clegane&#39;,&#39;The Hound&#39;)<br>df[&#39;character&#39;] = df[&#39;character&#39;].str.replace(&#39;Robb Stark&#39;,&#39;Rob Stark&#39;)</pre><pre>def fetch_image(name,api_data):<br>    for item in api_data:<br>        if item[&#39;fullName&#39;] == name:<br>            return item[&#39;imageUrl&#39;]</pre><pre>st.title(&quot;Game Of Thrones Personality Matcher&quot;)</pre><pre>characters = df[&#39;character&#39;].values</pre><pre>selected_character = st.selectbox(&quot;Select a character&quot;,characters)</pre><pre># fetch closest match<br>character_id = np.where(df[&#39;character&#39;].values == selected_character)[0][0]<br>x = df[[&#39;x&#39;,&#39;y&#39;]].values</pre><pre>distances = []<br>for i in range(len(x)):<br>    distances.append(np.linalg.norm(x[character_id] - x[i]))</pre><pre>recommended_id = sorted(list(enumerate(distances)),key=lambda x:x[1])[1][0]<br>recommended_character = df[&#39;character&#39;].values[recommended_id]</pre><pre>image_url = fetch_image(selected_character,api_data)<br>recommended_character_image_url = fetch_image(recommended_character,api_data)<br>col1, col2 = st.columns(2)</pre><pre>with col1:<br>    st.header(selected_character)<br>    st.image(image_url)<br>with col2:<br>    st.header(recommended_character)<br>    st.image(recommended_character_image_url)</pre><p>Preview:</p><p>Daenerys Targaryen,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*5Sy8aC_w6iFR-cO0.png" /></figure><p>Tyrion Lannister,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Y5_XK8OnhecVV5YI.png" /></figure><p>Varys,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*nIU8xj6vwLJ4OpfF.png" /></figure><p>you can effectively illustrate the functionality and user interface of your “Game of Thrones Personality Matcher” while maintaining engagement and clarity for your readers.</p><h3>Conclusion</h3><p>This Game of Thrones Personality Matcher is a fun and interactive way to engage with the beloved characters from the series. By leveraging the ThronesAPI and a preprocessed dataset, we provide users with an immersive experience that includes character images and a personality-matching feature.</p><p>Thanks for visit, and giving your valuable time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af4b66ab514a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Duplicate Question Pairs Using Machine Learning]]></title>
            <link>https://medium.com/@kaushikpandav16/detecting-duplicate-question-pairs-using-machine-learning-fbbadf295a68?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbbadf295a68</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ml-project]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[duplicate-content]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:03:51 GMT</pubDate>
            <atom:updated>2024-07-13T18:03:51.167Z</atom:updated>
            <content:encoded><![CDATA[<p>Duplicate question detection is a common problem in Natural Language Processing (NLP), especially in platforms like Quora and Stack Overflow, where users often post similar questions. In this blog, we’ll walk through a simple yet effective implementation of a duplicate question detection system using machine learning, Python, and Streamlit.</p><h3>Project Overview</h3><p>The goal of this project is to determine if two given questions are duplicates of each other. We’ll achieve this by extracting various features from the questions and training a machine learning model to predict the likelihood of duplication.</p><h3>Setting Up the Environment</h3><p>We’ll start by setting up our environment with the necessary libraries. Here’s an overview of the files involved:</p><ol><li><strong>app.py</strong>: This is the main file that runs our Streamlit web application.</li><li><strong>helper.py</strong>: This file contains helper functions for feature extraction and preprocessing.</li><li><strong>model.pkl</strong>: This is the pre-trained machine learning model used to predict duplicate questions.</li><li><strong>cv.pkl</strong>: This is the CountVectorizer model used to convert text into a bag-of-words representation.</li></ol><p><strong>To check how duplicates on datasets:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*V1vUINzlzP3HJNAP.png" /></figure><h3>The app.py File</h3><p>The app.py file is the entry point of our application. It uses Streamlit to create a simple web interface where users can input two questions and get a prediction on whether they are duplicates.</p><pre>import streamlit as st<br>import helper<br>import pickle</pre><pre>model = pickle.load(open(&#39;model.pkl&#39;,&#39;rb&#39;))</pre><pre>st.header(&#39;Duplicate Question Pairs&#39;)</pre><pre>q1 = st.text_input(&#39;Enter question 1&#39;)<br>q2 = st.text_input(&#39;Enter question 2&#39;)</pre><pre>if st.button(&#39;Find&#39;):<br>    query = helper.query_point_creator(q1,q2)<br>    result = model.predict(query)[0]</pre><pre>    if result:<br>        st.header(&#39;Duplicate&#39;)<br>    else:<br>        st.header(&#39;Not Duplicate&#39;)</pre><h3>The helper.py File</h3><p>The helper.py file contains several functions that are crucial for feature extraction and preprocessing of the input questions. Let&#39;s go through some of the key functions:</p><h3>Preprocessing Function</h3><p>The preprocess function cleans and normalizes the input questions by:</p><ul><li>Converting text to lowercase</li><li>Replacing special characters and contractions</li><li>Removing HTML tags and non-word characters</li></ul><pre>def preprocess(q):<br>    q = str(q).lower().strip()<br>    q = q.replace(&#39;%&#39;, &#39; percent&#39;)<br>    q = q.replace(&#39;$&#39;, &#39; dollar &#39;)<br>    q = q.replace(&#39;₹&#39;, &#39; rupee &#39;)<br>    q = q.replace(&#39;€&#39;, &#39; euro &#39;)<br>    q = q.replace(&#39;@&#39;, &#39; at &#39;)<br>    q = q.replace(&#39;[math]&#39;, &#39;&#39;)<br>    q = q.replace(&#39;,000,000,000 &#39;, &#39;b &#39;)<br>    q = q.replace(&#39;,000,000 &#39;, &#39;m &#39;)<br>    q = q.replace(&#39;,000 &#39;, &#39;k &#39;)<br>    q = re.sub(r&#39;([0-9]+)000000000&#39;, r&#39;\1b&#39;, q)<br>    q = re.sub(r&#39;([0-9]+)000000&#39;, r&#39;\1m&#39;, q)<br>    q = re.sub(r&#39;([0-9]+)000&#39;, r&#39;\1k&#39;, q)<br>    contractions = {&quot;ain&#39;t&quot;: &quot;am not&quot;, &quot;aren&#39;t&quot;: &quot;are not&quot;, &quot;can&#39;t&quot;: &quot;can not&quot;, &quot;can&#39;t&#39;ve&quot;: &quot;can not have&quot;, &quot;&#39;cause&quot;: &quot;because&quot;,<br>                    &quot;could&#39;ve&quot;: &quot;could have&quot;, &quot;couldn&#39;t&quot;: &quot;could not&quot;, &quot;couldn&#39;t&#39;ve&quot;: &quot;could not have&quot;, &quot;didn&#39;t&quot;: &quot;did not&quot;,<br>                    &quot;doesn&#39;t&quot;: &quot;does not&quot;, &quot;don&#39;t&quot;: &quot;do not&quot;, &quot;hadn&#39;t&quot;: &quot;had not&quot;, &quot;hadn&#39;t&#39;ve&quot;: &quot;had not have&quot;, &quot;hasn&#39;t&quot;: &quot;has not&quot;,<br>                    &quot;haven&#39;t&quot;: &quot;have not&quot;, &quot;he&#39;d&quot;: &quot;he would&quot;, &quot;he&#39;d&#39;ve&quot;: &quot;he would have&quot;, &quot;he&#39;ll&quot;: &quot;he will&quot;, &quot;he&#39;ll&#39;ve&quot;: &quot;he will have&quot;,<br>                    &quot;he&#39;s&quot;: &quot;he is&quot;, &quot;how&#39;d&quot;: &quot;how did&quot;, &quot;how&#39;d&#39;y&quot;: &quot;how do you&quot;, &quot;how&#39;ll&quot;: &quot;how will&quot;, &quot;how&#39;s&quot;: &quot;how is&quot;, &quot;i&#39;d&quot;: &quot;i would&quot;,<br>                    &quot;i&#39;d&#39;ve&quot;: &quot;i would have&quot;, &quot;i&#39;ll&quot;: &quot;i will&quot;, &quot;i&#39;ll&#39;ve&quot;: &quot;i will have&quot;, &quot;i&#39;m&quot;: &quot;i am&quot;, &quot;i&#39;ve&quot;: &quot;i have&quot;, &quot;isn&#39;t&quot;: &quot;is not&quot;,<br>                    &quot;it&#39;d&quot;: &quot;it would&quot;, &quot;it&#39;d&#39;ve&quot;: &quot;it would have&quot;, &quot;it&#39;ll&quot;: &quot;it will&quot;, &quot;it&#39;ll&#39;ve&quot;: &quot;it will have&quot;, &quot;it&#39;s&quot;: &quot;it is&quot;,<br>                    &quot;let&#39;s&quot;: &quot;let us&quot;, &quot;ma&#39;am&quot;: &quot;madam&quot;, &quot;mayn&#39;t&quot;: &quot;may not&quot;, &quot;might&#39;ve&quot;: &quot;might have&quot;, &quot;mightn&#39;t&quot;: &quot;might not&quot;,<br>                    &quot;mightn&#39;t&#39;ve&quot;: &quot;might not have&quot;, &quot;must&#39;ve&quot;: &quot;must have&quot;, &quot;mustn&#39;t&quot;: &quot;must not&quot;, &quot;mustn&#39;t&#39;ve&quot;: &quot;must not have&quot;,<br>                    &quot;needn&#39;t&quot;: &quot;need not&quot;, &quot;needn&#39;t&#39;ve&quot;: &quot;need not have&quot;, &quot;o&#39;clock&quot;: &quot;of the clock&quot;, &quot;oughtn&#39;t&quot;: &quot;ought not&quot;,<br>                    &quot;oughtn&#39;t&#39;ve&quot;: &quot;ought not have&quot;, &quot;shan&#39;t&quot;: &quot;shall not&quot;, &quot;sha&#39;n&#39;t&quot;: &quot;shall not&quot;, &quot;shan&#39;t&#39;ve&quot;: &quot;shall not have&quot;,<br>                    &quot;she&#39;d&quot;: &quot;she would&quot;, &quot;she&#39;d&#39;ve&quot;: &quot;she would have&quot;, &quot;she&#39;ll&quot;: &quot;she will&quot;, &quot;she&#39;ll&#39;ve&quot;: &quot;she will have&quot;, &quot;she&#39;s&quot;: &quot;she is&quot;,<br>                    &quot;should&#39;ve&quot;: &quot;should have&quot;, &quot;shouldn&#39;t&quot;: &quot;should not&quot;, &quot;shouldn&#39;t&#39;ve&quot;: &quot;should not have&quot;, &quot;so&#39;ve&quot;: &quot;so have&quot;,<br>                    &quot;so&#39;s&quot;: &quot;so as&quot;, &quot;that&#39;d&quot;: &quot;that would&quot;, &quot;that&#39;d&#39;ve&quot;: &quot;that would have&quot;, &quot;that&#39;s&quot;: &quot;that is&quot;, &quot;there&#39;d&quot;: &quot;there would&quot;,<br>                    &quot;there&#39;d&#39;ve&quot;: &quot;there would have&quot;, &quot;there&#39;s&quot;: &quot;there is&quot;, &quot;they&#39;d&quot;: &quot;they would&quot;, &quot;they&#39;d&#39;ve&quot;: &quot;they would have&quot;,<br>                    &quot;they&#39;ll&quot;: &quot;they will&quot;, &quot;they&#39;ll&#39;ve&quot;: &quot;they will have&quot;, &quot;they&#39;re&quot;: &quot;they are&quot;, &quot;they&#39;ve&quot;: &quot;they have&quot;, &quot;to&#39;ve&quot;: &quot;to have&quot;,<br>                    &quot;wasn&#39;t&quot;: &quot;was not&quot;, &quot;we&#39;d&quot;: &quot;we would&quot;, &quot;we&#39;d&#39;ve&quot;: &quot;we would have&quot;, &quot;we&#39;ll&quot;: &quot;we will&quot;, &quot;we&#39;ll&#39;ve&quot;: &quot;we will have&quot;,<br>                    &quot;we&#39;re&quot;: &quot;we are&quot;, &quot;we&#39;ve&quot;: &quot;we have&quot;, &quot;weren&#39;t&quot;: &quot;were not&quot;, &quot;what&#39;ll&quot;: &quot;what will&quot;, &quot;what&#39;ll&#39;ve&quot;: &quot;what will have&quot;,<br>                    &quot;what&#39;re&quot;: &quot;what are&quot;, &quot;what&#39;s&quot;: &quot;what is&quot;, &quot;what&#39;ve&quot;: &quot;what have&quot;, &quot;when&#39;s&quot;: &quot;when is&quot;, &quot;when&#39;ve&quot;: &quot;when have&quot;,<br>                    &quot;where&#39;d&quot;: &quot;where did&quot;, &quot;where&#39;s&quot;: &quot;where is&quot;, &quot;where&#39;ve&quot;: &quot;where have&quot;, &quot;who&#39;ll&quot;: &quot;who will&quot;, &quot;who&#39;ll&#39;ve&quot;: &quot;who will have&quot;,<br>                    &quot;who&#39;s&quot;: &quot;who is&quot;, &quot;who&#39;ve&quot;: &quot;who have&quot;, &quot;why&#39;s&quot;: &quot;why is&quot;, &quot;why&#39;ve&quot;: &quot;why have&quot;, &quot;will&#39;ve&quot;: &quot;will have&quot;, &quot;won&#39;t&quot;: &quot;will not&quot;,<br>                    &quot;won&#39;t&#39;ve&quot;: &quot;will not have&quot;, &quot;would&#39;ve&quot;: &quot;would have&quot;, &quot;wouldn&#39;t&quot;: &quot;would not&quot;, &quot;wouldn&#39;t&#39;ve&quot;: &quot;would not have&quot;,<br>                    &quot;y&#39;all&quot;: &quot;you all&quot;, &quot;y&#39;all&#39;d&quot;: &quot;you all would&quot;, &quot;y&#39;all&#39;d&#39;ve&quot;: &quot;you all would have&quot;, &quot;y&#39;all&#39;re&quot;: &quot;you all are&quot;,<br>                    &quot;y&#39;all&#39;ve&quot;: &quot;you all have&quot;, &quot;you&#39;d&quot;: &quot;you would&quot;, &quot;you&#39;d&#39;ve&quot;: &quot;you would have&quot;, &quot;you&#39;ll&quot;: &quot;you will&quot;, &quot;you&#39;ll&#39;ve&quot;: &quot;you will have&quot;,<br>                    &quot;you&#39;re&quot;: &quot;you are&quot;, &quot;you&#39;ve&quot;: &quot;you have&quot;}</pre><pre>    q_decontracted = []<br>    for word in q.split():<br>        if word in contractions:<br>            word = contractions[word]<br>        q_decontracted.append(word)<br>    q = &#39; &#39;.join(q_decontracted)</pre><pre>    q = q.replace(&quot;&#39;ve&quot;, &quot; have&quot;)<br>    q = q.replace(&quot;n&#39;t&quot;, &quot; not&quot;)<br>    q = q.replace(&quot;&#39;re&quot;, &quot; are&quot;)<br>    q = q.replace(&quot;&#39;ll&quot;, &quot; will&quot;)<br>    q = BeautifulSoup(q, &quot;html.parser&quot;).get_text()<br>    q = re.sub(r&#39;\W&#39;, &#39; &#39;, q).strip()<br>    return q</pre><h3>Feature Extraction Functions</h3><p>The helper functions extract various features from the questions. These features include:</p><ul><li>Common words</li><li>Total words</li><li>Token features</li><li>Length features</li><li>Fuzzy features</li></ul><p>These features are crucial for our model to understand the similarity between two questions.</p><pre>def test_common_words(q1, q2):<br>    w1 = set(map(lambda word: word.lower().strip(), q1.split(&quot; &quot;)))<br>    w2 = set(map(lambda word: word.lower().strip(), q2.split(&quot; &quot;)))<br>    return len(w1 &amp; w2)</pre><pre>def test_total_words(q1, q2):<br>    w1 = set(map(lambda word: word.lower().strip(), q1.split(&quot; &quot;)))<br>    w2 = set(map(lambda word: word.lower().strip(), q2.split(&quot; &quot;)))<br>    return len(w1) + len(w2)</pre><pre>def test_fetch_token_features(q1, q2):<br>    SAFE_DIV = 0.0001<br>    STOP_WORDS = stopwords.words(&quot;english&quot;)<br>    token_features = [0.0] * 8</pre><pre>    q1_tokens = q1.split()<br>    q2_tokens = q2.split()<br>    if len(q1_tokens) == 0 or len(q2_tokens) == 0:<br>        return token_features</pre><pre>    q1_words = set([word for word in q1_tokens if word not in STOP_WORDS])<br>    q2_words = set([word for word in q2_tokens if word not in STOP_WORDS])<br>    q1_stops = set([word for word in q1_tokens if word in STOP_WORDS])<br>    q2_stops = set([word for word in q2_tokens if word in STOP_WORDS])</pre><pre>    common_word_count = len(q1_words.intersection(q2_words))<br>    common_stop_count = len(q1_stops.intersection(q2_stops))<br>    common_token_count = len(set(q1_tokens).intersection(set(q2_tokens)))</pre><pre>    token_features[0] = common_word_count / (min(len(q1_words), len(q2_words)) + SAFE_DIV)<br>    token_features[1] = common_word_count / (max(len(q1_words), len(q2_words)) + SAFE_DIV)<br>    token_features[2] = common_stop_count / (min(len(q1_stops), len(q2_stops)) + SAFE_DIV)<br>    token_features[3] = common_stop_count / (max(len(q1_stops), len(q2_stops)) + SAFE_DIV)<br>    token_features[4] = common_token_count / (min(len(q1_tokens), len(q2_tokens)) + SAFE_DIV)<br>    token_features[5] = common_token_count / (max(len(q1_tokens), len(q2_tokens)) + SAFE_DIV)<br>    token_features[6] = int(q1_tokens[-1] == q2_tokens[-1])<br>    token_features[7] = int(q1_tokens[0] == q2_tokens[0])</pre><pre>    return token_features</pre><pre>def test_fetch_length_features(q1, q2):<br>    length_features = [0.0] * 3</pre><pre>    # Converting the Sentence into Tokens:<br>    q1_tokens = q1.split()<br>    q2_tokens = q2.split()</pre><pre>    if len(q1_tokens) == 0 or len(q2_tokens) == 0:<br>        return length_features</pre><pre>    # Absolute length features<br>    length_features[0] = abs(len(q1_tokens) - len(q2_tokens))</pre><pre>    # Average Token Length of both Questions<br>    length_features[1] = (len(q1_tokens) + len(q2_tokens)) / 2</pre><pre>    # Find the longest common substring using SequenceMatcher<br>    matcher = difflib.SequenceMatcher(None, q1, q2)<br>    match = matcher.find_longest_match(0, len(q1), 0, len(q2))<br>    longest_common_substring = q1[match.a: match.a + match.size]</pre><pre>    length_features[2] = len(longest_common_substring) / (min(len(q1), len(q2)) + 1)</pre><pre>    return length_features</pre><pre>def test_fetch_fuzzy_features(q1, q2):<br>    fuzzy_features = [0.0] * 4<br>    fuzzy_features[0] = fuzz.QRatio(q1, q2)<br>    fuzzy_features[1] = fuzz.partial_ratio(q1, q2)<br>    fuzzy_features[2] = fuzz.token_sort_ratio(q1, q2)<br>    fuzzy_features[3] = fuzz.token_set_ratio(q1, q2)<br>    return fuzzy_features</pre><h3>Query Point Creator</h3><p>The query_point_creator function preprocesses the questions and extracts all relevant features. These features are then combined into a single query point that is fed into the machine learning model.</p><pre>def query_point_creator(q1, q2):<br>    input_query = []<br>    <br>    q1 = preprocess(q1)<br>    q2 = preprocess(q2)<br>    <br>    input_query.append(len(q1))<br>    input_query.append(len(q2))<br>    <br>    input_query.append(len(q1.split(&quot; &quot;)))<br>    input_query.append(len(q2.split(&quot; &quot;)))<br>    <br>    input_query.append(test_common_words(q1, q2))<br>    input_query.append(test_total_words(q1, q2))<br>    <br>    input_query.append(round(test_common_words(q1, q2) / test_total_words(q1, q2), 2))<br>    token_features = test_fetch_token_features(q1, q2)<br>    <br>    input_query.extend(token_features)<br>    length_features = test_fetch_length_features(q1, q2)<br>    <br>    input_query.extend(length_features)<br>    fuzzy_features = test_fetch_fuzzy_features(q1, q2)<br>    <br>    input_query.extend(fuzzy_features)<br>    <br>    q1_bow = cv.transform([q1]).toarray()<br>    q2_bow = cv.transform([q2]).toarray()<br>    <br>    # Reshape input_query to 2D<br>    input_query = np.array(input_query).reshape(1, -1)<br>    <br>    return np.hstack((input_query, q1_bow, q2_bow))Whole helper.py:</pre><p>Whole helper.py:</p><pre>import re<br>from bs4 import BeautifulSoup<br>import difflib<br>from fuzzywuzzy import fuzz<br>import pickle<br>import numpy as np<br>import nltk<br>from nltk.corpus import stopwords</pre><pre>cv = pickle.load(open(&#39;cv.pkl&#39;, &#39;rb&#39;))</pre><pre>nltk.download(&#39;stopwords&#39;)</pre><pre>def test_common_words(q1, q2):<br>    w1 = set(map(lambda word: word.lower().strip(), q1.split(&quot; &quot;)))<br>    w2 = set(map(lambda word: word.lower().strip(), q2.split(&quot; &quot;)))<br>    return len(w1 &amp; w2)</pre><pre>def test_total_words(q1, q2):<br>    w1 = set(map(lambda word: word.lower().strip(), q1.split(&quot; &quot;)))<br>    w2 = set(map(lambda word: word.lower().strip(), q2.split(&quot; &quot;)))<br>    return len(w1) + len(w2)</pre><pre>def test_fetch_token_features(q1, q2):<br>    SAFE_DIV = 0.0001<br>    STOP_WORDS = stopwords.words(&quot;english&quot;)<br>    token_features = [0.0] * 8</pre><pre>    q1_tokens = q1.split()<br>    q2_tokens = q2.split()<br>    if len(q1_tokens) == 0 or len(q2_tokens) == 0:<br>        return token_features</pre><pre>    q1_words = set([word for word in q1_tokens if word not in STOP_WORDS])<br>    q2_words = set([word for word in q2_tokens if word not in STOP_WORDS])<br>    q1_stops = set([word for word in q1_tokens if word in STOP_WORDS])<br>    q2_stops = set([word for word in q2_tokens if word in STOP_WORDS])</pre><pre>    common_word_count = len(q1_words.intersection(q2_words))<br>    common_stop_count = len(q1_stops.intersection(q2_stops))<br>    common_token_count = len(set(q1_tokens).intersection(set(q2_tokens)))</pre><pre>    token_features[0] = common_word_count / (min(len(q1_words), len(q2_words)) + SAFE_DIV)<br>    token_features[1] = common_word_count / (max(len(q1_words), len(q2_words)) + SAFE_DIV)<br>    token_features[2] = common_stop_count / (min(len(q1_stops), len(q2_stops)) + SAFE_DIV)<br>    token_features[3] = common_stop_count / (max(len(q1_stops), len(q2_stops)) + SAFE_DIV)<br>    token_features[4] = common_token_count / (min(len(q1_tokens), len(q2_tokens)) + SAFE_DIV)<br>    token_features[5] = common_token_count / (max(len(q1_tokens), len(q2_tokens)) + SAFE_DIV)<br>    token_features[6] = int(q1_tokens[-1] == q2_tokens[-1])<br>    token_features[7] = int(q1_tokens[0] == q2_tokens[0])</pre><pre>    return token_features</pre><pre>def test_fetch_length_features(q1, q2):<br>    length_features = [0.0] * 3</pre><pre>    # Converting the Sentence into Tokens:<br>    q1_tokens = q1.split()<br>    q2_tokens = q2.split()</pre><pre>    if len(q1_tokens) == 0 or len(q2_tokens) == 0:<br>        return length_features</pre><pre>    # Absolute length features<br>    length_features[0] = abs(len(q1_tokens) - len(q2_tokens))</pre><pre>    # Average Token Length of both Questions<br>    length_features[1] = (len(q1_tokens) + len(q2_tokens)) / 2</pre><pre>    # Find the longest common substring using SequenceMatcher<br>    matcher = difflib.SequenceMatcher(None, q1, q2)<br>    match = matcher.find_longest_match(0, len(q1), 0, len(q2))<br>    longest_common_substring = q1[match.a: match.a + match.size]</pre><pre>    length_features[2] = len(longest_common_substring) / (min(len(q1), len(q2)) + 1)</pre><pre>    return length_features</pre><pre>def test_fetch_fuzzy_features(q1, q2):<br>    fuzzy_features = [0.0] * 4<br>    fuzzy_features[0] = fuzz.QRatio(q1, q2)<br>    fuzzy_features[1] = fuzz.partial_ratio(q1, q2)<br>    fuzzy_features[2] = fuzz.token_sort_ratio(q1, q2)<br>    fuzzy_features[3] = fuzz.token_set_ratio(q1, q2)<br>    return fuzzy_features</pre><pre>def preprocess(q):<br>    q = str(q).lower().strip()<br>    q = q.replace(&#39;%&#39;, &#39; percent&#39;)<br>    q = q.replace(&#39;$&#39;, &#39; dollar &#39;)<br>    q = q.replace(&#39;₹&#39;, &#39; rupee &#39;)<br>    q = q.replace(&#39;€&#39;, &#39; euro &#39;)<br>    q = q.replace(&#39;@&#39;, &#39; at &#39;)<br>    q = q.replace(&#39;[math]&#39;, &#39;&#39;)<br>    q = q.replace(&#39;,000,000,000 &#39;, &#39;b &#39;)<br>    q = q.replace(&#39;,000,000 &#39;, &#39;m &#39;)<br>    q = q.replace(&#39;,000 &#39;, &#39;k &#39;)<br>    q = re.sub(r&#39;([0-9]+)000000000&#39;, r&#39;\1b&#39;, q)<br>    q = re.sub(r&#39;([0-9]+)000000&#39;, r&#39;\1m&#39;, q)<br>    q = re.sub(r&#39;([0-9]+)000&#39;, r&#39;\1k&#39;, q)<br>    contractions = {&quot;ain&#39;t&quot;: &quot;am not&quot;, &quot;aren&#39;t&quot;: &quot;are not&quot;, &quot;can&#39;t&quot;: &quot;can not&quot;, &quot;can&#39;t&#39;ve&quot;: &quot;can not have&quot;, &quot;&#39;cause&quot;: &quot;because&quot;,<br>                    &quot;could&#39;ve&quot;: &quot;could have&quot;, &quot;couldn&#39;t&quot;: &quot;could not&quot;, &quot;couldn&#39;t&#39;ve&quot;: &quot;could not have&quot;, &quot;didn&#39;t&quot;: &quot;did not&quot;,<br>                    &quot;doesn&#39;t&quot;: &quot;does not&quot;, &quot;don&#39;t&quot;: &quot;do not&quot;, &quot;hadn&#39;t&quot;: &quot;had not&quot;, &quot;hadn&#39;t&#39;ve&quot;: &quot;had not have&quot;, &quot;hasn&#39;t&quot;: &quot;has not&quot;,<br>                    &quot;haven&#39;t&quot;: &quot;have not&quot;, &quot;he&#39;d&quot;: &quot;he would&quot;, &quot;he&#39;d&#39;ve&quot;: &quot;he would have&quot;, &quot;he&#39;ll&quot;: &quot;he will&quot;, &quot;he&#39;ll&#39;ve&quot;: &quot;he will have&quot;,<br>                    &quot;he&#39;s&quot;: &quot;he is&quot;, &quot;how&#39;d&quot;: &quot;how did&quot;, &quot;how&#39;d&#39;y&quot;: &quot;how do you&quot;, &quot;how&#39;ll&quot;: &quot;how will&quot;, &quot;how&#39;s&quot;: &quot;how is&quot;, &quot;i&#39;d&quot;: &quot;i would&quot;,<br>                    &quot;i&#39;d&#39;ve&quot;: &quot;i would have&quot;, &quot;i&#39;ll&quot;: &quot;i will&quot;, &quot;i&#39;ll&#39;ve&quot;: &quot;i will have&quot;, &quot;i&#39;m&quot;: &quot;i am&quot;, &quot;i&#39;ve&quot;: &quot;i have&quot;, &quot;isn&#39;t&quot;: &quot;is not&quot;,<br>                    &quot;it&#39;d&quot;: &quot;it would&quot;, &quot;it&#39;d&#39;ve&quot;: &quot;it would have&quot;, &quot;it&#39;ll&quot;: &quot;it will&quot;, &quot;it&#39;ll&#39;ve&quot;: &quot;it will have&quot;, &quot;it&#39;s&quot;: &quot;it is&quot;,<br>                    &quot;let&#39;s&quot;: &quot;let us&quot;, &quot;ma&#39;am&quot;: &quot;madam&quot;, &quot;mayn&#39;t&quot;: &quot;may not&quot;, &quot;might&#39;ve&quot;: &quot;might have&quot;, &quot;mightn&#39;t&quot;: &quot;might not&quot;,<br>                    &quot;mightn&#39;t&#39;ve&quot;: &quot;might not have&quot;, &quot;must&#39;ve&quot;: &quot;must have&quot;, &quot;mustn&#39;t&quot;: &quot;must not&quot;, &quot;mustn&#39;t&#39;ve&quot;: &quot;must not have&quot;,<br>                    &quot;needn&#39;t&quot;: &quot;need not&quot;, &quot;needn&#39;t&#39;ve&quot;: &quot;need not have&quot;, &quot;o&#39;clock&quot;: &quot;of the clock&quot;, &quot;oughtn&#39;t&quot;: &quot;ought not&quot;,<br>                    &quot;oughtn&#39;t&#39;ve&quot;: &quot;ought not have&quot;, &quot;shan&#39;t&quot;: &quot;shall not&quot;, &quot;sha&#39;n&#39;t&quot;: &quot;shall not&quot;, &quot;shan&#39;t&#39;ve&quot;: &quot;shall not have&quot;,<br>                    &quot;she&#39;d&quot;: &quot;she would&quot;, &quot;she&#39;d&#39;ve&quot;: &quot;she would have&quot;, &quot;she&#39;ll&quot;: &quot;she will&quot;, &quot;she&#39;ll&#39;ve&quot;: &quot;she will have&quot;, &quot;she&#39;s&quot;: &quot;she is&quot;,<br>                    &quot;should&#39;ve&quot;: &quot;should have&quot;, &quot;shouldn&#39;t&quot;: &quot;should not&quot;, &quot;shouldn&#39;t&#39;ve&quot;: &quot;should not have&quot;, &quot;so&#39;ve&quot;: &quot;so have&quot;,<br>                    &quot;so&#39;s&quot;: &quot;so as&quot;, &quot;that&#39;d&quot;: &quot;that would&quot;, &quot;that&#39;d&#39;ve&quot;: &quot;that would have&quot;, &quot;that&#39;s&quot;: &quot;that is&quot;, &quot;there&#39;d&quot;: &quot;there would&quot;,<br>                    &quot;there&#39;d&#39;ve&quot;: &quot;there would have&quot;, &quot;there&#39;s&quot;: &quot;there is&quot;, &quot;they&#39;d&quot;: &quot;they would&quot;, &quot;they&#39;d&#39;ve&quot;: &quot;they would have&quot;,<br>                    &quot;they&#39;ll&quot;: &quot;they will&quot;, &quot;they&#39;ll&#39;ve&quot;: &quot;they will have&quot;, &quot;they&#39;re&quot;: &quot;they are&quot;, &quot;they&#39;ve&quot;: &quot;they have&quot;, &quot;to&#39;ve&quot;: &quot;to have&quot;,<br>                    &quot;wasn&#39;t&quot;: &quot;was not&quot;, &quot;we&#39;d&quot;: &quot;we would&quot;, &quot;we&#39;d&#39;ve&quot;: &quot;we would have&quot;, &quot;we&#39;ll&quot;: &quot;we will&quot;, &quot;we&#39;ll&#39;ve&quot;: &quot;we will have&quot;,<br>                    &quot;we&#39;re&quot;: &quot;we are&quot;, &quot;we&#39;ve&quot;: &quot;we have&quot;, &quot;weren&#39;t&quot;: &quot;were not&quot;, &quot;what&#39;ll&quot;: &quot;what will&quot;, &quot;what&#39;ll&#39;ve&quot;: &quot;what will have&quot;,<br>                    &quot;what&#39;re&quot;: &quot;what are&quot;, &quot;what&#39;s&quot;: &quot;what is&quot;, &quot;what&#39;ve&quot;: &quot;what have&quot;, &quot;when&#39;s&quot;: &quot;when is&quot;, &quot;when&#39;ve&quot;: &quot;when have&quot;,<br>                    &quot;where&#39;d&quot;: &quot;where did&quot;, &quot;where&#39;s&quot;: &quot;where is&quot;, &quot;where&#39;ve&quot;: &quot;where have&quot;, &quot;who&#39;ll&quot;: &quot;who will&quot;, &quot;who&#39;ll&#39;ve&quot;: &quot;who will have&quot;,<br>                    &quot;who&#39;s&quot;: &quot;who is&quot;, &quot;who&#39;ve&quot;: &quot;who have&quot;, &quot;why&#39;s&quot;: &quot;why is&quot;, &quot;why&#39;ve&quot;: &quot;why have&quot;, &quot;will&#39;ve&quot;: &quot;will have&quot;, &quot;won&#39;t&quot;: &quot;will not&quot;,<br>                    &quot;won&#39;t&#39;ve&quot;: &quot;will not have&quot;, &quot;would&#39;ve&quot;: &quot;would have&quot;, &quot;wouldn&#39;t&quot;: &quot;would not&quot;, &quot;wouldn&#39;t&#39;ve&quot;: &quot;would not have&quot;,<br>                    &quot;y&#39;all&quot;: &quot;you all&quot;, &quot;y&#39;all&#39;d&quot;: &quot;you all would&quot;, &quot;y&#39;all&#39;d&#39;ve&quot;: &quot;you all would have&quot;, &quot;y&#39;all&#39;re&quot;: &quot;you all are&quot;,<br>                    &quot;y&#39;all&#39;ve&quot;: &quot;you all have&quot;, &quot;you&#39;d&quot;: &quot;you would&quot;, &quot;you&#39;d&#39;ve&quot;: &quot;you would have&quot;, &quot;you&#39;ll&quot;: &quot;you will&quot;, &quot;you&#39;ll&#39;ve&quot;: &quot;you will have&quot;,<br>                    &quot;you&#39;re&quot;: &quot;you are&quot;, &quot;you&#39;ve&quot;: &quot;you have&quot;}</pre><pre>    q_decontracted = []<br>    for word in q.split():<br>        if word in contractions:<br>            word = contractions[word]<br>        q_decontracted.append(word)<br>    q = &#39; &#39;.join(q_decontracted)</pre><pre>    q = q.replace(&quot;&#39;ve&quot;, &quot; have&quot;)<br>    q = q.replace(&quot;n&#39;t&quot;, &quot; not&quot;)<br>    q = q.replace(&quot;&#39;re&quot;, &quot; are&quot;)<br>    q = q.replace(&quot;&#39;ll&quot;, &quot; will&quot;)<br>    q = BeautifulSoup(q, &quot;html.parser&quot;).get_text()<br>    q = re.sub(r&#39;\W&#39;, &#39; &#39;, q).strip()<br>    return q</pre><pre>def query_point_creator(q1, q2):<br>    input_query = []<br>    <br>    q1 = preprocess(q1)<br>    q2 = preprocess(q2)<br>    <br>    input_query.append(len(q1))<br>    input_query.append(len(q2))<br>    <br>    input_query.append(len(q1.split(&quot; &quot;)))<br>    input_query.append(len(q2.split(&quot; &quot;)))<br>    <br>    input_query.append(test_common_words(q1, q2))<br>    input_query.append(test_total_words(q1, q2))<br>    <br>    input_query.append(round(test_common_words(q1, q2) / test_total_words(q1, q2), 2))<br>    token_features = test_fetch_token_features(q1, q2)<br>    <br>    input_query.extend(token_features)<br>    length_features = test_fetch_length_features(q1, q2)<br>    <br>    input_query.extend(length_features)<br>    fuzzy_features = test_fetch_fuzzy_features(q1, q2)<br>    <br>    input_query.extend(fuzzy_features)<br>    <br>    q1_bow = cv.transform([q1]).toarray()<br>    q2_bow = cv.transform([q2]).toarray()<br>    <br>    # Reshape input_query to 2D<br>    input_query = np.array(input_query).reshape(1, -1)<br>    <br>    return np.hstack((input_query, q1_bow, q2_bow))</pre><h3>Running the Application</h3><p>To run the application, execute the app.py file using Streamlit:</p><pre>streamlit run app.py</pre><p>This will launch a web interface where you can input two questions and get an immediate prediction on whether they are duplicates.</p><p>Like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*d1txwASKe-HZvxVM.png" /></figure><p>Let’s ckeck to enter questions,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*_Wm7hkhnaIWvrtIV.png" /></figure><p>For Not Duplicate,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*EbWaAkpJ4XVnLk8-.png" /></figure><p>So this is my project.</p><h3>Conclusion</h3><p>In this project, we’ve demonstrated how to build a duplicate question detection system using machine learning. By leveraging text preprocessing, feature extraction, and a pre-trained model, we can effectively determine the similarity between questions. This system can be further improved with advanced NLP techniques and a larger dataset for training.</p><p>Feel free to experiment with the code and enhance the model’s accuracy by incorporating additional features and fine-tuning the preprocessing steps.</p><p>Stay safe, Have a nice day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbbadf295a68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Olympics Data Analysis]]></title>
            <link>https://medium.com/@kaushikpandav16/olympics-data-analysis-with-machine-learning-e89e4577fb85?source=rss-101d0e750e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e89e4577fb85</guid>
            <category><![CDATA[olympics]]></category>
            <category><![CDATA[ml-project]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaushikpandav]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 17:58:37 GMT</pubDate>
            <atom:updated>2024-10-09T05:56:20.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The Olympic Games have a long history and are one of the most celebrated sports events worldwide. With over a century’s worth of data, there’s a lot of information to explore. This project uses machine learning to analyze Olympic history, uncovering patterns and trends to deepen our understanding of the Games and possibly predict future results.</p><h3>Objectives</h3><p>The main objectives of this project are:</p><ol><li><strong>Data Preprocessing</strong>: Cleaning and preparing the dataset for analysis.</li><li><strong>Exploratory Data Analysis (EDA)</strong>: Visualizing and summarizing the data to understand underlying patterns.</li><li><strong>Medal Tally Analysis</strong>: Analyzing medal counts by year and country.</li><li><strong>Country-wise Analysis</strong>: Investigating the performance of specific countries over time.</li><li><strong>Athlete-wise Analysis</strong>: Exploring data on individual athletes, including age distributions and performance trends.</li></ol><p>Used Dataset : <a href="https://www.kaggle.com/datasets/heesoo37/120-years-of-olympic-history-athletes-and-results">https://www.kaggle.com/datasets/heesoo37/120-years-of-olympic-history-athletes-and-results</a></p><h3>Methodology</h3><p>The project involves several steps:</p><p><strong>Data Preprocessing</strong>:</p><ul><li>Load the datasets.</li><li>Filter for Summer Olympics data.</li><li>Merge the datasets to include region information.</li><li>Create dummy variables for medals (Gold, Silver, Bronze).</li></ul><p><strong>Exploratory Data Analysis (EDA)</strong>:</p><ul><li>Generate key statistics such as the number of editions, host cities, sports, events, athletes, and nations.</li><li>Visualize trends over time, such as the number of participating nations, events, and athletes.</li></ul><p><strong>Medal Tally Analysis</strong>:</p><ul><li>Allow users to select a specific year and country to view their medal tally.</li><li>Display the overall performance, as well as year-wise and country-wise performances.</li></ul><p><strong>Country-wise Analysis</strong>:</p><ul><li>Analyze the medal tally of a selected country over the years.</li><li>Identify sports in which the country excels.</li><li>List the top 10 athletes from the selected country.</li></ul><p><strong>Athlete-wise Analysis</strong>:</p><ul><li>Visualize the age distribution of athletes and medalists.</li><li>Analyze the distribution of age with respect to different sports.</li><li>Explore height and weight data of athletes.</li><li>Compare male and female participation over the years.</li></ul><p>Let’s see how look like this project :</p><p><strong>Medal Tally:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*ApgQKX8Hhltls-1K.png" /></figure><p>Year wise,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*AXZwJFVZHgtI5Abo.png" /></figure><p>Country wise,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*ZFZrd64kDqUC6s-f.png" /></figure><p><strong>Overall Analysis:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*axePSFJQJY24mvuz.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*slC-o0vv3ZE6Z9Cc.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*nor8y6rsUoG9ezM7.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*g0bNeoO0fygB1_BD.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*KNPN2t2zU9BYvJo2.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*fDkx-ODnEyYZp5pK.png" /></figure><p><strong>Country-wise Analysis:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*inEosByWhUBzbW2z.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*SlMFB7DlhK8fLKlD.png" /></figure><p>And then let’s see code for this project,</p><p>app.py</p><pre>import streamlit as st<br>import pandas as pd<br>import preprocessor,helper<br>import plotly.express as px<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import plotly.figure_factory as ff</pre><pre>df = pd.read_csv(&#39;athlete_events.csv&#39;)<br>region_df = pd.read_csv(&#39;noc_regions.csv&#39;)</pre><pre>df = preprocessor.preprocess(df,region_df)</pre><pre>st.sidebar.title(&quot;Olympics Analysis&quot;)<br>st.sidebar.image(&#39;olympic.jpg&#39;)<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><pre>if user_menu == &#39;Medal Tally&#39;:<br>    st.sidebar.header(&quot;Medal Tally&quot;)<br>    years,country = helper.country_year_list(df)</pre><pre>    selected_year = st.sidebar.selectbox(&quot;Select Year&quot;,years)<br>    selected_country = st.sidebar.selectbox(&quot;Select Country&quot;, country)</pre><pre>    medal_tally = helper.fetch_medal_tally(df,selected_year,selected_country)<br>    if selected_year == &#39;Overall&#39; and selected_country == &#39;Overall&#39;:<br>        st.title(&quot;Overall Tally&quot;)<br>    if selected_year != &#39;Overall&#39; and selected_country == &#39;Overall&#39;:<br>        st.title(&quot;Medal Tally in &quot; + str(selected_year) + &quot; Olympics&quot;)<br>    if selected_year == &#39;Overall&#39; and selected_country != &#39;Overall&#39;:<br>        st.title(selected_country + &quot; overall performance&quot;)<br>    if selected_year != &#39;Overall&#39; and selected_country != &#39;Overall&#39;:<br>        st.title(selected_country + &quot; performance in &quot; + str(selected_year) + &quot; Olympics&quot;)<br>    st.table(medal_tally)</pre><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]</pre><pre>    st.title(&quot;Top Statistics&quot;)<br>    col1,col2,col3 = st.columns(3)<br>    with col1:<br>        st.header(&quot;Editions&quot;)<br>        st.title(editions)<br>    with col2:<br>        st.header(&quot;Hosts&quot;)<br>        st.title(cities)<br>    with col3:<br>        st.header(&quot;Sports&quot;)<br>        st.title(sports)</pre><pre>    col1, col2, col3 = st.columns(3)<br>    with col1:<br>        st.header(&quot;Events&quot;)<br>        st.title(events)<br>    with col2:<br>        st.header(&quot;Nations&quot;)<br>        st.title(nations)<br>    with col3:<br>        st.header(&quot;Athletes&quot;)<br>        st.title(athletes)</pre><pre>    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 years&quot;)<br>    st.plotly_chart(fig)</pre><pre>    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 years&quot;)<br>    st.plotly_chart(fig)</pre><pre>    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 years&quot;)<br>    st.plotly_chart(fig)</pre><pre>    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;),<br>                annot=True)<br>    st.pyplot(fig)</pre><pre>    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;)</pre><pre>    selected_sport = st.selectbox(&#39;Select a Sport&#39;,sport_list)<br>    x = helper.most_successful(df,selected_sport)<br>    st.table(x)</pre><pre>if user_menu == &#39;Country-wise Analysis&#39;:</pre><pre>    st.sidebar.title(&#39;Country-wise Analysis&#39;)</pre><pre>    country_list = df[&#39;region&#39;].dropna().unique().tolist()<br>    country_list.sort()</pre><pre>    selected_country = st.sidebar.selectbox(&#39;Select a Country&#39;,country_list)</pre><pre>    country_df = helper.yearwise_medal_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 years&quot;)<br>    st.plotly_chart(fig)</pre><pre>    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=(15, 15))<br>    ax = sns.heatmap(pt,annot=True)<br>    st.pyplot(fig)</pre><pre>    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)</pre><pre>if user_menu == &#39;Athlete wise Analysis&#39;:<br>    <br>    athlete_df = df.drop_duplicates(subset=[&#39;Name&#39;, &#39;region&#39;])</pre><pre>    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()</pre><pre>    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>    <br>    fig.update_layout(autosize=False,width=1000,height=600)<br>    <br>    st.title(&quot;Distribution of Age&quot;)<br>    st.plotly_chart(fig)</pre><pre>    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)</pre><pre>    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)</pre><pre>    sport_list = df[&#39;Sport&#39;].unique().tolist()<br>    sport_list.sort()<br>    sport_list.insert(0, &#39;Overall&#39;)</pre><pre>    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(x=temp_df[&#39;Weight&#39;],y=temp_df[&#39;Height&#39;],hue=temp_df[&#39;Medal&#39;],style=temp_df[&#39;Sex&#39;],s=60)<br>    st.pyplot(fig)</pre><pre>    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)</pre><p>helper.py</p><pre>import numpy as np<br></pre><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)]</pre><pre>    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;,<br>                                                                                      ascending=False).reset_index()</pre><pre>    x[&#39;total&#39;] = x[&#39;Gold&#39;] + x[&#39;Silver&#39;] + x[&#39;Bronze&#39;]</pre><pre>    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;)</pre><pre>    return x<br></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;)</pre><pre>    country = np.unique(df[&#39;region&#39;].dropna().values).tolist()<br>    country.sort()<br>    country.insert(0, &#39;Overall&#39;)</pre><pre>    return years,country</pre><pre>def data_over_time(df,col):</pre><pre>    nations_over_time = df.drop_duplicates([&#39;Year&#39;, col])[&#39;Year&#39;].value_counts().reset_index().sort_values(&#39;Year&#39;)    <br>    nations_over_time.rename(columns = {&#39;Year&#39;:&#39;Edition&#39;, &#39;count&#39;: col}, inplace = True)   <br>     <br>    return nations_over_time</pre><pre>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]</pre><pre>    top_athletes = temp_df[&#39;Name&#39;].value_counts().reset_index().head(15)<br>    top_athletes.columns = [&#39;Name&#39;, &#39;Medals&#39;]</pre><pre>    result = top_athletes.merge(df, on=&#39;Name&#39;, how=&#39;left&#39;)<br>    x = result[[&#39;Name&#39;, &#39;Medals&#39;, &#39;Sport&#39;, &#39;region&#39;]].drop_duplicates(&#39;Name&#39;)<br>    return x</pre><pre>def yearwise_medal_tally(df,country):<br>    <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)</pre><pre>    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()</pre><pre>    return final_df</pre><pre>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)</pre><pre>    new_df = temp_df[temp_df[&#39;region&#39;] == country]</pre><pre>    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></pre><pre>def most_successful_countrywise(df, country):<br>    <br>    temp_df = df.dropna(subset=[&#39;Medal&#39;])<br>    <br>    temp_df = temp_df[temp_df[&#39;region&#39;] == country]</pre><pre>    top_athletes = temp_df[&#39;Name&#39;].value_counts().reset_index().head(15)<br>    top_athletes.columns = [&#39;Name&#39;, &#39;Medals&#39;]</pre><pre>    result = top_athletes.merge(df, on=&#39;Name&#39;, how=&#39;left&#39;)<br>    x = result[[&#39;Name&#39;, &#39;Medals&#39;, &#39;Sport&#39;]].drop_duplicates(&#39;Name&#39;)<br>    return x</pre><pre>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</pre><pre>def men_vs_women(df):<br>    athlete_df = df.drop_duplicates(subset=[&#39;Name&#39;, &#39;region&#39;])</pre><pre>    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()</pre><pre>    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)</pre><pre>    final.fillna(0, inplace=True)</pre><pre>    return final</pre><p>preprocessor.py</p><pre>import pandas as pd</pre><pre>def preprocess(df, region_df):<br>    <br>    # global df, region_df<br>    <br>    df = df[df[&#39;Season&#39;] == &#39;Summer&#39;]<br>    <br>    df = df.merge(region_df, on = &#39;NOC&#39;, how= &#39;left&#39;)<br>    <br>    df.drop_duplicates(inplace=True)<br>    <br>    df = pd.concat([df, pd.get_dummies(df[&#39;Medal&#39;])], axis = 1)<br>    <br>    return df</pre><h3>Conclusion</h3><p>we’ve analyzed Olympic data using data science techniques. We found a significant rise in participating nations, events, and athletes, indicating global Olympic growth.</p><p>Medal tallies revealed dominant countries and performance trends. The country-specific analysis highlighted sports strengths and cultural significance.</p><p>Athlete data showed peak performance ages and increasing female participation. This project emphasizes data science’s role in sports analytics, offering insights into Olympic history, trends, and athlete performance.</p><p>let’s see with another interesting project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e89e4577fb85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>