<?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 Keith Chadberc Niven Villanueva on Medium]]></title>
        <description><![CDATA[Stories by Keith Chadberc Niven Villanueva on Medium]]></description>
        <link>https://medium.com/@kisetzuu?source=rss-3a169225c550------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IdZN81ruR7YWK3KmZ0k8cg.png</url>
            <title>Stories by Keith Chadberc Niven Villanueva on Medium</title>
            <link>https://medium.com/@kisetzuu?source=rss-3a169225c550------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:57:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kisetzuu/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[How I Started from Zero and Became a Machine Learning Engineer and Software Engineer at 20: The…]]></title>
            <link>https://medium.com/@kisetzuu/how-i-started-from-zero-and-became-a-machine-learning-engineer-and-software-engineer-at-20-the-66f4a735e0b3?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f4a735e0b3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 16:01:16 GMT</pubDate>
            <atom:updated>2025-02-01T16:01:16.953Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Started from Zero and Became a Machine Learning Engineer and Software Engineer at 20: The Core of AI</h3><blockquote>“Your niche lies where your deepest interests meet the world’s needs. Align with who you are, and create what only you can.”<br><em>– Inspired by Mastery by Robert Greene</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ALQ1amzTbS7riCmn" /><figcaption>Image Generated by DALL-E</figcaption></figure><h3>Introduction</h3><p>From the very beginning, I was captivated by AI’s potential to transform the future. I envisioned a world where AI wasn’t just a tool, but the driving force behind innovation and technological advancement — a force capable of unlocking unprecedented progress across countless domains.</p><p>As a Computer Engineering student, I dove into AI during my second year, even though it wasn’t part of the formal curriculum. Fueled by curiosity and determination, I embarked on a self-directed journey to master its core concepts and practical applications.</p><p>Balancing a rigorous engineering curriculum with this newfound passion was challenging. I juggled coursework with self-study sessions — often seizing every opportunity to learn, even sneaking into DataCamp lessons during class when traditional topics failed to spark my interest. These unconventional moments kept my passion alive and propelled my progress.</p><p>This marked the beginning of my journey toward becoming both a Machine Learning Engineer and a Software Engineer, laying the foundation for a career centered around the core of AI.</p><h3>Mindset and Work Ethic</h3><p>Pursuing both my degree and self-directed learning in machine learning demanded a disciplined mindset. I knew that managing my time effectively was critical to my success. Here’s how I approached it:</p><ul><li><strong>Time Management:</strong><br>I meticulously planned each day, allocating specific time slots for academics, DataCamp lessons, Kaggle projects, and eventually, my responsibilities at Farmtri. This structure allowed me to make consistent progress even on busy days.</li><li><strong>Networking and Collaboration:</strong><br>I actively connected with peers at AI Pilipinas Cebu, engaged with the Kaggle community, and collaborated with colleagues at Farmtri. These interactions provided valuable insights, motivation, and fresh perspectives, reinforcing that learning is never a solo endeavor.</li><li><strong>Balancing Work and Self-Care:</strong><br>Recognizing the importance of downtime, I made sure to balance intense study sessions with moments of relaxation — whether it was taking short breaks or playing video games to recharge. This balance helped prevent burnout and kept my focus sharp over the long haul.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*V_ijTm_GpirF7ygwTNrZeQ.png" /><figcaption>“Mindset and Work Ethic for Mastery — A Visual Representation of Key Principles from Robert Greene’s <em>Mastery</em>”</figcaption></figure><h3>Challenges Along the Way</h3><p>Despite a structured approach and strong work ethic, my journey was far from smooth. I encountered several challenges that tested my resolve:</p><h4>Balancing Multiple Priorities</h4><p>There were days when juggling assignments, projects, and self-directed learning left me questioning if I could keep up. The pressure of maintaining academic performance while exploring new machine learning topics was intense and sometimes overwhelming.</p><h4>Technical Setbacks</h4><p>Complex algorithms and the intricacies of debugging code often resulted in roadblocks. These technical challenges led to moments of frustration, but each setback provided a valuable lesson in perseverance and problem-solving.</p><h4>Distractions and Self-Doubt</h4><p>The allure of distractions — like video games — occasionally disrupted my focus. Additionally, the rapidly evolving field of AI sometimes made me doubt my abilities, as it felt like I was constantly trying to catch up.</p><p>Each of these struggles, although challenging, ultimately became stepping stones that refined my time management, resilience, and ability to seek help from mentors and peers.</p><h3>Grinding the Fundamentals</h3><p>In addition to overcoming daily challenges, I dove headfirst into the core principles that form the backbone of both Machine Learning Engineering and Software Engineering. This wasn’t merely about absorbing theory — it was about putting in countless hours of practice, building models from scratch, and writing robust, scalable code.</p><h4>Deep Learning &amp; Data Processing</h4><ul><li><strong>Focus:</strong> Mastering intricate algorithms, developing data pipelines, and understanding the subtleties of neural networks.</li><li><strong>Approach:</strong> Repeated practice and hands-on experimentation were key to understanding how to manipulate and process data effectively.</li></ul><h4>Software Development Practices</h4><ul><li><strong>Focus:</strong> Honing my proficiency in programming languages, system design, and adopting best practices in software engineering.</li><li><strong>Techniques:</strong> I embraced version control, modular code design, and test-driven development to build machine learning systems that are reliable, maintainable, and scalable.</li></ul><h4>Core Machine Learning Algorithms</h4><p>I immersed myself in the essential algorithms that form the heart of machine learning:</p><ul><li><strong>Supervised Learning:</strong><br>Techniques like linear regression, decision trees, random forests, support vector machines (SVMs), and gradient boosting enabled me to work effectively with labeled data.</li><li><strong>Unsupervised Learning:</strong><br>I explored clustering methods (e.g., k-means, hierarchical clustering), dimensionality reduction (e.g., PCA, t-SNE), and anomaly detection to extract insights from unstructured data.</li><li><strong>Reinforcement Learning:</strong><br>By experimenting with Q-learning and policy gradient methods, I developed agents capable of learning optimal policies through trial and error.</li><li><strong>Deep Learning Architectures:</strong><br>I worked with specialized architectures, including Convolutional Neural Networks (CNNs) for image recognition, Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) networks for sequence data, and transformer-based models that have redefined possibilities in natural language processing.</li></ul><p>The steep learning curve and heavy workload demanded discipline, persistence, and the ability to switch rapidly between different technical paradigms. Yet, this rigorous phase cemented my understanding of both the theoretical and practical aspects of my field.</p><h3>Landing the Job</h3><p>Securing a role at Farmtri marked a significant turning point in my journey. I started as an intern at a startup with limited resources and a small team, meaning every member had to shoulder greater responsibilities. Initially, I was anxious — worrying about balancing the demanding workload with my academic commitments.</p><p>While interning, I was also a second-year college student taking required summer classes in MSAD, which introduced me to the fundamentals of software development. This dual exposure to academic learning and real-world challenges made it clear that I needed to elevate my game to succeed on both fronts.</p><p>After careful consideration by the company, I was entrusted with a dual role as a Machine Learning Engineer and Software Engineer. I was thrilled by the opportunity, but it also meant playing at a much higher level. I already had months of experience with machine learning concepts, so I was confident in that area; however, I quickly realized that my software engineering skills were still in their infancy.</p><p>Fortunately, my best friend — who was also my colleague at Farmtri — became an invaluable partner. We worked as a duo on the company’s software development projects. He took me under his wing, teaching me the ground-level essentials: from core principles and standards for clean, maintainable code to best practices in software development. This hands-on mentorship accelerated my learning and allowed us to overcome challenges together.</p><p>In this dynamic startup environment, where each day presented new obstacles, I learned to break down my responsibilities into manageable tasks and focus on incremental improvements. Over time, as I absorbed guidance from both formal education and on-the-ground mentorship, my initial anxiety gave way to confidence. I embraced a growth mindset — viewing every challenge as an opportunity to refine my expertise — and pushed myself to excel in the core domains of AI.</p><h3>Next Steps</h3><p>Landing the job was only the beginning. While I’m still in the early stages of my career and acknowledge that I lack a lot of expertise, I am committed to grinding hard every day to become a better engineer. Here’s how I plan to move forward in my journey:</p><ul><li><strong>Deepening Technical Expertise:</strong><br>I aim to expand my knowledge by diving deeper into advanced machine learning algorithms and cutting-edge software engineering practices. Whether it’s exploring new deep learning architectures or mastering distributed systems, I’m committed to staying at the forefront of AI innovation — even as I recognize there’s still much to learn.</li><li><strong>Challenging Projects and Real-World Impact:</strong><br>Working at a startup has exposed me to a variety of real-world challenges. I plan to take on increasingly complex projects that push the boundaries of my current skill set and contribute to solutions that make a tangible impact. Every project is an opportunity to grow, even when I’m still building my expertise.</li><li><strong>Continuous Learning and Mentorship:</strong><br>The journey of learning never ends. I intend to pursue further education through online courses, workshops, and conferences while also seeking mentorship from experienced professionals. At the same time, I look forward to sharing my experiences with others who are just starting out, creating a cycle of learning and growth.</li><li><strong>Expanding My Role and Responsibilities:</strong><br>With every challenge comes the opportunity to take on more responsibility. I hope to gradually lead larger projects, guide cross-functional teams, and influence strategic decisions, even as I continue to develop my own technical skills and knowledge.</li><li><strong>Building a Strong Network:</strong><br>Collaboration and community are essential in the rapidly evolving world of AI. I will continue to network with fellow professionals, participate in industry forums, and contribute to open-source projects, ensuring that I remain connected with emerging trends and continuously learn from the broader community.</li><li><strong>Adapting to New Challenges:</strong><br>The AI landscape is ever-changing, and I’m committed to adapting to new technologies and methodologies. Embracing a growth mindset means accepting that I have much to learn, but also that every setback is an opportunity to refine my expertise and evolve as an engineer.</li></ul><p>I may still be at the beginning of my career, but each challenge and every project is a stepping stone toward becoming a stronger, more capable engineer. I’m excited for the road ahead and ready to work hard to achieve excellence in the core domains of AI.</p><h3>Looking Back: What I Would Do Differently</h3><p>Reflecting on my journey, there are a few things I would have done differently before landing the job — lessons I now believe could have accelerated my growth:</p><ul><li><strong>Prioritize Software Engineering Early On:</strong><br>Although I was confident in my machine learning abilities, I realized too late that my software engineering skills needed more attention. I would have started building my expertise in software development sooner by engaging in hands-on projects, taking targeted online courses, and actively seeking mentorship in this area.</li><li><strong>Embrace a Structured Learning Path:</strong><br>Much of my early learning came through trial and error. I now see the value in a more disciplined approach — balancing academic studies with real-world application through a structured learning plan would have better prepared me for the startup environment.</li><li><strong>Seek Mentorship More Actively:</strong><br>While I was fortunate to have my best friend and colleague guide me, I would have proactively sought additional mentors and joined more professional communities earlier. Diverse perspectives could have fast-tracked my learning and helped me navigate challenges more effectively.</li><li><strong>Adopt a Mindset That Welcomes Failure:</strong><br>I often hesitated, fearing failure and its consequences. I would have embraced experimentation more openly, recognizing that every mistake is a valuable lesson on the path to mastery.</li></ul><p>Every challenge and setback has contributed to my evolution as both a Machine Learning Engineer and a Software Engineer. While I wouldn’t change my overall journey, focusing on these areas sooner might have eased some early anxieties and accelerated my progress. The lessons learned are now integral to my approach to continuous learning and personal development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f4a735e0b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End MLOps: Deploying a Stock Price Prediction API with FastAPI and Docker]]></title>
            <link>https://medium.com/@kisetzuu/end-to-end-mlops-deploying-a-stock-price-prediction-api-with-fastapi-and-docker-08741cff1884?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/08741cff1884</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 07:31:22 GMT</pubDate>
            <atom:updated>2025-01-25T07:31:22.936Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Artificial intelligence is the new electricity.”<br> — Andrew Ng</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0JOhAew0-KH49F5h" /><figcaption>Generated with DALL-E</figcaption></figure><h3>A. Introduction</h3><p>In the fast-paced world of machine learning, developing a robust model is only the beginning. The real challenge lies in deploying that model so it can deliver value by making real-time predictions. This is where MLOps (Machine Learning Operations) comes into play — a systematic approach to integrating machine learning workflows with software engineering practices, enabling efficient deployment, monitoring, and scaling of machine learning models.</p><p>In this article, we’ll walk through an end-to-end MLOps workflow by building and deploying a <strong>Stock Price Prediction API</strong>. Using <strong>FastAPI</strong> for the backend, <strong>Docker</strong> for containerization, and <strong>Scikit-learn</strong> for model creation, we’ll show how to go from raw data to a fully containerized application ready to serve predictions.</p><p>Whether you’re a data scientist aiming to deploy your first model or a software engineer looking to integrate machine learning into production, this article will guide you step-by-step through the process. By the end, you’ll have a clear understanding of how to package your machine learning models, expose them via APIs, and containerize them for scalable deployments.</p><p>Let’s dive into the exciting journey of deploying machine learning at scale! 🚀</p><h3>B. Prerequisites</h3><p>Before diving into the implementation, ensure you have the following tools and libraries installed and ready to use. This will set up the foundation for our workflow.</p><h4>1. Tools Required</h4><ul><li><strong>Python (3.9 or higher)</strong>: The programming language used for building the machine learning model and API.</li><li><strong>Docker</strong>: A platform for containerizing applications to ensure portability and scalability.</li><li><strong>Postman</strong>: A tool for testing APIs.</li><li><strong>Editor/IDE</strong>: Such as Visual Studio Code or PyCharm.</li></ul><h4>2. Python Libraries</h4><p>Make sure you have the following Python libraries installed:</p><ul><li><strong>FastAPI</strong>: For building the web API.</li><li><strong>Uvicorn</strong>: A lightweight ASGI server for running FastAPI applications.</li><li><strong>Scikit-learn</strong>: For creating and training the stock price prediction model.</li><li><strong>Numpy</strong>: For numerical computations.</li><li><strong>Pickle</strong>: For saving and loading the machine learning model.</li></ul><p>Install all the libraries using the following command:</p><pre>pip install fastapi uvicorn scikit-learn nump</pre><h4>3. Dataset</h4><p>You’ll need a dataset for training the stock price prediction model. In this example, the dataset should contain features and a target column for stock prices. Make sure to have the dataset ready at a local path, such as:</p><pre>&lt;your_path&gt;/indexData.csvPs\indexData.csv</pre><p>Ensure the dataset contains the necessary features and target values for training the model.</p><h4>4. Docker Installation</h4><p>If you don’t have Docker installed, follow the Docker installation guide for your operating system. Once installed, verify it by running:</p><pre>docker --version</pre><h4>5. Postman Setup</h4><p>Download and install Postman to test the API endpoints later in the process.</p><h3>C. Creating the Machine Learning Model</h3><p>This section guides you through the process of creating and training a machine learning model for stock price prediction. We’ll cover three steps:</p><h4>Step 1: Loading the Dataset</h4><ol><li><strong>Read the Dataset</strong></li></ol><ul><li>Load the dataset into a pandas DataFrame for easier manipulation.</li><li>Replace &lt;your_path&gt;/indexData.csv with the path to your dataset.</li></ul><pre>import pandas as pd<br><br># Load the dataset<br>dataset_path = &quot;&lt;your_path&gt;/indexData.csv&quot;<br>data = pd.read_csv(dataset_path)<br><br>print(data.head())  # View the first few rows of the dataset</pre><p>2. <strong>Prepare Features and Target</strong></p><ul><li>Split the dataset into features (X) and target (y).</li><li>For this example, assume the target column is named price.</li></ul><pre># Separate features and target<br>X = data.drop(columns=[&quot;price&quot;])  # Replace &quot;price&quot; with your target column name<br>y = data[&quot;price&quot;]</pre><h4>Step 2: Training the Model</h4><ol><li><strong>Split the Data</strong></li></ol><ul><li>Split the dataset into training and testing sets using Scikit-learn’s train_test_split.</li></ul><pre>from sklearn.model_selection import train_test_split<br><br># Split data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p><strong>2. Train a Machine Learning Model</strong></p><ul><li>Use a simple model like Random Forest for demonstration.</li><li>Train the model on the training data.</li></ul><pre>from sklearn.ensemble import RandomForestRegressor<br><br># Initialize the model<br>model = RandomForestRegressor(n_estimators=100, random_state=42)<br><br># Train the model<br>model.fit(X_train, y_train)<br><br>print(&quot;Model training completed.&quot;)</pre><p>3. <strong>Evaluate the Model</strong></p><ul><li>Check the model’s performance on the testing set.</li></ul><pre>from sklearn.metrics import mean_squared_error<br><br># Make predictions on the testing set<br>y_pred = model.predict(X_test)<br><br># Calculate Mean Squared Error (MSE)<br>mse = mean_squared_error(y_test, y_pred)<br>print(f&quot;Mean Squared Error: {mse}&quot;)</pre><h4>Step 3: Saving the Trained Model</h4><ol><li><strong>Save the Model</strong></li></ol><ul><li>Save the trained model to a file for later use.</li></ul><pre>import pickle<br><br># Define the path to save the model<br>model_path = &quot;stock_model.pkl&quot;<br><br># Save the model using Pickle<br>with open(model_path, &quot;wb&quot;) as f:<br>    pickle.dump(model, f)<br><br>print(f&quot;Model saved to {model_path}&quot;)</pre><p><strong>Verify the Saved Model</strong></p><ul><li>Reload the saved model and test it with new data.</li></ul><pre># Load the saved model<br>with open(model_path, &quot;rb&quot;) as f:<br>    loaded_model = pickle.load(f)<br><br># Test the model with sample features<br>test_features = [[150.5, 149.2, 1000000]]  # Replace with valid test data<br>prediction = loaded_model.predict(test_features)<br>print(f&quot;Test Prediction: {prediction[0]}&quot;)</pre><h3>D. Building the FastAPI Application</h3><p>With the machine learning model trained and saved, the next step is to create an API that can serve predictions. We’ll use <strong>FastAPI</strong>, a modern, fast (high-performance) web framework for building APIs with Python.</p><h4>Step 1: Setting Up FastAPI</h4><ol><li><strong>Install FastAPI and Uvicorn</strong>: If not installed already, run:</li></ol><pre>pip install fastapi uvicorn</pre><p><strong>Create the </strong><strong>app.py File</strong>:</p><ul><li>This file will contain the FastAPI application code.</li><li>Save the file in the same directory as the stock_model.pkl file.</li></ul><h4>Step 2: Writing the FastAPI Code</h4><p>Here’s the complete code for your FastAPI application:</p><pre>from fastapi import FastAPI, Request<br>import pickle<br>import numpy as np<br>import os<br><br># Load the saved model using a relative path<br>model_path = os.path.join(os.path.dirname(__file__), &quot;stock_model.pkl&quot;)<br>with open(model_path, &quot;rb&quot;) as f:<br>    model = pickle.load(f)<br><br># Initialize FastAPI app<br>app = FastAPI()<br><br>@app.post(&quot;/predict/&quot;)<br>async def predict(request: Request):<br>    &quot;&quot;&quot;<br>    Predict the stock price based on input features.<br>    &quot;&quot;&quot;<br>    try:<br>        data = await request.json()  # Parse JSON from the request<br>        features = np.array(data[&quot;features&quot;]).reshape(1, -1)  # Convert to 2D array<br>        prediction = model.predict(features)[0]<br>        return {&quot;prediction&quot;: prediction}<br>    except Exception as e:<br>        return {&quot;error&quot;: str(e)}<br><br>@app.get(&quot;/&quot;)<br>def root():<br>    &quot;&quot;&quot;<br>    Health check endpoint.<br>    &quot;&quot;&quot;<br>    return {&quot;message&quot;: &quot;Stock Price Prediction API is up and running!&quot;}</pre><h4>Step 3: Run the FastAPI Application</h4><ol><li>Open your terminal.</li><li>Navigate to the directory containing app.py.</li><li>Run the application using <strong>Uvicorn</strong>:</li></ol><pre>uvicorn app:app --reload --host 0.0.0.0 --port 8000</pre><p>4. Once the application starts, you should see output like:</p><pre>INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)</pre><p>5. Open your browser and visit http://127.0.0.1:8000/ to confirm the API is running.</p><h4>Step 4: Testing the API Locally</h4><ul><li><strong>Root Endpoint</strong>:</li><li>Visit http://127.0.0.1:8000/ in your browser.</li><li>You should see:</li></ul><pre>{&quot;message&quot;: &quot;Stock Price Prediction API is up and running!&quot;}</pre><p><strong>Prediction Endpoint</strong>:</p><ul><li>Use Postman or curl to test the /predict/ endpoint.</li><li>Sample Request:</li></ul><pre>{<br>    &quot;features&quot;: [150.5, 149.2, 1000000]<br>}</pre><ul><li>Expected Response:</li></ul><pre>{&quot;prediction&quot;: &lt;value&gt;}</pre><h3>E. Testing Locally with Postman</h3><p>With the FastAPI application running, it’s time to test the endpoints to ensure they function as expected. We’ll use <strong>Postman</strong> to send requests and validate the responses.</p><h4>Step 1: Open Postman</h4><p>If you don’t have Postman installed, download it here and install it.</p><h4>Step 2: Test the Root Endpoint</h4><ol><li>Open Postman and create a <strong>new request</strong>.</li><li>Set the HTTP method to <strong>GET</strong>.</li><li>Enter the following URL:</li></ol><pre>http://127.0.0.1:8000/</pre><p>4. Click <strong>Send</strong>.</p><p><strong>Expected Response</strong>:</p><pre>{<br>    &quot;message&quot;: &quot;Stock Price Prediction API is up and running!&quot;<br>}</pre><h4>Step 3: Test the Prediction Endpoint</h4><ol><li>In Postman, create another <strong>new request</strong>.</li><li>Set the HTTP method to <strong>POST</strong>.</li><li>Enter the following URL:</li></ol><pre>http://127.0.0.1:8000/predict/</pre><p>4. Go to the <strong>Headers</strong> tab and set:</p><ul><li><strong>Key</strong>: Content-Type</li><li><strong>Value</strong>: application/json</li></ul><p>5. Go to the <strong>Body</strong> tab and:</p><ul><li>Select <strong>raw</strong>.</li><li>Choose <strong>JSON</strong> from the dropdown menu.</li><li>Enter the following sample payload</li></ul><pre>{<br>    &quot;features&quot;: [150.5, 149.2, 1000000]<br>}</pre><p>6. Click <strong>Send</strong>.</p><p><strong>Expected Response</strong>:</p><pre>{<br>    &quot;prediction&quot;: &lt;value&gt;<br>}</pre><p>6. Containerizing the Application with Docker</p><p>Now that the FastAPI application is running locally, the next step is to containerize it using Docker. This ensures the application can run consistently across different environments, whether it’s your local machine, a server, or the cloud.</p><h4>Step 1: Install Docker</h4><ul><li>If Docker isn’t installed, download and install it from the official Docker website.</li><li>Verify the installation by running:</li></ul><pre>docker --version</pre><h4>Step 2: Create a Dockerfile</h4><p>The Dockerfile defines the environment and instructions for building the Docker image.</p><ol><li>In the same directory as app.py, create a new file named Dockerfile (no extension).</li><li>Add the following content to the file:</li></ol><pre># Use the official Python image<br>FROM python:3.9-slim<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy the requirements file and install dependencies<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Copy the application files<br>COPY app.py .<br>COPY stock_model.pkl .<br><br># Expose the port that the app runs on<br>EXPOSE 8000<br><br># Command to run the application<br>CMD [&quot;uvicorn&quot;, &quot;app:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h4>Step 3: Create a requirements.txt File</h4><p>This file lists all the dependencies for your application.</p><ol><li>In the same directory, create a file named requirements.txt.</li><li>Add the following dependencies:</li></ol><pre>fastapi<br>uvicorn<br>scikit-learn<br>numpy</pre><h4>Step 4: Build the Docker Image</h4><p>Run the following command in the terminal to build the Docker image:</p><pre>docker build -t fastapi-mlops-app .</pre><p><strong>Explanation</strong>:</p><ul><li>docker build: Command to build the image.</li><li>-t fastapi-mlops-app: Tags the image with the name fastapi-mlops-app.</li><li>.: Refers to the current directory as the build context.</li></ul><h4>Step 5: Run the Docker Container</h4><p>Run the container to start your API inside Docker:</p><pre>docker run -d -p 8000:8000 fastapi-mlops-app</pre><p><strong>Explanation</strong>:</p><ul><li>-d: Runs the container in detached mode (in the background).</li><li>-p 8000:8000: Maps port 8000 on your machine to port 8000 in the container.</li></ul><h4>Step 6: Test the Application</h4><ol><li>Open your browser or Postman.</li><li>Visit the root endpoint:</li></ol><pre>http://127.0.0.1:8000/</pre><p>3. Test the /predict/ endpoint with the same payload used earlier.</p><h4>Step 7: Verify the Running Container</h4><p>Check the running container:</p><pre>docker ps</pre><h3>F. Pushing the Docker Image to DockerHub</h3><p>Now that your FastAPI application is containerized and running locally, the next step is to push the Docker image to DockerHub. This allows you to share the image or deploy it to cloud platforms.</p><h4>Step 1: Log In to DockerHub</h4><ol><li>Open your terminal.</li><li>Log in to DockerHub using the following command:</li></ol><pre>docker login</pre><p>3. Enter your DockerHub credentials</p><h4>Step 2: Tag the Docker Image</h4><p>DockerHub requires your image to have a specific format for the repository name. Tag your image with your DockerHub username and repository name:</p><pre>docker tag fastapi-mlops-app &lt;your_dockerhub_username&gt;/fastapi-mlops-app:latest</pre><h4>Step 3: Push the Docker Image</h4><p>Push the tagged image to your DockerHub account:</p><pre>docker push &lt;your_dockerhub_username&gt;/fastapi-mlops-app:latest</pre><p>Replace &lt;your_dockerhub_username&gt; with your actual DockerHub username.</p><h4>Step 4: Verify on DockerHub</h4><ol><li>Open DockerHub in your browser.</li><li>Log in to your account.</li><li>Navigate to the <strong>Repositories</strong> section.</li><li>You should see your fastapi-mlops-app repository listed.</li></ol><h3>G. Recommendations for What’s Next</h3><p>With the Docker image successfully pushed to DockerHub, you now have a portable and shareable version of your FastAPI application. Here are some next steps to consider for further enhancing and deploying your project:</p><h4>1. Deploy the API to a Cloud Platform</h4><p>Take your application live by deploying it to a cloud platform. Here are some options:</p><p><strong>AWS (Amazon Web Services)</strong>:</p><ul><li>Use AWS Elastic Beanstalk or AWS Fargate to deploy your container.</li></ul><p><strong>Google Cloud</strong>:</p><ul><li>Deploy using Google Cloud Run for a fully managed container service.</li></ul><p><strong>Heroku</strong>:</p><ul><li>A simpler option for small projects. Deploy Docker containers directly.</li></ul><p><strong>Azure</strong>:</p><ul><li>Use Azure App Service or Azure Container Instances for deployment.</li></ul><h4>2. Add Logging and Monitoring</h4><p>Improve your API’s reliability and maintainability:</p><ul><li>Use tools like <strong>Prometheus</strong> or <strong>ELK Stack</strong> (Elasticsearch, Logstash, Kibana) to monitor API performance and track requests.</li><li>Integrate logging with Python’s logging module for better debugging and tracking.</li></ul><pre>import logging<br>logging.basicConfig(level=logging.INFO)</pre><h4>3. Implement Unit and Integration Testing</h4><p>Ensure your application behaves as expected:</p><ul><li>Write unit tests for the API using <strong>pytest:</strong></li></ul><pre>from fastapi.testclient import TestClient<br>from app import app<br><br>client = TestClient(app)<br><br>def test_predict():<br>    response = client.post(&quot;/predict/&quot;, json={&quot;features&quot;: [150.5, 149.2, 1000000]})<br>    assert response.status_code == 200<br>    assert &quot;prediction&quot; in response.json()</pre><p>Run the tests:</p><pre>pytest test_app.py</pre><h4>4. Automate CI/CD Pipelines</h4><p>Set up Continuous Integration/Continuous Deployment (CI/CD) pipelines to automate testing and deployment:</p><ul><li>Use tools like <strong>GitHub Actions</strong>, <strong>GitLab CI</strong>, or <strong>CircleCI</strong>.</li><li>Automate the build, test, and deployment process to ensure consistent releases.</li></ul><h4>5. Optimize for Production</h4><ul><li><strong>Scaling</strong>: Use Kubernetes or Docker Swarm for managing containers at scale.</li><li><strong>Security</strong>: Secure the API by implementing authentication and HTTPS.</li><li><strong>Efficiency</strong>: Optimize the model loading process or switch to a lightweight framework like <strong>ONNX</strong> for better performance.</li></ul><h4>6. Explore Advanced Features</h4><ul><li>Integrate a database (e.g., PostgreSQL, Firebase) to store prediction logs for analytics.</li><li>Add a front-end interface for user interaction.</li><li>Experiment with multi-model endpoints to handle different use cases.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08741cff1884" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of Machine Learning]]></title>
            <link>https://medium.com/@kisetzuu/100-days-of-machine-learning-93348c281e50?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/93348c281e50</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 19:02:48 GMT</pubDate>
            <atom:updated>2024-12-18T19:02:48.004Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Success doesn’t come from what you do occasionally, it comes from what you do consistently.”<br>– <strong>Marie Forleo</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6MIVCPoSvO7abPZ4" /><figcaption>This thumbnail was generated using DALL·E</figcaption></figure><h3>Introduction</h3><p>Check out my <strong>100 Days of Machine Learning Journey</strong> on GitHub: <a href="https://github.com/kisetzuu/100-Days-Of-Machine-Learning"><strong>100-Days-Of-Machine-Learning</strong></a>. This repository contains all the code, projects, and lessons I tackled during the challenge.</p><p>Machine learning has always fascinated me — a field where mathematics meets creativity, producing solutions that redefine industries. As a <strong>Machine Learning Engineer</strong>, I realized the importance of constantly refreshing and expanding my knowledge to stay sharp in this ever-evolving field. A hundred days ago, I decided to take on the <strong>100 Days of Machine Learning Challenge</strong> to achieve just that.</p><p>This challenge was not only a way to reinforce my foundations but also an opportunity to explore advanced concepts, build real-world projects, and push my boundaries. From mastering the basics to deploying models in production, this journey has been transformative.</p><p>If you’re inspired to start your own challenge or want to delve into the specifics of what I covered, feel free to explore the repository. I hope my experience motivates you to embark on your own path to mastering machine learning!</p><h3>Why 100 Days of Machine Learning?</h3><p>Why 100 days? Because consistency beats intensity. Machine learning is vast, and tackling it requires structure, focus, and patience. Committing to 100 days allowed me to:</p><ul><li>Build a strong foundation without feeling overwhelmed.</li><li>Progress gradually from basics to advanced concepts.</li><li>Stay accountable by tracking daily learning goals.</li><li>Apply my skills in real-world scenarios, turning theory into practice.</li></ul><p>This approach ensured I didn’t just learn; I truly mastered.</p><h3>The Journey: Week-by-Week Breakdown</h3><h4>Week 1–3: Foundations of Python and Data Handling</h4><ul><li>Learned Python basics, NumPy for numerical operations, and Pandas for data manipulation.</li><li>Gained insights into data cleaning, preprocessing, and visualization with Matplotlib and Seaborn.</li><li>Challenge: Cleaning inconsistent datasets and handling missing values efficiently.</li></ul><h4>Week 4–6: Building Core Machine Learning Skills</h4><ul><li>Built regression and classification models using Scikit-learn.</li><li>Explored feature engineering techniques like scaling, encoding, and selection.</li><li>Challenge: Understanding when to use specific models and how to interpret evaluation metrics.</li></ul><h4>Week 7–9: Diving into Deep Learning</h4><ul><li>Implemented feedforward neural networks, CNNs, and RNNs using PyTorch.</li><li>Used CNNs for image classification and RNNs for sequential data like time series.</li><li>Challenge: Debugging deep learning models and optimizing their hyperparameters.</li></ul><h4>Week 10–12: Advanced Topics and Applications</h4><ul><li>Tackled transfer learning with pre-trained models like BERT and ResNet.</li><li>Learned Explainable AI (XAI) techniques to interpret models using SHAP and LIME.</li><li>Challenge: Balancing learning advanced concepts with applying them in meaningful projects.</li></ul><h4>Week 13–14: Real-World Projects and Final Mastery</h4><ul><li>Built an end-to-end customer churn prediction pipeline.</li><li>Deployed models using Flask, Docker, and AWS, integrating all previous skills.</li><li>Challenge: Setting up cloud services for the first time and ensuring a seamless deployment process.</li></ul><h3>Tools and Techniques I Mastered</h3><ul><li><strong>Programming</strong>: Python for ML workflows.</li><li><strong>Libraries</strong>: NumPy, Pandas, Scikit-learn, TensorFlow, PyTorch, and Hugging Face Transformers.</li><li><strong>Visualization</strong>: Matplotlib, Seaborn, SHAP (for explainability).</li><li><strong>Deployment</strong>: Flask, Docker, AWS Elastic Beanstalk.</li><li><strong>Skills</strong>: Data preprocessing, feature engineering, model training, evaluation, and deployment.</li></ul><h3>Reflection: What I Learned</h3><p>This journey taught me more than machine learning — it taught me discipline, problem-solving, and how to break complex goals into achievable milestones. Some lessons that stood out:</p><ul><li>Start small and build momentum. The basics are crucial.</li><li>It’s okay to struggle. The steep learning curve makes success even sweeter.</li><li>Collaboration and community can amplify learning. Resources like Kaggle, GitHub, and forums were invaluable.</li></ul><h3>Advice for Aspiring ML Learners</h3><ul><li><strong>Start with the Basics</strong>: Ensure a strong foundation in Python, data handling, and statistics.</li><li><strong>Stay Consistent</strong>: Commit daily, even if it’s just 30 minutes of learning.</li><li><strong>Apply What You Learn</strong>: Build projects — nothing reinforces concepts better.</li><li><strong>Leverage Free Resources</strong>: Use YouTube, blogs, and communities like Kaggle and Stack Overflow.</li><li><strong>Don’t Fear Failure</strong>: Every error is an opportunity to learn.</li></ul><h3>Call to Action</h3><p>Take the leap. Set a 100-day challenge for yourself. Learn, build, and grow. Whether it’s machine learning or any other goal, consistency and effort will get you there. Share your journey, inspire others, and let’s build the future together. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93348c281e50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring AI-Driven Solutions for Early Lung Cancer Detection in Medical Imaging]]></title>
            <link>https://medium.com/@kisetzuu/exploring-ai-driven-solutions-for-early-lung-cancer-detection-in-medical-imaging-68361aa8eb2b?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/68361aa8eb2b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 07:43:50 GMT</pubDate>
            <atom:updated>2024-12-17T07:43:50.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G38r0sQrwckGif0BnpH0uQ.jpeg" /><figcaption><em>Visualizing AI and Healthcare: Bridging the Gap for Lung Cancer Detection.”</em><br><em>Generated by DALL·E</em></figcaption></figure><h3>Abstract</h3><p>Lung cancer remains one of the leading causes of cancer-related deaths globally. Early detection of lung nodules using chest CT scans can significantly improve patient outcomes. In this case study, we explore the development of an automated lung nodule detection system using the LUNA16 dataset and deep learning. The pipeline includes data preprocessing, a 3D convolutional neural network (3D CNN) for classification, model evaluation on unseen data, and model interpretability using Grad-CAM.</p><h3>Introduction</h3><p>Lung cancer detection remains a critical challenge in healthcare, often relying on radiologists manually analyzing CT scans to identify suspicious nodules. While effective, this process can be <strong>time-consuming</strong>, subject to human fatigue, and prone to variability in interpretation.</p><p>This ongoing exploration leverages <strong>machine learning</strong> to develop an AI-based system capable of automating lung nodule detection. Specifically, we experiment with a <strong>deep learning pipeline</strong> that involves:</p><ol><li><strong>Training</strong> a 3D Convolutional Neural Network (CNN) on the LUNA16 dataset.</li><li><strong>Testing</strong> on unseen CT scan data to evaluate the model’s generalization capabilities.</li><li><strong>Interpreting predictions</strong> using Grad-CAM to visualize which regions of the input influenced the model’s decisions.</li></ol><p>The experiment focuses on improving <strong>diagnostic accuracy</strong> while ensuring the model remains <strong>explainable</strong> and interpretable. By combining AI with medical imaging, this exploration aims to bridge gaps in efficiency and precision, offering radiologists a powerful tool to enhance clinical decision-making.</p><p>This work remains an iterative process, where unseen data, model refinements, and further testing contribute to the ongoing journey of building a robust AI system for lung cancer detection.</p><h3>Dataset Overview</h3><h4>LUNA16 Dataset</h4><h4>Dataset Overview</h4><p><strong>LUNA16 Dataset</strong><br>The <strong>Lung Nodule Analysis 2016 (LUNA16)</strong> dataset is a benchmark for developing and evaluating lung nodule detection systems. It includes:</p><ul><li><strong>CT Scans</strong>: Available in <strong>.mhd</strong> (meta-image header) and <strong>.zraw</strong> formats, representing 3D volumetric medical images.</li><li><strong>Annotations</strong>: A <strong>.csv</strong> file containing nodule details, including <strong>coordinates</strong> (x, y, z) and <strong>diameters</strong> in millimeters.</li><li><strong>Evaluation Standard</strong>: Designed for <strong>training</strong> and <strong>validation</strong> of automated lung nodule detection algorithms, ensuring reproducible performance comparisons.</li></ul><p><strong>Key Challenges</strong></p><ol><li><strong>Handling Large 3D Volumetric Data</strong>:<br>Managing and preprocessing high-dimensional CT scans requires significant computational resources.</li><li><strong>Patch Extraction</strong>:<br>Extracting meaningful 3D regions (patches) centered around annotated nodules from CT volumes while avoiding redundant information.</li><li><strong>Class Imbalance</strong>:<br>The dataset contains significantly more non-nodule regions than nodules, posing challenges for model training and generalization.</li></ol><h3>Methodology</h3><h4>Step 1: Data Preprocessing</h4><ol><li><strong>Loading CT Scans</strong>:</li></ol><ul><li>CT scans were loaded using the SimpleITK library, extracting 3D arrays, voxel spacing, and origin information.</li></ul><pre>import SimpleITK as sitk<br>import numpy as np<br><br># Load a CT scan<br>def load_ct_scan(file_path):<br>    scan = sitk.ReadImage(file_path)<br>    ct_array = sitk.GetArrayFromImage(scan)<br>    spacing = scan.GetSpacing()<br>    origin = scan.GetOrigin()<br>    return ct_array, spacing, origin<br><br># Extract a patch<br>def extract_patch(ct_array, center, patch_size=(64, 64, 64)):<br>    z, y, x = center<br>    half_size = np.array(patch_size) // 2<br>    start = np.maximum([z, y, x] - half_size, 0)<br>    end = start + patch_size<br>    patch = np.zeros(patch_size, dtype=ct_array.dtype)<br>    actual_patch = ct_array[start[0]:end[0], start[1]:end[1], start[2]:end[2]]<br>    patch[:actual_patch.shape[0], :actual_patch.shape[1], :actual_patch.shape[2]] = actual_patch<br>    return patch</pre><p><strong>2. Patch Extraction</strong>:</p><ul><li><strong>Positive Patches</strong>: Centered on annotated nodules using the coordinates provided in annotations.csv.</li><li><strong>Negative Patches</strong>: Randomly sampled regions without nodules, ensuring no overlap with annotated nodules.</li></ul><p><strong>3. Normalization</strong>:</p><ul><li>All patches were normalized to have intensity values between [0, 1].</li></ul><p><strong>4. Data Splitting</strong>:</p><ul><li>The dataset was split into <strong>80% training data</strong> and <strong>20% testing data</strong>.</li></ul><h4>Step 2: Model Design</h4><ol><li><strong>Model Architecture</strong>:</li></ol><ul><li>A 3D CNN was developed to analyze 3D patches.</li></ul><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Conv3D, MaxPooling3D, Flatten, Dense, Dropout<br><br>model = Sequential([<br>    Conv3D(32, (3, 3, 3), activation=&#39;relu&#39;, input_shape=(64, 64, 64, 1)),<br>    MaxPooling3D((2, 2, 2)),<br>    Conv3D(64, (3, 3, 3), activation=&#39;relu&#39;),<br>    MaxPooling3D((2, 2, 2)),<br>    Conv3D(128, (3, 3, 3), activation=&#39;relu&#39;),<br>    MaxPooling3D((2, 2, 2)),<br>    Flatten(),<br>    Dense(256, activation=&#39;relu&#39;),<br>    Dropout(0.5),<br>    Dense(1, activation=&#39;sigmoid&#39;)<br>])<br><br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><p>2. <strong>Key components:</strong></p><ul><li><strong>Conv3D Layers</strong>: Extract spatial features.</li><li><strong>MaxPooling3D Layers</strong>: Reduce spatial dimensions.</li><li><strong>Dense Layers</strong>: Perform final classification.</li><li><strong>Dropout</strong>: Prevent overfitting.</li></ul><p><strong>Input Shape</strong>:</p><ul><li>(64, 64, 64, 1) (3D patches with one intensity channel).</li></ul><p><strong>Loss Function</strong>:</p><ul><li>Binary Crossentropy.</li></ul><p><strong>Optimizer</strong>:</p><ul><li>Adam optimizer for efficient convergence.<strong>Output</strong>:</li><li>A single neuron with Sigmoid activation to output the probability of the patch containing a nodule.</li></ul><h4>Step 3: Model Training</h4><pre># Split data<br>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(all_patches, all_labels, test_size=0.2, random_state=42)<br><br># Train the model<br>history = model.fit(X_train, y_train, validation_split=0.2, epochs=20, batch_size=16)<br><br># Evaluate on test data<br>test_loss, test_accuracy = model.evaluate(X_test, y_test)<br>print(f&quot;Test Accuracy: {test_accuracy:.2f}&quot;)</pre><ol><li><strong>Hyperparameters</strong>:</li></ol><ul><li>Batch size: 16.</li><li>Epochs: 20.</li></ul><p><strong>2. Training Process</strong>:</p><ul><li>The model was trained using the extracted patches.</li><li>Validation data was used to monitor overfitting.</li></ul><p><strong>3. Results</strong>:</p><ul><li><strong>Training Accuracy</strong>: ~85%.</li><li><strong>Validation Accuracy</strong>: ~70%.</li></ul><h4>Step 4: Model Testing</h4><ol><li><strong>Testing on Held-Out Data</strong>:</li></ol><ul><li>The model was evaluated on the 20% test set.</li></ul><p><strong>Metrics</strong>:</p><ul><li>Accuracy: ~69%.</li><li>Precision (positive class): ~72%.</li><li>Recall (positive class): ~87%.</li><li>ROC-AUC: ~0.62.</li></ul><h3>Results</h3><p>The 3D CNN model was trained for 20 epochs over approximately 8 hours. The final metrics, evaluated on a <strong>test set of 20% unseen data</strong>, are as follows:</p><h4>Model Performance</h4><ul><li><strong>Test Accuracy</strong>: <strong>82%</strong></li><li><strong>Precision (Positive Class — Nodule)</strong>: <strong>48%</strong></li><li><strong>Recall (Positive Class — Nodule)</strong>: <strong>5%</strong></li><li><strong>F1-Score (Positive Class — Nodule)</strong>: <strong>8%</strong></li><li><strong>ROC-AUC</strong>: <strong>0.7429</strong></li></ul><h4>Performance Analysis</h4><ul><li><strong>High Accuracy</strong>: The overall accuracy of <strong>82%</strong> demonstrates the model’s ability to classify non-nodule regions effectively.</li><li><strong>Imbalance in Positive Predictions</strong>: The recall for nodules (positive class) remains low at <strong>5%</strong>, indicating that the model struggles to detect positive nodule patches. This is likely due to <strong>class imbalance</strong> in the dataset, where non-nodule regions vastly outnumber nodule regions.</li><li><strong>ROC-AUC</strong>: With an ROC-AUC score of <strong>0.74</strong>, the model shows moderate ability to distinguish between nodule and non-nodule patches.</li></ul><p><strong>3. Testing on CT Scans</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*V-qx9o04cQotj13XSk63Sg.png" /><figcaption>Figure 1: Raw Loaded Patch</figcaption></figure><ul><li><strong>Description</strong>:<br>Figure 1 shows the middle slice of the raw 3D CT patch extracted from the .mhd file. This visualization highlights the lung region in grayscale, where different intensities represent tissue densities. The lung boundaries are clearly visible, with low-intensity (black) regions representing air-filled spaces and higher-intensity (gray) regions representing soft tissue structures.</li><li><strong>Interpretation</strong>:<br>This raw slice provides an unprocessed view of the CT data. The lack of visible nodules or abnormalities in this slice visually aligns with the model’s low probability prediction for a lung nodule. However, the presence or absence of nodules cannot always be determined visually in a single slice, emphasizing the importance of the deep learning model analyzing the entire 3D patch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*wU4-8gG6xzpIbZMxtoq7Iw.png" /><figcaption>Figure 2: Path After Resizing — Shape: (64, 64, 64)</figcaption></figure><ul><li><strong>Description</strong>:<br>Figure 2 shows the middle slice after preprocessing. Preprocessing includes:</li><li><strong>Normalization</strong>: Intensity values are scaled to the range [0, 1], ensuring consistency across CT scans.</li><li><strong>Resizing</strong>: The patch is resized to a uniform shape of (64, 64, 64), which is required for input into the 3D CNN.</li><li><strong>Shape Transformation</strong>: The patch is reshaped to (64, 64, 64, 1) to include the channel dimension for model compatibility.</li><li>The preprocessing slightly blurs the slice due to resizing and interpolation, but the key structures remain visible.</li><li><strong>Interpretation</strong>:<br>The processed slice ensures the model receives data in a standardized format, enabling it to analyze the spatial relationships within the volume effectively. Despite preprocessing, the normalized intensities remain very low (maximum: 5.94e-07), which reflects the absence of prominent nodules in this region. This aligns with the model&#39;s <strong>predicted probability of 0.34</strong>, classifying the patch as <strong>&quot;No lung nodule detected&quot;</strong>.</li></ul><h3>Results on Data</h3><p>The <strong>model prediction probability</strong> for this CT patch was <strong>0.34</strong>. The model determined that this patch does not contain a lung nodule.</p><p><strong>Reasoning</strong>:</p><ol><li>The intensity distribution in the patch is quite low, with no strong high-intensity regions indicative of nodules.</li><li>The Grad-CAM heatmap (which can be generated in the next step) would provide further insight into whether the model focused on any region within the patch.</li></ol><h3>Interpretation and Insights</h3><p>The current results indicate that the model effectively identifies non-nodule regions but performs poorly on nodule detection. The class imbalance likely biases the model toward the majority (non-nodule) class. This imbalance impacts precision and recall, as false negatives dominate predictions for nodule regions.</p><h3>Challenges</h3><ol><li><strong>Class Imbalance</strong>:</li></ol><ul><li>More non-nodule regions than nodule regions caused bias.</li><li><strong>Mitigation</strong>: Oversampling positive patches and under-sampling negative patches.</li><li><strong>Future Work</strong>: Use advanced techniques like SMOTE or focal loss to improve balance.</li></ul><p><strong>2. Overfitting</strong>:</p><ul><li>Validation loss increased despite high training accuracy.</li><li><strong>Mitigation</strong>: Added dropout regularization and early stopping.</li><li><strong>Future Work</strong>: Data augmentation and deeper architectures like 3D ResNet or DenseNet.</li></ul><p><strong>3. Computational Complexity</strong>:</p><ul><li>High memory and time demands of processing 3D CT data.</li><li><strong>Mitigation</strong>: Patch-based analysis and optimized batch sizes.</li><li><strong>Future Work</strong>: Multi-resolution processing and lightweight models (e.g., 3D MobileNet).</li></ul><p><strong>4. Model Interpretability</strong>:</p><ul><li>Limited 2D Grad-CAM visualization for 3D data.</li><li><strong>Mitigation</strong>: Grad-CAM heatmap overlays for middle slices.</li><li><strong>Future Work</strong>: Full 3D heatmap visualization and advanced tools like SHAP or LRP.</li></ul><p><strong>5. Generalization to Unseen Datasets</strong>:</p><ul><li>Potential performance drop on external datasets.</li><li><strong>Mitigation</strong>: Validation on a hold-out LUNA16 test set.</li><li><strong>Future Work</strong>: External validation on datasets like LIDC-IDRI and fine-tuning on diverse data.</li></ul><h3>Conclusion and Future Directions</h3><p>This work represents an <strong>ongoing exploration</strong> into the application of <strong>AI for automated lung nodule detection</strong> using 3D convolutional neural networks. By leveraging the LUNA16 dataset and a carefully constructed deep learning pipeline, we demonstrated the potential of AI to support early lung cancer detection. The current findings highlight both achievements and limitations, underscoring the iterative nature of this work.</p><h4>Current Achievements</h4><ol><li><strong>Data Preprocessing</strong>: Successfully processed 3D CT scan patches, ensuring compatibility with the 3D CNN model.</li><li><strong>Model Training and Evaluation</strong>: Achieved a <strong>test accuracy of 82%</strong> with an ROC-AUC score of <strong>0.74</strong>, demonstrating moderate discriminatory power.</li><li><strong>Insights from Unseen Data</strong>: Testing on unseen CT patches provided valuable feedback on the model’s generalization ability, particularly in identifying non-nodule regions.</li></ol><h4>Future Directions</h4><p>The exploration will evolve through the following key areas:</p><ol><li><strong>Enhanced Model Interpretability</strong>:</li></ol><ul><li>Implementing <strong>Grad-CAM</strong> to provide visual explanations of the regions influencing the model’s decisions. This will enhance trust and offer radiologists intuitive insights into the AI’s predictions.</li></ul><p>2. <strong>Improved Generalization</strong>:</p><ul><li>Testing on external datasets such as <strong>LIDC-IDRI</strong> and <strong>NLST</strong> to validate the model’s robustness and ensure performance across diverse patient populations and imaging conditions.</li></ul><p>3.<strong> Addressing Class Imbalance</strong>:</p><ul><li>Integrating advanced <strong>data augmentation</strong> techniques, such as random rotations, flips, and contrast adjustments, to increase training diversity.</li><li>Exploring methods like <strong>focal loss</strong> and <strong>oversampling</strong> of nodule patches to address the imbalance between nodule and non-nodule regions effectively.</li></ul><p>4.<strong> Advanced Architectures</strong>:</p><ul><li>Experimenting with deeper 3D network architectures, such as <strong>3D ResNet</strong> and <strong>3D DenseNet</strong>, to improve feature extraction and classification performance.</li><li>Investigating the use of <strong>transfer learning</strong> with pre-trained 3D medical imaging models to accelerate convergence and improve accuracy.</li></ul><h4>Conclusion</h4><p>This exploration serves as a foundational step in the integration of AI for medical imaging, particularly for early lung cancer detection. While the current model shows promise, ongoing refinements and future iterations will focus on enhancing interpretability, addressing class imbalance, and improving robustness across datasets. By bridging the gap between AI and clinical applications, this work aspires to deliver an accurate, explainable, and clinically viable solution for lung nodule detection, ultimately aiding radiologists in their critical decision-making processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68361aa8eb2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Algorithms to Applications: The Role of Machine Learning in Software Engineering]]></title>
            <link>https://medium.com/@kisetzuu/from-algorithms-to-applications-the-role-of-machine-learning-in-software-engineering-dac0a6dfb990?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/dac0a6dfb990</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 03:06:04 GMT</pubDate>
            <atom:updated>2024-11-17T03:06:04.966Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Artificial intelligence is the science of making machines do things that would require intelligence if done by men.” — Marvin Minsky</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qR4S2zM0rh8oMvy8" /><figcaption>Image generated by DALL-E: Visual representation of <em>‘From Algorithms to Applications: The Role of Machine Learning in Software Engineering</em></figcaption></figure><h3><strong>I. Predictive Analytics and Automated Decision-Making</strong></h3><ul><li><strong>Insight</strong>: Machine learning enables software to predict future trends, such as user behavior, system failures, or demand fluctuations, based on historical data. Automated decision systems can adjust to these trends, improving responsiveness and efficiency.</li><li><strong>Applications</strong>: Customer behavior analysis, supply chain forecasting, real-time recommendation engines.</li><li><strong>Considerations</strong>: Predictive models rely on high-quality data; poor data quality leads to inaccurate predictions, requiring frequent updates and monitoring for accuracy.</li></ul><h3>II. Smart Testing and Quality Assurance</h3><ul><li><strong>Insight</strong>: ML models can automate the testing process by generating and running test cases based on patterns and historical data, reducing manual work and enhancing bug detection.</li><li><strong>Applications</strong>: Test case generation, anomaly detection, and automated debugging in software builds.</li><li><strong>Considerations</strong>: While ML-based testing reduces manual work, false positives and negatives remain a challenge. Pairing ML-driven testing with manual QA improves reliability.</li></ul><h3>III. Code Synthesis and Optimization</h3><ul><li><strong>Insight</strong>: Machine learning tools assist with code generation, refactoring, and optimization, allowing software engineers to spend more time on complex and creative tasks.</li><li><strong>Applications</strong>: Tools like OpenAI Codex generate code snippets, improve efficiency, and suggest optimizations based on common coding patterns.</li><li><strong>Considerations</strong>: ML-generated code may not fully meet project standards or security needs, making it crucial for engineers to review suggestions critically.</li></ul><h3>IV. Predictive Maintenance and Proactive Monitoring</h3><ul><li><strong>Insight</strong>: ML enhances system monitoring by predicting potential issues, allowing for timely intervention and reducing unexpected downtime.</li><li><strong>Applications</strong>: Proactive alerts in critical applications, anomaly detection in logs, dynamic resource allocation based on demand.</li><li><strong>Considerations</strong>: Predictive models sometimes produce false alarms, which can lead to unnecessary intervention. Continuous tuning and data refinement are essential to maintain effectiveness.</li></ul><h3>V. Personalized User Experience and Engagement</h3><ul><li><strong>Insight</strong>: Machine learning enables dynamic personalization in applications, offering users customized content and experiences based on preferences and behavior.</li><li><strong>Applications</strong>: Recommendation engines in e-commerce, dynamic user interfaces, and personalized content delivery in streaming platforms.</li><li><strong>Considerations</strong>: Personalization relies on sensitive user data, making privacy and ethical data handling critical. Transparency with users about data usage fosters trust and adherence to privacy laws.</li></ul><h3>VI. Enhanced Security through Anomaly and Threat Detection</h3><ul><li><strong>Insight</strong>: ML models provide advanced security by identifying unusual patterns, alerting engineers to potential security threats, and minimizing risks.</li><li><strong>Applications</strong>: Fraud detection in financial systems, behavioral analysis for unauthorized access detection, and threat prediction.</li><li><strong>Considerations</strong>: Security ML models must continuously adapt to new threat patterns, requiring regular retraining and monitoring to ensure robust protection against evolving cyber threats.</li></ul><h3>VII. Optimized DevOps and CI/CD Automation</h3><ul><li><strong>Insight</strong>: Machine learning improves efficiency in DevOps, streamlining build and deployment processes and automating dependency checks and rollbacks.</li><li><strong>Applications</strong>: Predictive error detection in CI/CD, automated dependency management, and deployment optimization.</li><li><strong>Considerations</strong>: Automated rollbacks or deployments carry risks, especially in complex applications. A balance between automation and manual review helps maintain stability in production environments.</li></ul><h3>VIII. NLP in Documentation and Support</h3><ul><li><strong>Insight</strong>: NLP models in machine learning automatically generate and update documentation, enhancing consistency and making it easier for teams to stay aligned.</li><li><strong>Applications</strong>: Real-time documentation updates based on code changes, intelligent chatbots for customer support, and instant FAQ response.</li><li><strong>Considerations</strong>: NLP may misinterpret complex code or user queries, so human review is essential to ensure documentation quality and customer support accuracy.</li></ul><h3>IX. Skill Development and Knowledge Sharing</h3><ul><li><strong>Insight</strong>: ML helps software engineers grow by personalizing learning paths, suggesting resources for skill improvement, and promoting knowledge transfer within teams.</li><li><strong>Applications</strong>: Tailored learning recommendations on platforms like DataCamp, expertise matching for mentorship within organizations.</li><li><strong>Considerations</strong>: While ML aids skill development, real-world application and peer feedback are crucial to mastering skills. Privacy is a concern when using ML to analyze internal expertise for knowledge sharing.</li></ul><h3>X. Ethical and Security Implications of ML-Driven Engineering</h3><ul><li><strong>Insight</strong>: The use of ML in software engineering raises ethical considerations, particularly around transparency, data privacy, and potential biases in decision-making algorithms.</li><li><strong>Applications</strong>: Explainable AI (XAI) frameworks to interpret model decisions, transparency standards for data handling in personalized experiences.</li><li><strong>Considerations</strong>: Ensuring ethical AI use involves transparency in model decision processes, fairness, and adherence to privacy regulations. Responsible AI practices foster trust and reliability in ML-driven applications.</li></ul><h3>Conclusion: The Balanced Future of ML in Software Engineering</h3><p>Machine learning transforms software engineering by enabling predictive, adaptive, and personalized applications. The impact of ML extends beyond automation, offering engineers powerful insights and elevating user experiences. However, these advancements come with considerations around data quality, model accuracy, ethical responsibility, and the importance of human oversight. The most successful ML applications in software engineering strike a balance between automation and human expertise, leveraging ML for efficiency while maintaining critical ethical and technical standards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dac0a6dfb990" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Driven Traffic Lights: Reinforcement Learning and YOLOv5 for Smarter Roads]]></title>
            <link>https://medium.com/@kisetzuu/ai-driven-traffic-lights-reinforcement-learning-and-yolov5-for-smarter-roads-6f521c44951e?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f521c44951e</guid>
            <category><![CDATA[smart-cities]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 02:00:09 GMT</pubDate>
            <atom:updated>2024-11-01T02:00:09.324Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>“Artificial intelligence is the future, and the future is here.”</strong><br> — <em>Dave Waters</em></blockquote><h3>Introduction</h3><p>Urban traffic congestion is a growing challenge, causing delays, frustration, and inefficiencies in cities worldwide. The traditional traffic light systems, which often operate on fixed cycles, are not responsive to real-time traffic conditions, leading to unnecessary waits and frequent bottlenecks.</p><p>Artificial Intelligence (AI) offers a solution to this problem by enabling dynamic, data-driven control of traffic systems. In this article, we explore how YOLOv5, a state-of-the-art object detection model, combined with reinforcement learning (RL), can create adaptive traffic light systems that respond to real-time traffic conditions, optimizing the flow of vehicles and reducing congestion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZWEp0cfQY-TZYLaQm5DwA.jpeg" /><figcaption>Generated by DALL-E</figcaption></figure><h3>Problem Statement</h3><p>Conventional traffic light systems rely on predefined timer-based cycles, which remain static regardless of traffic volume at intersections. These systems are incapable of dynamically adjusting to changing traffic conditions, leading to inefficiencies such as long wait times when there are few or no vehicles at a red light, or insufficient green light time when traffic density is high.</p><p><strong>The problem with static traffic light systems:</strong></p><ul><li>Traffic lights may remain red when no vehicles are present.</li><li>Green lights might not stay on long enough to clear traffic during peak hours.</li><li>Lack of real-time adaptation leads to traffic jams and increased fuel consumption.</li></ul><p>To solve these problems, we propose an AI-driven approach that leverages the real-time vehicle detection capabilities of YOLOv5 and the decision-making power of RL to adjust traffic lights based on actual traffic conditions.</p><h3>Background on YOLOv5 and Reinforcement Learning</h3><h4>1. YOLOv5 for Object Detection</h4><p><strong>YOLOv5</strong> is a highly efficient object detection model that can identify multiple objects within an image in real-time. YOLO (You Only Look Once) is known for its speed and accuracy, making it ideal for time-sensitive applications like traffic monitoring.</p><p><strong>Why YOLOv5 for traffic detection?</strong></p><ul><li><strong>Speed:</strong> YOLOv5 can process live video streams in real-time, making it ideal for detecting vehicles on busy intersections.</li><li><strong>Accuracy:</strong> It can detect and classify vehicles such as cars, buses, and trucks, which are essential for understanding traffic density.</li><li><strong>Versatility:</strong> YOLOv5 can be easily adapted to various traffic environments with minimal configuration.</li></ul><p>By using YOLOv5 to detect the number of vehicles at an intersection, we can supply real-time data to an RL agent that controls the traffic lights, allowing for more informed decision-making.</p><h4>2. Reinforcement Learning for Traffic Control</h4><p>Reinforcement Learning (RL) is a subset of machine learning where an agent learns to make decisions by interacting with an environment. In this case, the RL agent learns to control the traffic lights by observing the number of vehicles at an intersection, choosing the optimal light cycle to minimize wait times and maximize traffic flow.</p><p><strong>Why use RL for traffic control?</strong></p><ul><li><strong>Dynamic adjustment:</strong> Unlike traditional systems, RL adapts based on real-time traffic data, reducing congestion.</li><li><strong>Learning over time:</strong> The RL agent improves over time as it experiences more traffic patterns, optimizing its decisions.</li><li><strong>Reward system:</strong> The agent is rewarded for clearing traffic efficiently, and penalized for causing long waits.</li></ul><pre># Initialize RL agent&#39;s logic (simplified)<br>current_light = &quot;RED&quot;<br>green_time = 0<br>max_green_duration = 10  # Maximum time for green light<br><br>if vehicle_count &gt; 3 and current_light == &quot;RED&quot;:<br>    current_light = &quot;GREEN&quot;<br>    green_time = 0<br>elif current_light == &quot;GREEN&quot; and green_time &gt;= max_green_duration:<br>    current_light = &quot;RED&quot;</pre><h3>Dataset</h3><p>For the traffic detection and control system, I utilized the <strong>Traffic-Net dataset</strong> (version 1.0), which contains <strong>4,400 images</strong>. This dataset is specifically designed for traffic surveillance tasks, such as vehicle detection and traffic pattern analysis, making it highly suitable for this project. The dataset includes a variety of traffic scenarios, from light to dense traffic, captured at different times of day and from multiple angles.</p><p>The Traffic-Net dataset provides a comprehensive set of images that were instrumental in training and validating the AI system’s performance in real-world traffic conditions. By feeding these images into the YOLOv5 model, I was able to detect vehicles in real-time, and the dataset’s variety ensured the system could handle different types of traffic densities and environments.</p><p><strong>Key Features of the Traffic-Net Dataset</strong>:</p><ul><li><strong>4,400 images</strong> specifically for traffic-related object detection tasks.</li><li>A wide range of traffic scenarios (low, medium, and heavy traffic).</li><li>Images captured at different times of the day (morning, noon, night).</li><li>Different vehicle types such as cars, buses, trucks, and motorcycles.</li></ul><p>The rich variety of this dataset ensured that the YOLOv5 model was exposed to diverse traffic patterns, helping the RL agent make more accurate decisions regarding traffic light control.</p><h3>System Architecture and Setup</h3><h4>1. Video Feed for Object Detection</h4><p>The system begins by capturing video from traffic cameras monitoring intersections. These video feeds are processed by YOLOv5 to detect vehicles in real-time. Each frame is analyzed, and the number of vehicles at the intersection is counted.</p><pre># Process video frame-by-frame<br>import cv2<br>cap = cv2.VideoCapture(&#39;traffic_video.mp4&#39;)<br>while True:<br>    ret, frame = cap.read()<br>    if not ret:<br>        break<br>    results = model(frame)  # Perform YOLOv5 inference<br>    vehicle_count = len(results.xyxy[0])  # Count detected vehicles</pre><p><strong>How it works:</strong></p><ul><li>The video is split into frames.</li><li>YOLOv5 processes each frame and detects vehicles.</li><li>The vehicle count is passed to the RL agent, which determines the optimal action (keep the light green, turn it red, etc.).</li></ul><h4>2. RL Environment for Traffic Control</h4><p>The RL environment simulates an intersection with traffic lights, where the RL agent takes actions (changing lights) based on vehicle counts provided by YOLOv5. The RL agent receives rewards based on how well it manages traffic, encouraging it to minimize waiting times and avoid unnecessary light changes.</p><p><strong>RL environment details:</strong></p><ul><li><strong>State:</strong> The number of vehicles waiting at each side of the intersection.</li><li><strong>Action:</strong> Change the traffic light from red to green or vice versa.</li><li><strong>Reward:</strong> Positive reward for reducing wait times, negative reward for causing traffic jams.</li></ul><h4>3. Flow of Data and Decision-Making</h4><ul><li>The RL agent receives the number of detected vehicles from YOLOv5.</li><li>Based on the traffic density, it determines whether the light should remain green or switch to red.</li><li>A timer is included to ensure no light stays green or red for too long.</li><li>The decision is rendered in real time, and the traffic lights are controlled based on this feedback.</li></ul><pre># Display the current light status on the frame<br>cv2.putText(frame_with_detections, f&quot;Light: {current_light}&quot;, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, <br>            (0, 255, 0) if current_light == &quot;GREEN&quot; else (0, 0, 255), 2)<br>cv2.imshow(&#39;Traffic Light Control&#39;, frame_with_detections)</pre><h3>Conclusion</h3><p><strong>Summary</strong><br>Integrating YOLOv5 and RL in traffic management systems offers a powerful solution for dynamic traffic light adjustment, reducing congestion, and improving urban transport efficiency.</p><p><strong>Future Directions</strong></p><ul><li><strong>Enhanced Training</strong>: Expanding traffic scenarios to further improve RL model training.</li><li><strong>Multi-Intersection Control</strong>: Extending the system to manage multiple intersections.</li><li><strong>Long-Term Data Analysis</strong>: Leveraging data over time to enhance traffic predictions and control strategies.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f521c44951e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Intelligent Chatbots: Engineering Conversations with DialoGPT and Flask]]></title>
            <link>https://medium.com/@kisetzuu/creating-intelligent-chatbots-engineering-conversations-with-dialogpt-and-flask-3afec252c512?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/3afec252c512</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 04:16:15 GMT</pubDate>
            <atom:updated>2024-10-12T04:16:15.972Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Artificial Intelligence is not about replacing human minds, but about augmenting our abilities and helping us see what we couldn’t before.</blockquote><blockquote>— Fei-Fei Li</blockquote><p>In today’s fast-paced digital era, chatbots have emerged as essential tools for transforming how we engage with technology and businesses. From enhancing customer service to providing personalized assistance, chatbots are reshaping user experiences and streamlining communication. In this article, I’ll show you how to build your own conversational AI using Microsoft DialoGPT and Flask, a lightweight Python web framework. By the end, you’ll have a fully functional chatbot that’s ready to deploy and interact with users seamlessly. Let’s dive into crafting a dynamic conversational agent from the ground up!</p><h3>Step 1: Setting Up the Flask App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yb5ISk2tHcxH8yIyKhD49w.jpeg" /><figcaption>Generated by DALL-E.</figcaption></figure><p>To get started, Flask is used to set up a lightweight web server. Flask is a popular Python web framework known for its ease of use in building APIs quickly. For this step, I initialized the Flask app with a simple line of code:</p><pre>from flask import Flask<br>app = Flask(__name__)</pre><p>This initializes the application, which will later be used to create an API endpoint that receives user messages and provides chatbot responses.</p><h3>Step 2: Integrating DialoGPT — Bringing AI Conversations to Life</h3><p>For the chatbot’s conversational core, I’m utilizing Microsoft’s DialoGPT — an open-source model trained on vast amounts of Reddit data. DialoGPT excels at generating dialogue-style responses, making it an ideal choice for building conversational chatbots. To load the pre-trained model, the Transformers library from Hugging Face is used, providing a seamless way to manage models:</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer<br>import torch<br><br># Load Pre-trained Conversational Model<br>tokenizer = AutoTokenizer.from_pretrained(&#39;microsoft/DialoGPT-medium&#39;)<br>model = AutoModelForCausalLM.from_pretrained(&#39;microsoft/DialoGPT-medium&#39;)</pre><p>The AutoTokenizer helps tokenize the user inputs into sequences of tokens that our DialoGPT model can understand. The model then generates responses based on this input to provide an intelligent, contextually aware conversation.</p><h3>Step 3: Defining the Chat Functionality</h3><p>Once we have our model, we need a function to generate responses based on user input. Here, we introduce the generate_response() function that takes the user&#39;s message as input and returns the AI&#39;s response.</p><pre>def generate_response(user_input, reset_history=False):<br>    global chat_history_ids, chat_counter<br>    if reset_history or chat_counter &gt;= MAX_CHAT_HISTORY:<br>        chat_history_ids = None<br>        chat_counter = 0<br><br>    new_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors=&#39;pt&#39;)<br>    bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim=-1) if chat_history_ids is not None else new_input_ids<br>    chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)<br>    response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)<br>    chat_counter += 1<br>    return response</pre><p>This function takes the user input, adds it to the chat history, and then generates a response from the model. If the reset_history flag is True or the conversation reaches a certain threshold, it resets the chat to provide a clean slate for new input.</p><h3>Step 4: Creating an API Endpoint for Chat</h3><p>To make our chatbot accessible, we expose an API endpoint named /chat that listens for POST requests. Users send a message in JSON format, and our API processes it to return a generated response.</p><pre>@app.route(&#39;/chat&#39;, methods=[&#39;POST&#39;])<br>def chat():<br>    data = request.json<br>    if &#39;text&#39; not in data:<br>        return jsonify({&#39;error&#39;: &#39;Missing &quot;text&quot; field in request&#39;}), 400<br><br>    user_text = data[&#39;text&#39;]<br>    reset_history = data.get(&#39;reset&#39;, False)<br>    response = generate_response(user_text, reset_history=reset_history)<br>    return jsonify({&#39;response&#39;: response})</pre><p>This endpoint is where the magic happens: it allows the user to communicate with our chatbot by sending a POST request containing the user input. The chatbot’s reply is then sent back as a response.</p><h3>Step 5: Running Flask with Multithreading</h3><p>In the final part of the script, we start the Flask server in a separate thread. This allows us to run Flask concurrently while providing useful instructions to the user:</p><pre># Step 5: Run Flask App in a separate thread<br>def run_flask():<br>    app.run(host=&#39;0.0.0.0&#39;, port=5000, debug=False, use_reloader=False)<br><br># Run Flask in a separate thread<br>flask_thread = threading.Thread(target=run_flask)<br>flask_thread.daemon = True<br>flask_thread.start()</pre><p>Running Flask in a separate thread gives us the ability to handle server operations in parallel, making our chatbot responsive even while executing other commands.</p><h3>Using Postman to Test the Chatbot</h3><p>Once the server is running, you can use <a href="https://www.postman.com/">Postman</a> or similar tools to test the chatbot. Send a POST request to http://127.0.0.1:5000/chat with the JSON payload:</p><pre>{<br>  &quot;text&quot;: &quot;Your message here&quot;<br>}</pre><p>The response from the server will contain the chatbot’s reply, which you can see in the output window. This interaction forms the basis of an engaging conversation.</p><h3>Tips for Scaling Your Chatbot</h3><ul><li><strong>Resetting History:</strong> Conversations often need a reset to keep them meaningful. We’ve implemented a MAX_CHAT_HISTORY limit to prevent the model from becoming overwhelmed with too much historical data.</li><li><strong>Production Deployment:</strong> To deploy in a production environment, consider using containerization (like Docker) or cloud services like AWS or GCP.</li><li><strong>Optimizing Responses:</strong> Experiment with different model sizes (DialoGPT-small, medium, large) to see what works best for your needs.</li></ul><h3>Conclusion</h3><p>With this guide, you’ve now built a simple but powerful conversational AI using DialoGPT and Flask! From setting up the basic Flask app to integrating the DialoGPT conversational model, this article has shown the steps involved in creating a chatbot capable of engaging in meaningful conversations.</p><p>The next steps could include adding more advanced features such as intent recognition, sentiment analysis, or even integration into a messaging platform. The world of conversational AI is vast, and you’re now equipped with the fundamentals to explore it further.</p><p>Ready to keep the conversation going? Try out these techniques and make your chatbot even more interactive!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3afec252c512" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Diving into Neural Networks: Understanding FNN, CNN, and RNN]]></title>
            <link>https://medium.com/@kisetzuu/deep-diving-into-neural-networks-understanding-fnn-cnn-and-rnn-3345b73676a2?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/3345b73676a2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 11:25:56 GMT</pubDate>
            <atom:updated>2024-09-27T11:25:56.810Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“AI is the engine of the next industrial revolution, and it’s up to us to steer it toward a better world.”</em><br>– <strong>Sundar Pichai</strong></blockquote><p>Artificial Neural Networks (ANNs) are one of the most transformative technologies in the field of artificial intelligence. They mimic the human brain’s ability to learn from data and make decisions. In this article, we’ll dive into three main types of neural networks: <strong>Feedforward Neural Networks (FNNs)</strong>, <strong>Convolutional Neural Networks (CNNs)</strong>, and <strong>Recurrent Neural Networks (RNNs)</strong>.</p><p>Each of these networks has its strengths and ideal use cases. Let’s explore how they work and when to use each one.</p><h3>What is a Neural Network?</h3><p>Neural networks are a subset of machine learning algorithms modeled after the human brain’s structure. They consist of layers of interconnected <strong>neurons</strong>, where each neuron performs a mathematical operation on the input and passes it to the next layer.</p><h3>Key Components of a Neural Network:</h3><ul><li><strong>Input Layer</strong>: Receives data in numerical form.</li><li><strong>Hidden Layers</strong>: Perform computations and extract features from the data.</li><li><strong>Output Layer</strong>: Produces the final prediction or decision.</li><li><strong>Weights and Biases</strong>: Adjusted during training to minimize error.</li><li><strong>Activation Functions</strong>: Introduce non-linearity, allowing the network to solve complex problems.</li></ul><h3>Feedforward Neural Networks (FNN)</h3><p>The most basic type of neural network is the <strong>Feedforward Neural Network (FNN)</strong>. In this architecture, information moves in one direction — from the input layer, through the hidden layers, to the output layer.</p><h3>Characteristics of FNN:</h3><ul><li><strong>No Cycles</strong>: Information only flows forward, meaning no loops or cycles.</li><li><strong>Used for Simple Tasks</strong>: Commonly used for tasks like image classification or regression.</li><li><strong>Fully Connected Layers</strong>: Each neuron in one layer connects to every neuron in the next.</li></ul><h3>How FNN Works:</h3><ol><li><strong>Input</strong> is fed into the network.</li><li>Data is passed through hidden layers, where each neuron applies a mathematical function.</li><li>The <strong>output layer</strong> produces the final prediction.</li></ol><h4>When to Use FNN:</h4><ul><li>When you need to solve relatively simple problems.</li><li>Ideal for cases where the relationship between inputs and outputs is not temporal (e.g., basic image classification).</li></ul><h3>Feedforward Neural Network for Heart Disease Prediction</h3><p>In this section, I implemented a Feedforward Neural Network (FNN) to predict heart disease using the Heart Disease Dataset. The model was built to classify whether a patient is likely to have heart disease based on features like age, cholesterol levels, and blood pressure.</p><p><strong>Model Architecture</strong><br>The FNN consists of three hidden layers with ReLU activations and dropout layers to mitigate overfitting. The final output layer uses a sigmoid activation function for binary classification.</p><pre>model = Sequential([<br>    Dense(64, activation=&#39;relu&#39;, input_dim=X_train.shape[1]),<br>    Dropout(0.5),<br>    Dense(32, activation=&#39;relu&#39;),<br>    Dropout(0.5),<br>    Dense(16, activation=&#39;relu&#39;),<br>    Dense(1, activation=&#39;sigmoid&#39;)<br>])</pre><p><strong>Training and Evaluation</strong><br>The model was compiled with the adam optimizer and trained using early stopping to monitor validation loss. It achieved a satisfactory accuracy score, highlighting the effectiveness of FNNs in binary classification tasks.</p><pre>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=100, callbacks=[EarlyStopping(monitor=&#39;val_loss&#39;, patience=10)])</pre><p>The FNN’s structure and the use of regularization techniques such as dropout resulted in a robust model that generalized well to unseen data, demonstrating the power of neural networks for healthcare-related predictions.</p><pre>model = Sequential([<br>    Dense(64, activation=&#39;relu&#39;, input_dim=X_train.shape[1]),<br>    Dropout(0.5),<br>    Dense(32, activation=&#39;relu&#39;),<br>    Dropout(0.5),<br>    Dense(16, activation=&#39;relu&#39;),<br>    Dense(1, activation=&#39;sigmoid&#39;)<br>])</pre><h3>Convolutional Neural Networks (CNN)</h3><p><strong>Convolutional Neural Networks (CNNs)</strong> are specialized for processing data with a grid-like topology, such as images. CNNs have revolutionized fields like computer vision.</p><h3>Key Features of CNN:</h3><ul><li><strong>Convolutions</strong>: Instead of fully connected layers, CNNs apply convolutional filters to reduce the number of parameters.</li><li><strong>Pooling Layers</strong>: Reduce the dimensionality of the data, making computations more efficient.</li><li><strong>Feature Detection</strong>: CNNs are excellent at detecting patterns, edges, and textures in images.</li></ul><h3>How CNN Works:</h3><ol><li><strong>Input</strong> (usually an image) is passed through a series of <strong>convolutional layers</strong>.</li><li><strong>Pooling layers</strong> downsample the data to reduce complexity.</li><li>The final fully connected layers generate the <strong>output</strong> (e.g., label or class of an image).</li></ol><h4>When to Use CNN:</h4><ul><li>Ideal for tasks related to <strong>image recognition</strong> and <strong>computer vision</strong> (e.g., facial recognition, object detection).</li></ul><h3>Understanding Convolutional Neural Networks for Image Classification</h3><p>Convolutional Neural Networks (CNNs) are designed to process and classify visual data, making them ideal for tasks like object detection and image classification. They extract hierarchical features such as edges, textures, and shapes, enabling effective recognition of complex patterns.</p><p><strong>Model Architecture</strong><br>A typical CNN model for classifying cats and dogs involves multiple convolutional layers, pooling layers, and fully connected layers. The dog_vs_cat_classifier.h5 model used here captures these features:</p><pre>model = Sequential([<br>    Conv2D(32, (3, 3), activation=&#39;relu&#39;, input_shape=(64, 64, 3)),<br>    MaxPooling2D(pool_size=(2, 2)),<br>    Conv2D(64, (3, 3), activation=&#39;relu&#39;),<br>    MaxPooling2D(pool_size=(2, 2)),<br>    Flatten(),<br>    Dense(128, activation=&#39;relu&#39;),<br>    Dense(1, activation=&#39;sigmoid&#39;)  # Binary classification<br>])</pre><p><strong>How CNNs Work</strong><br>The image is passed through the convolutional layers, where filters detect features like edges or shapes. Pooling layers reduce the spatial dimensions, and fully connected layers perform classification based on the learned features.</p><p><strong>Predicting an Image</strong><br>To predict whether an image is a cat or a dog, the model is loaded, the image is preprocessed (rescaled and reshaped), and a prediction is made:</p><pre># Load and preprocess the image<br>img = load_img(&#39;path_to_image.jpg&#39;, target_size=(64, 64))<br>img_array = img_to_array(img) / 255.0<br>img_array = np.expand_dims(img_array, axis=0)<br><br># Make prediction<br>prediction = model.predict(img_array)<br>label = &#39;Dog&#39; if prediction[0][0] &gt; 0.5 else &#39;Cat&#39;<br>print(f&quot;Predicted: {label}&quot;)</pre><p><strong>Real-World Applications</strong><br>CNNs have broad applications in image recognition, healthcare (e.g., identifying anomalies in scans), and security (e.g., facial recognition). Their ability to extract meaningful patterns from raw image data enables machines to interpret visual information with high accuracy.</p><ul><li>Works well with large datasets where detecting spatial relationships in data is crucial.</li></ul><h3>Recurrent Neural Networks (RNN)</h3><p><strong>Recurrent Neural Networks (RNNs)</strong> are designed for sequential data, such as time series or natural language. Unlike FNNs, RNNs can <strong>retain information</strong> from previous inputs, making them powerful for tasks where context or memory is essential.</p><h3>Key Features of RNN:</h3><ul><li><strong>Loops</strong>: RNNs have loops that allow information to persist across different time steps.</li><li><strong>Memory</strong>: They remember previous inputs, which makes them ideal for handling sequential data.</li><li><strong>Backpropagation Through Time (BPTT)</strong>: A variant of backpropagation used to train RNNs by unrolling them over time.</li></ul><h3>How RNN Works:</h3><ol><li><strong>Input</strong> is fed into the network.</li><li>Hidden layers process the input and retain information about previous inputs through <strong>feedback loops</strong>.</li><li>The <strong>output layer</strong> generates a prediction based on both the current and past inputs.</li></ol><h4>When to Use RNN:</h4><ul><li><strong>Text Processing</strong>: For tasks like machine translation, sentiment analysis, or speech recognition.</li><li><strong>Time Series Prediction</strong>: Useful for forecasting or any task where previous time steps affect the outcome.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3345b73676a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparative Study of Machine Learning Models for Sentiment Analysis: A Case of SVM, Naive Bayes…]]></title>
            <link>https://medium.com/@kisetzuu/comparative-study-of-machine-learning-models-for-sentiment-analysis-a-case-of-svm-naive-bayes-7311aea0f57f?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/7311aea0f57f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 09:31:51 GMT</pubDate>
            <atom:updated>2024-09-11T09:31:51.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparative Study of Machine Learning Models for Sentiment Analysis: A Case of SVM, Naive Bayes, and Logistic Regression</h3><blockquote><strong>“Success in creating effective AI could be the biggest event in the history of our civilization.”</strong> — Stephen Hawking</blockquote><h3>I. Introduction</h3><p>Sentiment analysis is a natural language processing task aimed at classifying the polarity of text into positive or negative sentiments. In this case study, we explore and compare three machine learning models — Random Forest, Support Vector Machine (SVM), and Naive Bayes — on a dataset of IMDB movie reviews. Each model is evaluated based on key performance metrics such as accuracy, precision, recall, and F1-score to identify the most effective model for sentiment classification.</p><h3>II. Dataset Description and Preprocessing</h3><p><strong>Dataset</strong>:</p><ul><li><strong>Source</strong>: IMDB Dataset of 50,000 movie reviews labeled as positive or negative.</li></ul><p><strong>Preprocessing Steps</strong>:</p><ol><li><strong>Text Cleaning</strong>: Reviews were preprocessed to remove HTML tags, non-alphabetic characters, and convert the text to lowercase.</li><li><strong>Feature Extraction</strong>: TF-IDF (Term Frequency-Inverse Document Frequency) vectorization was applied with bigrams. Custom stopwords such as “movie”, “film”, and “story” were removed to improve classification results.</li><li><strong>Label Encoding</strong>: Sentiment labels were encoded as binary (positive → 1, negative → 0).</li></ol><pre>import pandas as pd<br>import re<br>from bs4 import BeautifulSoup<br>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import TfidfVectorizer<br><br># Load dataset<br>file_path = r&quot;C:\path\to\IMDB Dataset.csv&quot;<br>imdb_data = pd.read_csv(file_path)<br><br># Clean text<br>def clean_text(text):<br>    text = BeautifulSoup(text, &quot;html.parser&quot;).get_text()  # Remove HTML tags<br>    text = re.sub(r&quot;[^a-zA-Z]&quot;, &quot; &quot;, text)  # Remove non-letters<br>    return text.lower()<br><br>imdb_data[&#39;clean_review&#39;] = imdb_data[&#39;review&#39;].apply(clean_text)<br><br># Encode sentiment labels<br>imdb_data[&#39;sentiment_label&#39;] = imdb_data[&#39;sentiment&#39;].map({&#39;positive&#39;: 1, &#39;negative&#39;: 0})<br><br># Split into train and test sets<br>X = imdb_data[&#39;clean_review&#39;]<br>y = imdb_data[&#39;sentiment_label&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># TF-IDF Vectorization<br>custom_stop_words = [&quot;movie&quot;, &quot;film&quot;, &quot;story&quot;, &quot;character&quot;, &quot;time&quot;]<br>tfidf_vectorizer = TfidfVectorizer(stop_words=custom_stop_words, max_features=5000, ngram_range=(1, 2), min_df=3, max_df=0.8)<br>X_train_tfidf = tfidf_vectorizer.fit_transform(X_train)<br>X_test_tfidf = tfidf_vectorizer.transform(X_test)</pre><h3>III. Methodology</h3><p>The performance of each algorithm (Random Forest, SVM, and Naive Bayes) is evaluated through the following steps:</p><ol><li><strong>Training and Testing Split</strong>: The dataset was split into training (80%) and testing (20%) sets using the train_test_split function.</li><li><strong>TF-IDF Vectorization</strong>: TF-IDF vectorizer was used to transform the text data into numerical features with a maximum of 5000 features and bigrams.</li><li><strong>Model Training</strong>: Each model was trained on the training set and evaluated on the test set.</li><li><strong>Evaluation Metrics</strong>: Models were evaluated using accuracy, precision, recall, F1-score, and confusion matrices.</li></ol><h3>IV. Model Results</h3><h4>1. Support Vector Machine (SVM)</h4><p><strong>Model Overview</strong>:<br>SVM works by finding a hyperplane that best separates positive and negative classes. For this case, we used a linear kernel, suitable for high-dimensional text data.</p><pre>from sklearn.svm import SVC<br>from sklearn.metrics import classification_report, confusion_matrix<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Train SVM model<br>svm_model = SVC(kernel=&#39;linear&#39;, C=1.0)<br>svm_model.fit(X_train_tfidf, y_train)<br><br># Predict and evaluate<br>y_pred_svm = svm_model.predict(X_test_tfidf)<br>print(&quot;Classification report for SVM:&quot;)<br>print(classification_report(y_test, y_pred_svm))<br><br># Confusion Matrix<br>cm_svm = confusion_matrix(y_test, y_pred_svm)<br>sns.heatmap(cm_svm, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;)<br>plt.title(&#39;Confusion Matrix for SVM&#39;)<br>plt.show()</pre><h4><strong>Performance Results</strong>:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*SEynib_MVJD5hECFUNWEhg.png" /><figcaption>Figure 1: Confusion Matrix for the SVM model showing correct and incorrect predictions for positive and negative sentiments.</figcaption></figure><ul><li>The SVM model correctly predicted <strong>4401</strong> negative and <strong>4559</strong> positive reviews, with <strong>560</strong> false positives and <strong>480</strong> false negatives, demonstrating a balanced performance across both sentiments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*oRhjBL7DDA7Fbee10Iu5HQ.png" /><figcaption>Figure 2: Classification report for the SVM model showing precision, recall, and F1-score.</figcaption></figure><ul><li>The SVM model achieved <strong>90%</strong> for <em>precision</em>, <em>recall</em>, and <em>F1-scores</em> for both positive and negative sentiments, resulting in an overall accuracy of <strong>90%</strong>, indicating robust classification performance.</li></ul><h4>2. Logistic Regression</h4><p><strong>Model Overview</strong>:<br>Logistic Regression predicts class probabilities using a logistic function. It is a common algorithm for binary classification tasks like sentiment analysis.</p><pre>from sklearn.linear_model import LogisticRegression<br><br># Train Logistic Regression model<br>lr_model = LogisticRegression(max_iter=1000)<br>lr_model.fit(X_train_tfidf, y_train)<br><br># Predict and evaluate<br>y_pred_lr = lr_model.predict(X_test_tfidf)<br>print(&quot;Classification report for Logistic Regression:&quot;)<br>print(classification_report(y_test, y_pred_lr))<br><br># Confusion Matrix<br>cm_lr = confusion_matrix(y_test, y_pred_lr)<br>sns.heatmap(cm_lr, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;)<br>plt.title(&#39;Confusion Matrix for Logistic Regression&#39;)<br>plt.show()<br><br># Visualize top words (positive and negative)<br>import numpy as np<br><br>coef = lr_model.coef_[0]<br>feature_names = np.array(tfidf_vectorizer.get_feature_names_out())<br>top_positive_indices = coef.argsort()[-10:]  # Top 10 positive words<br>top_negative_indices = coef.argsort()[:10]  # Top 10 negative words<br><br>top_positive_words = feature_names[top_positive_indices]<br>top_negative_words = feature_names[top_negative_indices]<br><br>plt.figure(figsize=(12, 6))<br>plt.subplot(1, 2, 1)<br>plt.barh(top_positive_words, coef[top_positive_indices], color=&#39;green&#39;)<br>plt.title(&#39;Top 10 Positive Words (Logistic Regression)&#39;)<br><br>plt.subplot(1, 2, 2)<br>plt.barh(top_negative_words, coef[top_negative_indices], color=&#39;red&#39;)<br>plt.title(&#39;Top 10 Negative Words (Logistic Regression)&#39;)<br>plt.tight_layout()<br>plt.show()</pre><h4><strong>Performance Results</strong>:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*t76NoBlZCMvBtkjXWk3ezw.png" /><figcaption>Figure 1: Confusion Matrix for the Logistic Regression model showing correct and incorrect predictions for positive and negative sentiments.</figcaption></figure><ul><li>The Logistic Regression model correctly predicted <strong>4400</strong> negative and <strong>4579</strong> positive reviews, with <strong>561</strong> false positives and <strong>460</strong> false negatives, reflecting a balanced classification of sentiments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*j4zAWuBjzYS9DBL_5gAu9g.png" /><figcaption>Figure 2: Classification report for the Logistic Regression model showing precision, recall, and F1-score.</figcaption></figure><ul><li>The model achieved <strong>91% precision</strong> for negative sentiment and <strong>89% precision</strong> for positive sentiment. The overall accuracy was <strong>90%</strong>, demonstrating consistent performance in both sentiment classifications.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBqPNUPzvI_5IQKZcdolgQ.png" /><figcaption>Figure 3: Top 10 words with the strongest positive and negative weights in the Logistic Regression model.</figcaption></figure><ul><li>Words like “<strong>great</strong>”, “<strong>excellent</strong>”, and “<strong>wonderful</strong>” have the highest positive weights, strongly predicting positive sentiment. On the other hand, words like “<strong>worst</strong>”, “<strong>awful</strong>”, and “<strong>bad</strong>” have the strongest negative weights, influencing negative sentiment predictions. These terms play a crucial role in the model’s decision-making process for sentiment classification.</li></ul><h4>3. Naive Bayes</h4><p><strong>Model Overview</strong>:<br>Naive Bayes is a probabilistic classifier based on Bayes’ theorem, with strong (naive) independence assumptions between features.</p><p><strong>Laplace Smoothing (Alpha) Tuning</strong>:<br>Different alpha values were tested to identify the best performing smoothing parameter. The plot below shows the effect of alpha on model accuracy:</p><pre>from sklearn.naive_bayes import MultinomialNB<br><br># Train Naive Bayes model (Alpha = 2.0)<br>nb_model = MultinomialNB(alpha=2.0)<br>nb_model.fit(X_train_tfidf, y_train)<br><br># Predict and evaluate<br>y_pred_nb = nb_model.predict(X_test_tfidf)<br>print(&quot;Classification report for Naive Bayes:&quot;)<br>print(classification_report(y_test, y_pred_nb))<br><br># Confusion Matrix<br>cm_nb = confusion_matrix(y_test, y_pred_nb)<br>sns.heatmap(cm_nb, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;)<br>plt.title(&#39;Confusion Matrix for Naive Bayes&#39;)<br>plt.show()<br><br># Visualize effect of Laplace Smoothing<br>alphas = [0.1, 0.5, 1.0, 2.0, 5.0]<br>scores = []<br><br>for alpha in alphas:<br>    nb = MultinomialNB(alpha=alpha)<br>    nb.fit(X_train_tfidf, y_train)<br>    scores.append(nb.score(X_test_tfidf, y_test))<br><br>plt.plot(alphas, scores, marker=&#39;o&#39;)<br>plt.title(&#39;Effect of Laplace Smoothing on Naive Bayes Accuracy&#39;)<br>plt.xlabel(&#39;Alpha&#39;)<br>plt.ylabel(&#39;Accuracy&#39;)<br>plt.grid(True)<br>plt.show()</pre><h4><strong>Performance Results</strong>:</h4><ul><li><strong>Confusion Matrix for Naive Bayes with Alpha = 2.0</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*wxOBiYae9tXEcdaztLuxRA.png" /><figcaption>Figure 1: The effect of different Laplace Smoothing (Alpha) values on the accuracy of the Naive Bayes model.</figcaption></figure><ul><li>This plot shows that as the <strong>alpha</strong> value increases, the <strong>accuracy</strong> of the Naive Bayes model decreases slightly. The model achieves the highest accuracy around an alpha value of <strong>0</strong> or <strong>0.5</strong>, with a decline as alpha increases further.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*1LYfOtd3bu12W4zgdyTPhg.png" /><figcaption>Figure 2: Classification report for Naive Bayes with Alpha = 2.0, showing precision, recall, and F1-score.</figcaption></figure><ul><li>With <strong>Alpha = 2.0</strong>, the Naive Bayes model achieved an overall accuracy of <strong>86%</strong>, with <strong>87% precision</strong> for negative sentiment and <strong>86% precision</strong> for positive sentiment. The model’s balanced performance is reflected in its F1-scores, making it a reliable classifier despite its simplicity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*0c9yf-_b2RN1i3ETmCuufQ.png" /><figcaption>Figure 3: Confusion matrix for the Naive Bayes model using Alpha = 2.0, showing the true positive and negative classifications along with the errors.</figcaption></figure><ul><li>The Naive Bayes model correctly classified <strong>4231</strong> negative and <strong>4387</strong> positive reviews. There were <strong>730</strong> false positives and <strong>652</strong> false negatives, indicating that the model tends to misclassify some reviews, but overall performs well with a balanced number of true positives and true negatives.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tD5yd9AEtkwUypx9RLdC3w.png" /><figcaption>Figure 4: The top 10 words for positive and negative sentiment based on log probability in the Naive Bayes model.</figcaption></figure><ul><li>The Naive Bayes model assigns high importance to common words like “<strong>was</strong>” and “<strong>as</strong>” for both positive and negative sentiments, reflecting the model’s reliance on word frequency rather than meaning. This highlights the limitations of Naive Bayes when dealing with more nuanced language structures.</li></ul><h3>V. Discussion and Comparison</h3><p><strong>Accuracy</strong>:</p><ul><li>SVM and Logistic Regression achieved the highest accuracy at 90%, while Naive Bayes performed slightly lower at 86%.</li></ul><p><strong>Precision and Recall</strong>:</p><ul><li>All models achieved balanced precision and recall. However, SVM and Logistic Regression were slightly better at minimizing both false positives and false negatives compared to Naive Bayes.</li></ul><p><strong>Model Strengths and Weaknesses</strong>:</p><ul><li><strong>SVM</strong>: Strong performance, especially on high-dimensional text data. However, it is computationally expensive compared to Naive Bayes.</li><li><strong>Logistic Regression</strong>: Provides explainable coefficients (weights) and performed well across metrics.</li><li><strong>Naive Bayes</strong>: Simple and fast but makes strong independence assumptions, which limits performance on complex data.</li></ul><h3>VI. Conclusion</h3><p>Based on the comparative study:</p><ul><li><strong>SVM</strong> and <strong>Logistic Regression</strong> emerged as the best models for sentiment analysis on this dataset, both achieving an accuracy of 90%.</li><li><strong>Naive Bayes</strong>, though not as strong as the other two, still performed reasonably well with 86% accuracy, making it a viable option when computational efficiency is important.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7311aea0f57f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning for Fraud Detection: Using Random Forests and Synthetic Minority Over-sampling…]]></title>
            <link>https://medium.com/@kisetzuu/machine-learning-for-fraud-detection-using-random-forests-and-synthetic-minority-over-sampling-629cf7e74671?source=rss-3a169225c550------2</link>
            <guid isPermaLink="false">https://medium.com/p/629cf7e74671</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[credit-cards]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Keith Chadberc Niven Villanueva]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 10:39:35 GMT</pubDate>
            <atom:updated>2024-08-30T06:28:45.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning for Fraud Detection: Using Random Forests and Synthetic Minority Over-sampling (SMOTE) in Credit Card Transactions</h3><blockquote>“AI will be a driving force for economic growth and innovation in the coming decades.”<br> — Erik Brynjolfsson</blockquote><h3>I. Introduction</h3><p>Credit card fraud detection is a critical challenge for financial institutions due to the substantial financial losses and reputational damage that can arise from fraudulent transactions. The increasing reliance on digital payments and the rapid growth in transaction volumes have made detecting fraudulent activities more complex than ever. Moreover, as fraudsters continue to develop more sophisticated techniques, there is a growing need for advanced models that can reliably distinguish between legitimate and fraudulent transactions.</p><p>This case study investigates the application of <strong>Random Forests</strong>, a powerful and versatile ensemble learning method, to enhance fraud detection efforts. To address the significant class imbalance typically found in fraud detection datasets, we also utilize <strong>SMOTE</strong> (Synthetic Minority Over-sampling Technique). By integrating these methods, we aim to develop a robust model that not only accurately identifies fraudulent transactions but also minimizes false positives, ultimately safeguarding both financial institutions and their customers.</p><h3>II. Objective</h3><p>The objective of this case study is to develop a machine learning model capable of accurately detecting fraudulent credit card transactions. The model aims to achieve two primary goals: maximizing the detection rate of fraudulent transactions (high <strong>recall</strong>) and minimizing the false alarm rate (high <strong>precision</strong>). To accomplish this, the study leverages <strong>Random Forests</strong> for their ability to handle complex and high-dimensional datasets effectively. Additionally, <strong>SMOTE</strong> (Synthetic Minority Over-sampling Technique) is utilized to address the significant <strong>class imbalance</strong> often found in fraud detection scenarios. By combining these techniques, the study seeks to enhance the model’s effectiveness, ensuring a balanced and robust approach to fraud detection that safeguards both financial institutions and their customers while minimizing the impact of false positives.</p><h3>III. Dataset</h3><p>The dataset used in this study is sourced from <a href="https://www.kaggle.com/">Kaggle</a>, which contains transactional data from a financial institution. The dataset includes 1,066 features such as transaction amounts, merchant details, customer geolocation, and timestamps. The target variable, is_fraud, indicates whether a transaction is fraudulent (1) or not (0). Given the sensitive nature of the data, all entries have been anonymized to protect customer privacy.</p><p>Initial preprocessing steps involved filtering out invalid entries in the is_fraud column and converting this target variable to an integer format. Additionally, the dataset was enriched by extracting temporal features from the transaction timestamps and one-hot encoding categorical features like merchant type and job title.</p><h3>IV. Data Preprocessing</h3><p>Data preprocessing is a crucial step to ensure that the dataset is in the optimal format for model training. For this study, several preprocessing steps were undertaken:</p><ol><li><strong>Datetime Features Extraction</strong>: The trans_date_trans_time feature was converted into a datetime object to extract useful temporal components such as year, month, day, hour, and minute.</li><li><strong>Feature Encoding</strong>: Categorical features, such as merchant, category, city, state, and job, were one-hot encoded to convert them into a numerical format suitable for machine learning algorithms.</li><li><strong>Data Cleaning</strong>: Unnecessary columns, including trans_date_trans_time, dob, and trans_num, were dropped to reduce noise and focus on the most relevant features.</li></ol><pre># Preprocessing<br>df[&#39;trans_date_trans_time&#39;] = pd.to_datetime(df[&#39;trans_date_trans_time&#39;], dayfirst=True)<br><br># Extract datetime features<br>df[&#39;year&#39;] = df[&#39;trans_date_trans_time&#39;].dt.year<br>df[&#39;month&#39;] = df[&#39;trans_date_trans_time&#39;].dt.month<br>df[&#39;day&#39;] = df[&#39;trans_date_trans_time&#39;].dt.day<br>df[&#39;hour&#39;] = df[&#39;trans_date_trans_time&#39;].dt.hour<br>df[&#39;minute&#39;] = df[&#39;trans_date_trans_time&#39;].dt.minute</pre><h3>V. Handling Imbalanced Data with SMOTE</h3><p>Credit card fraud detection is often challenged by a significant class imbalance, where fraudulent transactions constitute a small minority of all transactions. This imbalance can bias models towards predicting the majority class (non-fraudulent transactions), leading to poor detection rates for fraud.</p><p>To address this issue, the <strong>Synthetic Minority Over-sampling Technique (SMOTE)</strong> was applied to the training data. SMOTE generates synthetic samples for the minority class by interpolating between existing samples, effectively balancing the dataset and allowing the model to learn better from the fraud cases.</p><pre># Define the steps of the imbalanced-learn pipeline<br>pipeline = Pipeline([<br>    (&#39;smote&#39;, SMOTE(random_state=42)), <br>    (&#39;scaler&#39;, StandardScaler()), <br>    (&#39;classifier&#39;, RandomForestClassifier(random_state=42))<br>])</pre><h3>VI. Model Development with Random Forests</h3><p>Random Forests were selected as the primary modeling technique due to their robustness and ability to handle high-dimensional data. This ensemble method combines multiple decision trees to improve prediction accuracy and control overfitting. <strong>GridSearchCV</strong> was used to fine-tune hyperparameters such as the number of trees (n_estimators), maximum tree depth (max_depth), and minimum samples required to split a node (min_samples_split).</p><p>The optimal parameters were determined through an exhaustive search across specified ranges, ensuring that the model’s performance was maximized on the validation data.</p><pre># Define the parameter grid for GridSearchCV<br>param_grid = {<br>    &#39;classifier__n_estimators&#39;: [50, 100, 200],<br>    &#39;classifier__max_depth&#39;: [5, 10, 15],<br>    &#39;classifier__min_samples_split&#39;: [2, 5, 10],<br>    &#39;classifier__min_samples_leaf&#39;: [1, 2, 4],<br>    &#39;classifier__max_features&#39;: [&#39;sqrt&#39;, &#39;log2&#39;, None]<br>}<br><br># Initialize GridSearchCV<br>grid_search = GridSearchCV(pipeline, param_grid, cv=cv, scoring=scoring, n_jobs=-1, verbose=2)<br><br># Fit GridSearchCV<br>grid_search.fit(X_train, y_train)<br><br># Best parameters and best score<br>print(f&#39;Best parameters found: {grid_search.best_params_}&#39;)<br>print(f&#39;Best cross-validation ROC AUC score: {grid_search.best_score_:.2f}&#39;)</pre><h3>VII. Model Evaluation</h3><p>The model’s performance was evaluated using several metrics, including <strong>accuracy</strong>, <strong>precision</strong>, <strong>recall</strong>, <strong>F1-score</strong>, and <strong>AUC (Area Under the Curve)</strong>. These metrics provide a comprehensive view of the model’s ability to detect fraud while minimizing false positives.</p><p>The test set results were highly favorable, with a perfect <strong>ROC AUC score of 1.00</strong>, indicating that the model effectively distinguishes between fraudulent and non-fraudulent transactions.</p><pre># Evaluate the best model on the test set<br>best_model = grid_search.best_estimator_<br>y_pred = best_model.predict(X_test)<br>y_pred_proba = best_model.predict_proba(X_test)[:, 1]<br><br># Confusion matrix for test set<br>cm = confusion_matrix(y_test, y_pred)<br>print(&quot;Test Set Confusion Matrix:\n&quot;, cm)<br><br># Classification report for test set<br>print(&quot;Test Set Classification Report:\n&quot;, classification_report(y_test, y_pred))<br><br># ROC AUC score for test set<br>roc_auc = roc_auc_score(y_test, y_pred_proba)<br>print(f&#39;Test Set ROC AUC Score: {roc_auc:.2f}&#39;)<br><br># Precision-Recall curve and AUC for test set<br>precision, recall, _ = precision_recall_curve(y_test, y_pred_proba)<br>pr_auc = auc(recall, precision)<br>print(f&#39;Test Set Precision-Recall AUC: {pr_auc:.2f}&#39;)</pre><h3>VIII. Visualization and Interpretation</h3><p>To gain a deeper understanding of the model’s performance, several visualizations were generated, including the confusion matrix, ROC curve, and precision-recall curve. These visual tools help illustrate how well the model distinguishes between fraudulent and non-fraudulent transactions and provides insights into its decision-making process.</p><h4>Confusion Matrix</h4><p>The confusion matrix (Figure 1) shows the breakdown of correctly and incorrectly classified transactions. The model correctly identified <strong>2,510 non-fraudulent transactions</strong> and <strong>365 fraudulent transactions</strong>. It misclassified <strong>10 non-fraudulent transactions</strong> as fraudulent (false positives) and <strong>4 fraudulent transactions</strong> as non-fraudulent (false negatives). This demonstrates a high true positive rate with minimal errors, reflecting the model’s effectiveness in detecting fraud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*goDhMHZH69599ky2RGY8Ww.png" /><figcaption>Figure 1: Test Set Confusion Matrix</figcaption></figure><h4>ROC Curve</h4><p>The ROC curve (Figure 2) illustrates the model’s ability to discriminate between positive (fraudulent) and negative (non-fraudulent) classes at various threshold settings. The <strong>Area Under the Curve (AUC)</strong> is a perfect <strong>1.00</strong>, indicating excellent model performance across all thresholds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*L24ayVMWx_Dm7kXyO9AmMg.png" /><figcaption>Figure 2: Receiver Operating Characteristic (ROC) Curve</figcaption></figure><h4><strong>Precision-Recall Curve</strong></h4><p>The precision-recall curve (Figure 3) further demonstrates the model’s robustness, particularly in handling imbalanced datasets where the minority class (fraudulent transactions) is of greater interest. The high <strong>Area Under the Precision-Recall Curve (AUC = 1.00)</strong> confirms the model’s precision in identifying true positives while minimizing false positives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*p_vo9PnhS43Xto9UHkJjXw.png" /><figcaption>Figure 3: Precision-Recall Curve</figcaption></figure><h4><strong>Classification Report</strong></h4><p>The classification report (Figure 4) provides a detailed breakdown of the model’s performance across different metrics. The model achieved a <strong>precision of 0.97</strong> and a <strong>recall of 0.99</strong> for the fraudulent class, resulting in an <strong>F1-score of 0.98</strong>. The weighted average metrics for all classes are equally high, highlighting the model’s overall accuracy and balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*7VXYkJhcKseB5wF0LJ6m4g.png" /><figcaption>Figure 4: Test Set Classification Report</figcaption></figure><h3>Conclusion of Visualizations and Metrics</h3><p>The visualizations and performance metrics demonstrate that the <strong>Random Forest model</strong>, enhanced with <strong>SMOTE</strong> for handling class imbalance, is highly effective in detecting fraudulent credit card transactions. With a perfect <strong>ROC AUC</strong> and <strong>Precision-Recall AUC</strong> score, the model shows excellent discrimination capability and reliability, making it a robust tool for real-world fraud detection scenarios.</p><pre># Visualization: Confusion Matrix for test set<br>plt.figure(figsize=(6, 4))<br>sns.heatmap(cm, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;, xticklabels=[&#39;Not Fraud&#39;, &#39;Fraud&#39;], yticklabels=[&#39;Not Fraud&#39;, &#39;Fraud&#39;])<br>plt.xlabel(&#39;Predicted&#39;)<br>plt.ylabel(&#39;Actual&#39;)<br>plt.title(&#39;Test Set Confusion Matrix&#39;)<br>plt.show()<br><br># Visualization: ROC Curve for test set<br>fpr, tpr, _ = roc_curve(y_test, y_pred_proba)<br>plt.figure(figsize=(8, 6))<br>plt.plot(fpr, tpr, color=&#39;darkorange&#39;, lw=2, label=f&#39;Test ROC curve (AUC = {roc_auc:.2f})&#39;)<br>plt.plot([0, 1], [0, 1], color=&#39;navy&#39;, lw=2, linestyle=&#39;--&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.title(&#39;Receiver Operating Characteristic (ROC) Curve&#39;)<br>plt.legend(loc=&quot;lower right&quot;)<br>plt.show()<br><br># Visualization: Precision-Recall Curve for test set<br>plt.figure(figsize=(8, 6))<br>plt.plot(recall, precision, color=&#39;blue&#39;, lw=2, label=f&#39;Test Precision-Recall curve (AUC = {pr_auc:.2f})&#39;)<br>plt.xlabel(&#39;Recall&#39;)<br>plt.ylabel(&#39;Precision&#39;)<br>plt.title(&#39;Precision-Recall Curve&#39;)<br>plt.legend(loc=&quot;lower left&quot;)<br>plt.show()</pre><h3>IV. Conclusion and Future Work</h3><p>In conclusion, the <strong>Random Forest model</strong>, enhanced with <strong>SMOTE</strong> for handling class imbalance, successfully detected fraudulent transactions with high accuracy and minimal false positives. These results demonstrate the effectiveness of the chosen techniques in addressing the challenges of credit card fraud detection. Future work could involve exploring more advanced algorithms, such as deep learning, or integrating additional contextual features to further enhance the model’s predictive power.</p><ul><li><strong>Feature Extraction:</strong> Extracted relevant temporal features from the trans_date_trans_time field, such as year, month, day, hour, and minute.</li><li><strong>Dropping Irrelevant Columns:</strong> Removed columns like trans_date_trans_time, dob, and trans_num that do not contribute to fraud detection.</li><li><strong>One-Hot Encoding:</strong> Transformed categorical variables (e.g., merchant, category, city, state, job) into numeric format using one-hot encoding.</li><li><strong>Data Type Conversion:</strong> Ensured all features were in a numeric format suitable for model training.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=629cf7e74671" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>