<?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 Bikram Baruah on Medium]]></title>
        <description><![CDATA[Stories by Bikram Baruah on Medium]]></description>
        <link>https://medium.com/@baruahbikram05?source=rss-613e0875cc8d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QpbotyWXxtXarKm8ugtmfQ.jpeg</url>
            <title>Stories by Bikram Baruah on Medium</title>
            <link>https://medium.com/@baruahbikram05?source=rss-613e0875cc8d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:55:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baruahbikram05/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[ChatFactory: Transforming Manufacturing Insights Beyond the Dashboard]]></title>
            <link>https://baruahbikram05.medium.com/chatfactory-transforming-manufacturing-insights-beyond-the-dashboard-7e3f97203612?source=rss-613e0875cc8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e3f97203612</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[manufacturing]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm-in-manufacturing]]></category>
            <dc:creator><![CDATA[Bikram Baruah]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 09:20:16 GMT</pubDate>
            <atom:updated>2025-03-17T09:20:16.474Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>Dashboards have long been the backbone of data-driven decision-making in organisations across industries. They offer structured visuals, summarising complex data into accessible insights. However, while dashboards are powerful, they also come with significant drawbacks: they are typically rigid, require frequent updates, demand specialised technical knowledge for customisation, and often fail to directly address the nuanced questions users actually have.</p><p>Imagine if interacting with your data was as simple as having a conversation — no need to navigate complex interfaces, memorise precise machine names, or rely on technical teams to build and update numerous custom dashboards. This is exactly where ChatFactory comes in.</p><p>ChatFactory transforms the way users engage with their data by offering intuitive, conversational interactions powered by large language models (LLMs), automated SQL query generation, and Retrieval-Augmented Generation (RAG) for real-time, context-aware insights. With ChatFactory, stakeholders across the organisation, from machine operators to senior management, can ask natural language questions and receive precise, tailored answers instantly.</p><p>In this blog post, we’ll explore how ChatFactory not only simplifies data access but also significantly reduces the overhead of maintaining multiple custom dashboards. We’ll discuss its adaptability across various industries and show how, with just minor adjustments in system prompts, ChatFactory can quickly become a valuable tool tailored specifically to an organisation’s needs.</p><h3>The Problem with Traditional Dashboards:</h3><p>Traditional dashboards, though widely relied upon for operational insights, suffer from inherent limitations that undermine their effectiveness.</p><ul><li><strong>Rigidity and Inflexibility:</strong> Dashboards are typically static, designed for specific purposes, making them difficult and costly to adapt. Any minor change or new features requires additional resources and time. For example, investigating unexpected production issues can become challenging if dashboards aren’t initially configured to display needed metrics, forcing users back to data teams for modifications.</li><li><strong>Complexity and Overload:</strong> In complex industries such as manufacturing, healthcare, or logistics, dashboards often become cluttered with excessive charts and data points, overwhelming users and obscuring critical insights. Non-technical users might struggle to navigate these overloaded interfaces, wasting valuable time and reducing overall efficiency. For instance, a production manager searching for machine downtime metrics might have to navigate multiple dashboards before getting to the information of interest, which can lead to delay in decision-making.</li><li><strong>Poor Adaptability to Diverse Needs:</strong> Different departments or industries often require tailored dashboards, leading to multiple custom-built solutions. Managing these varied dashboards quickly becomes cumbersome and costly. Adapting dashboards across industries — for example, from automotive to pharmaceutical manufacturing — is rarely straightforward, causing duplication of efforts, increased expenses, and reduced responsiveness to changing needs.</li></ul><p>Ultimately, these limitations highlight the crucial need for a more dynamic, intuitive, and flexible way of accessing and interacting with business-critical information. This is exactly the gap that ChatFactory aims to fill, offering a conversational, scalable, and user-friendly alternative to traditional dashboards.</p><h3>Introducing ChatFactory — Conversational Data Insights:</h3><p>ChatFactory transforms the way businesses interact with data by replacing rigid, predefined dashboards with dynamic conversational interactions. At its core, ChatFactory leverages LLMs, enabling users to ask questions naturally and receive precise, actionable insights instantly, without navigating through complex interfaces or memorising specific technical details.</p><p><strong>Conversational Simplicity: </strong>Instead of clicking through countless dashboards, filtering numerous dropdown menus, or memorising exact machine names, users simply ask questions like:</p><ul><li><strong>What was the total downtime of the laser cutter in the last 2 weeks?</strong></li><li><strong>How many units were produced in the last shift?</strong></li><li><strong>How many control valves are left, and where are they?</strong></li></ul><p>ChatFactory intuitively understands these natural language queries, instantly generating SQL queries behind the scenes or retrieving relevant troubleshooting guidance directly from documentation.</p><h4><strong>Powerful Behind-the-Scenes Technology:</strong></h4><p>When users ask data-related questions, ChatFactory dynamically translates their queries into precise SQL statements, executes these against your databases, and seamlessly delivers accurate answers. For more detailed troubleshooting, ChatFactory incorporates Retrieval-Augmented Generation (RAG), automatically extracting information from manuals, PDFs, and user guides. This enables the chatbot to provide instant solutions, maintenance instructions, or diagnostics without users manually searching through documentation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FR2BsVULX-qw&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DR2BsVULX-qw&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FR2BsVULX-qw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb7e585ba9b258fdca37183f1270c7c8/href">https://medium.com/media/bb7e585ba9b258fdca37183f1270c7c8/href</a></iframe><h4><strong>One Solution, Multiple Applications:</strong></h4><p>ChatFactory’s most compelling strength is its adaptability. Changing the type of questions ChatFactory understands, or adapting it to a different industry or customer, can be achieved with an adjustment to its underlying system prompts. Without complex dashboard redesigns or coding new visualisations, businesses can quickly adapt ChatFactory to their evolving requirements:</p><ul><li><strong>Manufacturing:</strong> Instantly track production, downtime, and maintenance.</li><li><strong>Healthcare:</strong> Quickly access patient information or equipment diagnostics.</li><li><strong>Retail &amp; Logistics:</strong> Get immediate inventory insights and track shipments</li></ul><p>ChatFactory is more than just a chatbot — it’s a powerful, flexible, conversational gateway to an organisation’s data, offering simplicity, scalability, and accessibility far beyond traditional dashboards.</p><h3>Beyond Dashboards: Unlocking Flexibility with ChatFactory</h3><p>Dashboards provide key insights but struggle with dynamic, specific queries. However, dashboards often don’t exist for highly specific questions — yet these are exactly the types of inquiries that arise frequently on factory floors, in operations teams, and in maintenance departments.</p><p>For example, answering <strong>“</strong>Which machine was down for the longest in the last two weeks, and how long in total?<strong>”</strong> requires multiple steps:</p><ul><li><strong>Step 1:</strong> Open the machine downtime dashboard and set the date filter to the last two weeks.</li><li><strong>Step 2:</strong> Identify the column displaying downtime durations and sort the data by the longest duration.</li><li><strong>Step 3:</strong> If downtime is logged per event, manually sum the durations for each machine over the two-week period.</li><li><strong>Step 4:</strong> Compare total downtime across all machines to determine which had the longest overall downtime.</li></ul><p>Repeated daily, this process is inefficient and error-prone.</p><p>ChatFactory simplifies this to a single query:<br><strong>User</strong><em>:</em> “Which machine was down for the longest in the last two weeks, and how long in total?”<br><strong>ChatFactory</strong><em>:</em> “The machine that was down for the longest duration in the last two weeks was the Laser Cutter-X5. It was inactive for a total of 631 minutes”</p><p>Another example is inventory management — users typically have to check the current inventory in a database or another system (such as an Excel sheet) and then search for the exact part name or number. With ChatFactory, this process becomes much simpler:</p><p><strong>User:</strong> “How many control valves are left, and where are they?”<br><strong>ChatFactory:</strong> “There are 47 control valves remaining. They are located on Shelf A.”</p><p>By converting natural language into real-time database lookups, ChatFactory delivers instant, precise answers — enhancing dashboards rather than replacing them. It empowers all users, reducing complexity and improving decision-making without technical expertise.</p><h4><strong>No Need to Remember Exact Asset/ Process Names</strong></h4><p>Another major advantage of ChatFactory is its <strong>flexibility in handling asset and process names</strong>. Unlike traditional dashboards or SQL-based reporting systems that require exact spelling or structured input, ChatFactory can understand aliases, abbreviations and synonyms.</p><p>For example, when querying about downtime, the user doesn’t need to specify ‘When was the Laser-Cutter-X500 last down’. Instead, it can simply ask ‘When was the laser cutter last down’.</p><p>This allows users to <strong>ask questions naturally</strong>, without needing to reference specific technical IDs or asset labels. It eliminates friction and makes real-time data retrieval significantly more intuitive.</p><h4><strong>Accessibility — Use ChatFactory from Anywhere</strong></h4><p>Traditional dashboards require users to log into tools such as Grafana, navigate multiple menus, and apply filters to retrieve insights. However, operational teams, factory workers, and field engineers often need real-time answers without sitting at a computer.</p><p>ChatFactory reduces the barrier to getting insights by allowing users to ask questions in plain language without needing to learn tools like Grafana. Additionally, it can enable information access through apps like WhatsApp, making real-time information retrieval effortless, even on the go.</p><h3>Technical Overview — Behind the Scenes</h3><p>At the heart of ChatFactory lies a workflow that integrates LLMs with databases and document retrieval mechanisms. This section covers the fundamental processes that power ChatFactory.</p><h4><strong>Core Components and Workflow:</strong></h4><h4><strong>1. Natural Language Processing with LLMs</strong></h4><p>ChatFactory leverages LLMs like GPT-4 to interpret user queries in everyday language. Instead of memorising database schema or document structures, users can ask clear, conversational questions, and the system dynamically determines the best method to retrieve the required information.</p><h4><strong>2. Automated SQL Query Generation</strong></h4><p>For database-related questions, ChatFactory automatically translates user queries into precise SQL statements. This is achieved through:</p><ul><li>Understanding the database schema, including table names and column definitions.</li><li>Structuring prompts that guide the LLM in generating valid SQL queries.</li></ul><p>For example, if a user asks, <em>“How many parts were produced yesterday?”<br></em> ChatFactory translates it into:</p><pre>SELECT SUM(parts_produced)<br>FROM production_data<br>WHERE production_date = CURRENT_DATE - INTERVAL &#39;1 DAY&#39;;</pre><p>This ensures accurate and optimised query execution, retrieving only the necessary information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*ox2oQ0hb59zz3HSK" /><figcaption>Flowchart to visualise how ChatFactory processes queries</figcaption></figure><h4><strong>3. Retrieval-Augmented Generation (RAG) for Documents</strong></h4><p>For troubleshooting or document-based inquiries, ChatFactory employs RAG. This method:</p><ol><li>Extracts text from PDFs, manuals, or other knowledge sources.</li><li>Chunks and embeds the content using vector-based retrieval.</li><li>Fetches the most relevant document excerpts.</li><li>Uses an LLM to synthesise a clear, contextual answer.</li></ol><p>With RAG, users receive concise, source-backed responses rather than having to search lengthy manuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jot7kZ_EiQA1tLDOklsbAw.png" /><figcaption>Architecture Diagram to illustrate the system architecture</figcaption></figure><h3>Adaptability to Any Industry or Domain</h3><p>ChatFactory is adaptable to diverse industry contexts. Deploying it in new industries requires minimal adjustments — without rewriting core logic. Two key components make this possible:</p><h4><strong>System Prompts</strong></h4><p>The LLM’s behaviour is shaped by clear, domain-specific instructions. To transition from manufacturing to healthcare, you simply modify:</p><ul><li>Table and column definitions.</li><li>Industry-specific terminology.</li></ul><p>For example:</p><ul><li><strong>Manufacturing</strong>: The “machine_status” table tracks machine downtime and the inventory table part count</li><li><strong>Healthcare</strong>: The “patient_records” table contains patient information, diagnosis, and medical history.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*of8hudPXiZtsoGSB" /><figcaption>Example of a system prompt for a manufacturing based use-case for ChatFactory</figcaption></figure><h4><strong>2. Database Configuration File</strong></h4><p>To switch from one organisation to the other, update:</p><ul><li>Database connection parameters (hostname, credentials)</li></ul><p>With these two changes, ChatFactory can seamlessly transition between industries without additional development.</p><p>There are numerous benefits to this approach:</p><ul><li>Minimal overhead — No complex re-engineering required.</li><li>Rapid scalability — Can be applied across multiple industries (manufacturing, logistics, healthcare, retail).</li><li>Easy maintenance &amp; expansion — Additional features can be added via simple configuration changes.</li></ul><h3>Potential Limitations of ChatFactory</h3><p>While ChatFactory offers significant advantages over traditional dashboards, it’s essential to acknowledge and understand some limitations associated with this conversational approach. Recognising these points helps businesses better decide how and when to incorporate this technology effectively:</p><h4>1. Dependency on Accurate System Prompts</h4><ul><li>The effectiveness of ChatFactory heavily depends on the quality and accuracy of the <strong>system prompts</strong>. If the system prompt is unclear or incomplete — such as missing key table or column descriptions — the resulting queries or insights could be inaccurate.</li><li><strong>Mitigation</strong>: Ensuring comprehensive, clear, and accurate system prompts through careful prompt engineering and thorough validation of the database schema descriptions.</li></ul><h4>2. Database Schema Changes</h4><ul><li>If the database schema changes (tables or column names are altered), the ChatFactory system prompt and potentially the database configuration file must be updated promptly, or the tool may produce incorrect results or errors.</li><li><strong>Mitigation</strong>: Maintain clear communication between database administrators and the ChatFactory admin to ensure timely updates when schemas evolve.</li></ul><h4>3. Dependency on LLM Performance</h4><ul><li>The quality of natural language understanding heavily depends on the capabilities of the LLM being used. Complex or highly domain-specific queries might sometimes be misunderstood or require additional clarification.</li><li><strong>Mitigation</strong>: Validate LLM thoroughly to build user trust. Incorporate user feedback loops to continuously improve accuracy</li></ul><h4>4. Dependency on Documentation Quality (for RAG)</h4><ul><li>The accuracy and helpfulness of troubleshooting via Retrieval-Augmented Generation (RAG) depend directly on the quality and clarity of available PDF documentation or user manuals. Poor documentation leads to ineffective troubleshooting responses.</li><li><strong>Mitigation:</strong> Regularly update and maintain clear, structured, and comprehensive documentation. Employ document quality checks and encourage feedback from users.</li></ul><h4><strong>5. Interpretability and Trust</strong></h4><ul><li>Users accustomed to visual dashboards might initially question the accuracy of insights delivered conversationally, as traditional dashboards offer a tangible sense of control through visual verification of data.</li><li><strong>Mitigation</strong>: Integrate a verification feature where users can optionally view the generated SQL queries or data sources for transparency and trust-building. Additionally, train users to understand system limitations, and interpret responses accurately, ensuring they can use ChatFactory with confidence.</li></ul><h4>6. Data Availability and Completeness</h4><ul><li>ChatFactory relies entirely on existing data within the database to generate insights. However, in many organisations, especially those transitioning from manual processes or legacy systems, critical data may not be systematically recorded or stored in a structured format. This creates a fundamental limitation — if the necessary data isn’t captured in the first place, the system cannot provide meaningful responses.</li><li><strong>Mitigation:</strong> Foster a data-driven culture where teams prioritise structured data entry. Automate data collection where possible and establish clear governance policies to maintain consistency. Implement feedback loops to flag missing data and integrate fallback mechanisms to guide users when information is unavailable.</li></ul><h3>Conclusion</h3><p>As businesses strive for agility, speed, and simplicity in how they access data, organisations will look for other ways to interpret data than only from dashboards. While dashboards will continue to hold a valuable place in visualising standardised metrics, they often fall short when flexibility and quick adaptability are required.</p><p>ChatFactory fills precisely this gap — transforming rigid data interactions into natural, intuitive conversations. Its conversational interface not only streamlines the data query process but also removes barriers of technical complexity, <strong>empowering every user</strong> within an organisation to access critical information quickly and effortlessly.</p><p>By leveraging a powerful yet elegant technical foundation that dynamically generates SQL queries and retrieves contextual insights from documentation, ChatFactory is rapidly customisable across various industries. Adapting to a new industry requires minimal changes such as updating system prompts and database configuration files, eliminating the extensive development typically required for custom dashboards.</p><p>Ultimately, ChatFactory doesn’t aim to replace dashboards completely. Instead, it complements and extends them, offering businesses the agility, simplicity, and user-friendliness required to meet the evolving demands of the data-driven future.</p><p><em>The code for the project can be found on this </em><a href="https://github.com/bikramb98/chat-factory"><em>Github repository</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e3f97203612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving from Model-Centric to Data-Centric AI]]></title>
            <link>https://heartbeat.comet.ml/moving-from-model-centric-to-data-centric-ai-6429639903bc?source=rss-613e0875cc8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6429639903bc</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[data-centric-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Bikram Baruah]]></dc:creator>
            <pubDate>Wed, 01 Jun 2022 13:26:21 GMT</pubDate>
            <atom:updated>2022-06-01T13:26:21.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqfRuIleu4CfJ2cEDzHNYg.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/qwtCeJ5cLYs">Unsplash</a></figcaption></figure><h3>Introduction:</h3><p>AI is a rapidly evolving field and up until a few years ago there were distinct model architectures for different tasks, for example, CNN was the go-to for vision tasks and LSTM like networks for language tasks. Then, with the invention of the Transformer architecture and subsequent development in just the past 2–3 years, these tasks are now handled very well by a single architecture with some tweaks for the different use-cases. Newer, bigger models are being released every few months that beat state-of-the-art models in accuracy by some percent.</p><p>When developing AI solutions in practice, it is easy to get caught up in the land of searching for the better architecture, bigger pre-trained models or the best set of hyperparameters with the goal of achieving slightly higher accuracy. This is how the community has looked since the mid 2000s, however, in early 2021, a movement led by Andrew Ng shifted how practitioners think about improving their models. While research in model and architecture development is still going on (for all the right reasons) a new way of model development called data-centric AI is coming into play.</p><h3>Data-Centric AI:</h3><p>What is data-centric AI and how does it differ from model-centric AI? Model-centric AI development is what the industry has been traditionally doing. Have a fixed dataset, train a model, evaluate that model on a holdout-test set and then tweak the hyperparameters or change the model to get better results, and continue doing so until the desired metrics are achieved.</p><p>The data-centric approach varies in one key concept: Hold the model and hyperparameters fixed and apply error analysis driven data iteration to improve model performance. A very important point to note:<strong> Error analysis driven data iteration</strong>. This means analyzing the errors on various classes and samples and letting that guide future processes such as data acquisition, collection, and augmentation. This also helps improve the model performance with a strategy in place instead of randomly collecting more data, augmenting certain classes, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*g2NevrI5sBbx5xIE0-CRJw.png" /><figcaption>Data-Centric AI iteration loop. Source: <a href="https://www.coursera.org/learn/introduction-to-machine-learning-in-production">deeplearning.ai</a></figcaption></figure><p>But why move from the current model-centric approach which has worked so well? The answer is simple: Because in ML/AI, data is code. Data defines how our model performs, and by doing so, it takes on the role of code. What you feed into the model dictates its future behavior. Using the model-centric approach hits a performance ceiling, and then the results can be improved vastly by taking a more data-centric approach. Remember, garbage in = garbage out. This slide from <a href="https://www.coursera.org/specializations/machine-learning-engineering-for-production-mlops?utm_source=gg&amp;utm_medium=sem&amp;utm_campaign=28-MLOps-DL.ai-US&amp;utm_content=B2C&amp;campaignid=13572037851&amp;adgroupid=120618068101&amp;device=c&amp;keyword=andrew%20ng%20education&amp;matchtype=b&amp;network=g&amp;devicemodel=&amp;adpostion=&amp;creativeid=528598123150&amp;hide_mobile_promo&amp;gclid=CjwKCAjw4ayUBhA4EiwATWyBrpURdrxgppoo4EKalwARuig55VGf6cwyIFIVTWqPULJrnbQciq0I7xoCxRoQAvD_BwE">Andrew Ng’s course</a> shows how the performance of a model can improve in orders of magnitude by taking a data-centric approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*6dalVAk9sDkCjYU2u8qTeA.png" /><figcaption>Performance improvement using data-centric approach. Source: <a href="https://www.coursera.org/learn/introduction-to-machine-learning-in-production">deeplearning.ai</a></figcaption></figure><blockquote>Remember, data is code.</blockquote><h3><strong>Steps for data-centric model development approach:</strong></h3><p>How do you start taking a data-centric model development approach? It begins during the scoping phase and goes up to the post-deployment stages. Let’s get into the details:</p><h4><strong>1. Scoping and pre-model development:</strong></h4><p><strong>Ensure the right data can be acquired</strong>: Because data is code, it is important that the right data can be collected. It is important to ensure that the data contains the signal we are interested in. For example, if screen scratches on a phone are seen by a human inspector on the shop floor but the same inspector cannot see the scratch on the image captured by the image acquisition device, it might be that the lighting or the camera resolution used to acquire the images needs to change. Good data coverage is also important, such that as many possible cases are covered for the training and testing datasets.</p><p><strong>Establish a Human Level Performance (HLP)</strong>: For unstructured data such as audio and images, establishing HLP will help set a baseline during model iteration and also help drive the error analysis driven data iteration by identifying classes where improvement is possible and will result in the most positive returns.</p><h4>2. <strong>Labeling:</strong></h4><p>Be it model centric development or data centric development, this stage is very important. It is important that labels are consistent and clean and is even more important in cases with small datasets, as noisy data can negatively affect the model’s performance. In order to achieve this, labelers must have a rulebook which they can follow to make sure there are no inconsistencies between different labelers.</p><p>For example, in the image below some labelers might label individual kittens (left hand side), and some might label it as a group (right hand side). Both of them are technically correct, however, we should set up rules in the beginning of the labeling phase to let the labelers know which one is the preferred way. Tools such as <a href="https://landing.ai/platform/">LandingLens </a>can help streamline this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJ4uVBeALBlfj6bTiE32HQ.png" /><figcaption>Multiple labelling methods for a single image. Source: <a href="https://unsplash.com/photos/uePn9YCTCY0">Unsplash</a></figcaption></figure><h4><strong>3. Model development and error analysis driven iteration:</strong></h4><p>Model centric development keeps the dataset fixed, and then iteratively improves the model performance by tuning the hyperparameters or changing the model. Because of this, model development usually takes place after all the data required/possible to collect has been collected.</p><p>Data centric development takes on a different approach: <strong>Start quick and move fast in the initial stages</strong>. Rather than waiting for months and years to collect all the data possible, start with a relatively small dataset and train the model on it as soon as it is of a reasonable size for the architecture used.</p><blockquote>Real world data doesn’t always play nice. <a href="https://info.comet.ml/standardizing-the-experiment-series/">Make sure you’re setting your experiments up for success with our free webinar.</a></blockquote><p>Doing so helps to know whether the right data is being collected, or something in the data acquisition process needs to change. For example, if the lighting condition in a factory means that certain types of scratches on the car cannot be seen in images, this problem would’ve been identified earlier rather than later (waiting a year to collect the data).</p><p>Using tools for data version control such as <a href="https://www.comet.ml/site/">Comet ML </a>and <a href="https://dvc.org/">dvc </a>will help keep track of changes in the dataset over time during the iterative process.</p><p>Once the model is trained, error analysis is then performed on the initial model. This is the most interesting bit about the data-centric approach. <a href="https://medium.com/p/8d35e240d9d3">Error analysis</a>, along with HLP (if available) and importance-metrics, is used to guide the future actions and data collection strategy.</p><p>For example, if the defect detection model isn’t doing well on scratches less than 2 cm on silver colored car doors, that insight can be used to drive the future data collection strategy. Tools such as Comet ML can help identify cases where the model’s performance is not up to the mark.</p><p>The number of samples can be increased by:</p><ul><li>Collecting more data with current data acquisition pipelines.</li><li>Data augmentation.</li><li>Synthetic data generation using packages such as Unity Perception.</li></ul><p>In most modern day deep learning architectures, adding data rarely hurts, especially if a large model is being used. In fact, it usually results in similar classes improving their performance slightly. This means that if it is proving difficult to gather more samples of scratches less than 2 cm on silver colored doors, gathering samples from other similar looking doors (ex: grey doors) with scratches less than 2 cm will likely increase the model’s accuracy for silver colored doors too.</p><p>Prioritizing the improvement of the model’s performance on one class at a time can help focus the resources available. This decision can be taken through various methods, such as:</p><ul><li>Measuring the gap between the model’s performance on a particular class and the HLP (if available) of that class.</li><li>Using a particular class’s misprediction cost (confusion matrix with weights for each pair-wise misprediction).</li><li>Percentage of data of a particular class likely to be encountered during serving.</li><li>Combining the information about gap to HLP and percentage of data (as shown in the figure below).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*9yVsaB789KS-ykwD" /><figcaption>Table to prioritize class wise improvement. Source: Author</figcaption></figure><p>From the table above, it can be seen that focusing on improving the performance on grey cars will provide more value to the business than the other cars. In doing so, the accuracy of other similar classes should increase too.</p><p>Other techniques include testing the latest iteration of the model on samples misclassified by the previous iteration to analyze performance improvement on the latest iteration, and also whether the model training and data collection strategies are working. It will also help identify on which samples different iterations of the models are continuously failing to accurately predict, which might also serve as a guide for future data collection strategies.</p><h4><strong>4. Data monitoring:</strong></h4><p>Once the model is in production, the incoming data needs to be constantly monitored. This is because the real world is ever-evolving, which means data being fed into the model for prediction is constantly evolving. There are usually two kinds of <a href="https://medium.com/cometheartbeat/model-drift-in-ml-how-to-detect-and-overcome-a83c5d45d3f">drifts</a> that happen:</p><p><strong>Data drift:</strong> Change in the distribution of the input X. This can be due to a variety of reasons, such as:</p><ul><li>The voice input differs because different nationalities have started using the NLP system from what it was trained on.</li><li>In the case of a visual inspection system, the camera is knocked off its desired field of view.</li><li>Changes in the website, which now lets the user input negative values compared to only positive values the model was trained on.</li></ul><p><strong>Concept drift:</strong> The mapping from X to y changes. For example, a housing price dataset trained in 2000 probably wouldn’t work well today, as housing prices in most cases have gone up since then. <a href="https://heartbeat.comet.ml/how-to-deal-with-concept-drift-in-production-fabd519744e3">Concept drift</a> usually happens slower than data drift, as human sentiments and behavior rarely changes abruptly. However, events such as COVID-19 can cause a sudden change in concept, such as many more people ordering groceries online than they used to before.</p><p>Both types of drifts are detrimental to a model’s performance. There are various ways these drifts can happen. Therefore, the methods to handle drift vary case-by-case. However, in order to understand that there is data drift, the incoming data during model serving must first be monitored. This can be done in various ways, such as plotting a histogram of the incoming image image pixel values and comparing against a set schema (which can be obtained during training), or in the case of tabular data, calculating the various statistics such as min, max, mean, variance, and range, etc., of the incoming values.</p><p>Tools such as<a href="https://www.comet.ml/site/comet-mpm/"> Comet MPM</a> can help monitor production models and detect concept drifts. This blog by Chip Huyen titled ‘<a href="https://huyenchip.com/2022/02/07/data-distribution-shifts-and-monitoring.html">Data distribution shifts and monitoring</a>’ is a detailed must-read post on how to detect drifts in different cases.</p><p>In some cases, samples suffering from data drift or concept drift will pass right through the monitoring system. For example, a slightly blurry image from the camera because of vibrations in a factory will result in almost the same statistical image properties, which may pass under the data drift detector. This is why it is also important to track the performance of the model.</p><h4><strong>5. Model monitoring and retraining:</strong></h4><p>Model monitoring is the process of monitoring how accurate the model’s prediction is during serving.</p><p>Model monitoring can be done in different ways, either through human-in-the-loop feedback or through automatic feedback systems such as click-through-rate for recommendation systems. Some feedback can be obtained quicker than others.</p><p>A model can degrade in performance either due to concept drift or data drift or a combination of both. When the model performance for real-world inference falls below a set threshold (depending on the use case), it will have to be retrained. There are different techniques for doing so, such as retraining by using the new data on top of the old model (transfer learning), or if the concept change is drastic, then entirely new models will have to be retrained with the new data.</p><p>It is good practice to have systems in place where the correctly and misclassified samples during serving are stored separately, which can later be used for analysis and re-training.</p><p>Once re-trained, the performance of a new model can be assessed by rolling out the model using <a href="https://cloud.google.com/architecture/application-deployment-and-testing-strategies#bluegreen_deployment_pattern">different deployment strategies</a> such as shadow mode, canary deployment or blue-green deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtr3dhpfERc494fowZCNUA.png" /><figcaption>CometML MPM which allows monitoring production models</figcaption></figure><h3><strong>Conclusion:</strong></h3><p>As you’ve seen, taking a data-centric approach to a problem is an iterative process which uses data as your guide.</p><p>Data centric doesn’t only mean using the right high quality data to train your model, but it also means using data to measure the model’s success, perform error analysis driven iteration on that data to improve the model, and maintain the model by monitoring the incoming data and the models performance on it.</p><p>With the development of more developer friendly tools to take a <a href="https://medium.com/p/7a291ef2d508">data-centric approach</a>, such as Comet ML, LandingLens, etc., the data-centric approach for model development will be a great driver for model development and improvement in the future. Think about ways you can implement a more data-centric approach in your current project or future projects, and share your thoughts on this fairly new approach of model development.</p><p><strong>Remember, data is code.</strong></p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.comet.ml/call-for-contributors-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6429639903bc" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/moving-from-model-centric-to-data-centric-ai-6429639903bc">Moving from Model-Centric to Data-Centric AI</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding how to handle Image Data for Computer Vision and Deep Learning problems]]></title>
            <link>https://medium.com/data-science/understanding-how-to-handle-image-data-for-computer-vision-and-deep-learning-problems-f48cdeb98c83?source=rss-613e0875cc8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f48cdeb98c83</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bikram Baruah]]></dc:creator>
            <pubDate>Sun, 30 Jan 2022 17:11:52 GMT</pubDate>
            <atom:updated>2022-01-31T15:15:07.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*GD95PgJmKLeKOFXy" /><figcaption>Image by Bud Helisson from <a href="https://unsplash.com/photos/kqguzgvYrtM">Unsplash</a></figcaption></figure><h3>Introduction:</h3><p>After having worked on multiple computer vision and deep learning projects over the past couple of years, I’ve gathered my thoughts in this blog on how to handle with image data. Almost always it is better to pre-process the data rather than feed it straight to a deep learning model. At times, a deep learning model might not even be required, and a simple classifier might be enough after some processing.</p><p>Maximizing the signal and minimizing the noise in the image makes the problem in hand a lot easier to deal with. Applying filters to enhance the features and making the image more robust to lighting changes, color etc. should be taken into account when building computer vision systems.</p><p>With that in mind, let us explore a few methods that can help solve classical computer vision or image-based deep learning problems. The notebooks that go along with this blog can be found in this <a href="https://github.com/bikramb98/image_processing">repository</a>.</p><h4><strong>1. Go simple before going deep:</strong></h4><p>Before applying the latest and the best deep learning to solve a problem, try classical computer vision techniques. Especially in cases where data might be scarce, as it is in many real world problems.</p><p>Check if calculating the statistical values of the image pixels such as mean, kurtosis, standard deviation results in statistically distinct values for the different classes. A simple classifier such as a SVM, KNN can then be trained on those values to classify between the different classes.</p><h4>2. Increase signal in the image and remove noise:</h4><p>Check if pre-processing techniques enhance the main features of the image and increase the signal to noise ratio before feeding them into a deep learning model. This will help the model achieve better accuracy.</p><ul><li>Use techniques such as thresholding, noise removal techniques such as erosion and dilation, blurring techniques such as Gaussian blur (to smooth out edges) and Median blur (to remove salt and pepper noise)</li><li>Different operators might be useful in a different order for different problems.</li><li>It is common practice to use a particular operator more than once, a few steps after it was first applied, if that results in more enhanced features.</li></ul><p>To help find the best combination of different kernels sizes for filters, thresholding values etc. (the combination of which can run into millions!) which will result in the best possible image, build interactive sliders to help find the ideal range of those values. An example of how this can be done has been given below in Point 3 and in this <a href="https://github.com/bikramb98/image_processing/blob/main/histogram_equalization.ipynb">notebook</a></p><p>After that, try the method described in Point 1 and see if that gives you enough information for your task in hand.</p><h4>3. Histogram equalization</h4><p>Another way of enhancing the features of the image is using histogram equalization. Histogram equalization improves contrast of the image. The aim of histogram equalization is that the most frequent pixel values be evenly spread out and distributed.</p><p>Let us have a look at an example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gh_dPnYevduuhewM" /><figcaption>Image by Joe Decker on <a href="https://www.photocrati.com/the-tuesday-composition-areas-of-low-contrast-negative-space/">Photocrati</a></figcaption></figure><p>As it can be seen, the image above has very low contrast. In cases such as this, it is important that the contrast be improved such that the features of the image are more clearly visible. OpenCV provides two techniques of doing so — Histogram Equalization and Contrast Limited Adaptive Histogram Equalization (CLAHE).</p><p>Applying histogram equalization, the contrast of the image does improve. However, it also increases noise in the image, as it can be in the middle image below.</p><p>This is where CLAHE comes in. Using this method, the image is divided into m x n grids, and then histogram equalization applied onto each of these grids.The ideal clip limit (threshold for contrast) and the tile grid size can be found using interactive sliders as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g1UCu9bRF0CsyxfN" /><figcaption>Interactive sliders to find the best clip and tile value. Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SoSvMC34NPcUoUmI" /><figcaption>From left to right: Original image, Histogram Equalized image, Image post CLAHE. Image by author</figcaption></figure><p>The right image now has enhanced contrast, and the background and foreground trees more visible compared to the original image. The full notebook for histogram equalization and CLAHE is available <a href="https://github.com/bikramb98/image_processing/blob/main/histogram_equalization.ipynb">here</a></p><h4>4. Converting the image to a different color space:</h4><p>Converting the image into a different color space, such as HSV, can often give better information to segment the object, for cases such as object tracking. Typically, the RGB color space isn’t robust to shadows, slight changes in lighting (which influences the color of the object). For tasks such as object tracking using classical computer vision, oftentimes a finely tuned mask in the RGB space will fail later on when being used in a slightly different environment, because of the reasons listed above. Also, once the image is converted to a different space such as HSV, separating the channels often helps in segmenting the area of interest and removing noise. As it can be seen below, the shadow can be removed much easier and the tennis ball segmented once the image has been converted to HSV space and the channels split. The notebook on converting to HSV space and splitting the channels can be found <a href="https://github.com/bikramb98/image_processing/blob/main/hsv_color_space.ipynb">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hK89Nu8JQdqERXPv" /><figcaption>Different color spaces (RGB,HSV) and their components split. Image by author.</figcaption></figure><h4>5. Normalizing the image:</h4><p>In case the images are being fed into a deep learning model, the images must be normalized using techniques such as Batch Normalisation, which will help standardize the inputs to a network. This will help the network learn faster and be more stable. Batch normalization also reduces generalization error at times.</p><h4>6. Making sensible augmentations:</h4><p>When augmenting images, make sure that the augmentation techniques being applied preserve the class of the image and resembles the data encountered in the real world. For example, applying a cropping augmentation to the image of a dog might result in the augmented image not resembling a dog. This can also be true in the case of augmenting using rotation and flipping in some objects. Be very careful while changing the image properties such as color while augmenting. Also, make sure that augmenting the data does not change the label of the image.</p><p>Always check that the augmented images make sense and reflect the real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kGV56HwkA6wpamNC" /><figcaption>Example of how augmentation such as random cropping can lead to corrupted data. Left image by Oscar Sutton from <a href="https://unsplash.com/photos/yihlaRCCvd4">Unsplash</a></figcaption></figure><h4>7. Data leakage between the training and validation set:</h4><p>This one is more for deep learning in general — but making sure that the same images (let’s say the original and the augmented image) are not in both the train and validation set is important. This usually happens when augmentation is performed before a train-validation split. Ignoring this might result in the model metrics giving a false representation of it’s true nature, as it will have learned from very similar images during training that are also present in the validation set.</p><h4>8. Representation of all categories on the test/ validation set:</h4><p>Make sure that the testing and validation set contains examples of all the labels. This will result in model metrics reflecting the true nature of the model</p><p>Take the case of where one of the labels has a significantly lower number of examples. Performing a random train-test split might result in the class with fewer labels not being represented in the validation/ test set at all. Alas, when the trained model is tested, it will not have been tested on that particular class, and the model metrics will not reflect the true nature of its performance. An example of how this can be done is found in this <a href="https://github.com/bikramb98/ai_in_medicine_specialization/blob/main/custom_split.ipynb">notebook</a>.</p><h4>9. Post-processing sanity checks:</h4><p>It is also important to perform some sanity checks once the model has been trained:</p><ul><li>Make sure that the outputs of all the classes in case of a multiclass classifier adds up to 1.</li><li>Make sure that pre-processing applied to the images during the training is also applied when the model is tested or deployed.</li></ul><p>I hope this blogpost gave you some insights into how to deal with image data for classical computer vision or deep learning problems. Let me know if you have any questions or methods you use while going about handling image data. Feel free to connect with me on <a href="https://twitter.com/baruahbikram05">Twitter</a> and <a href="https://www.linkedin.com/in/bikramb/">LinkedIn</a>. If you don’t wanna miss out on future blogposts from me, you can subscribe <a href="https://baruahbikram05.medium.com/subscribe">here</a> to get them delivered straight to your inbox! Thank you for your time and have a wonderful day ahead! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f48cdeb98c83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understanding-how-to-handle-image-data-for-computer-vision-and-deep-learning-problems-f48cdeb98c83">Understanding how to handle Image Data for Computer Vision and Deep Learning problems</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI in Medical Diagnosis — Dealing with Medical Datasets]]></title>
            <link>https://medium.com/data-science/ai-in-medical-diagnosis-dealing-with-medical-datasets-b746e8bda9e5?source=rss-613e0875cc8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b746e8bda9e5</guid>
            <category><![CDATA[medical]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bikram Baruah]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 19:17:36 GMT</pubDate>
            <atom:updated>2021-11-16T05:50:25.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI in Medical Diagnosis — Dealing with Medical Datasets</h3><h4>Deal with medical dataset challenges such as imbalanced datasets, curating the test set to build useful models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMx95xhu55j_HqeU3ev7Vg.jpeg" /><figcaption>Image by National Cancer Institute from <a href="https://unsplash.com/photos/NFvdKIhxYlU">Unsplash</a>.</figcaption></figure><h3><strong>Introduction:</strong></h3><p>This blog post is a part of the series of posts I will be sharing based on my learnings from the AI in Medicine Coursera Specialisation. I recently completed <a href="https://www.coursera.org/learn/ai-for-medical-diagnosis">Part 1: AI in Medical Diagnosis</a>, and I’ve summarised my learnings from Week 1 in this blog post.</p><p>Faster. Smarter. Better. That’s what AI algorithms are becoming day by day. New models are continuously improving what is possible and doing so at a rapid rate. While it is important to use the state-of-the-art model for the problem and know how to effectively tune your hyperparameters, knowing how to deal with the dataset in hand is an equally important skill. <a href="https://docs.google.com/presentation/d/1bwJDRC777rAf00Drthi9yT2c9b0MabWO5ZlksfvFzx8/edit#slide=id.gf171287819_0_2480">The State of AI Report 2021</a> stated how data-centric AI is gaining popularity for all the right reasons. With that in mind, let’s discuss how to handle a medical dataset. Remember the golden rule of ML: Garbage in == Garbage out</p><h3><strong>Challenges in medical datasets:</strong></h3><p>Medical datasets have one big challenge: The scarcity of data. And even more so, scarcity of the data belonging to the ‘disease’ class, which is what we are most interested in predicting using the models we build. Throughout the rest of this blog post, we will be referring to two classes in the dataset: patients with the disease we are interested in predicting will be in the ‘disease’ class, and patients without it will be in the ‘normal’ class.</p><p>The scarcity of data leads to two main challenges: class imbalance and curating the test set. Other domains such as manufacturing can also suffer from the same problems. For example, class imbalance is a classic problem in manufacturing, where the number of defective components is far less than the number of non-defective components.</p><p>Let us discuss them in detail and how to work around those challenges!</p><h3><strong>Class imbalance problem:</strong></h3><p>In a typical medical scenario, when looking at a healthy population, the number of examples of ‘normal’ patients will vastly outnumber the number of patients with a particular disease.</p><p>This is called the Class Imbalance Problem. This leads to a majority of contribution to the model’s loss coming from the ‘normal’ class examples rather than the ‘disease’ class, and results in the algorithm optimising the loss function to predict the ‘normal’ examples better than the ‘disease’ class.</p><p>We can deal with class imbalance in the training set using the techniques below:</p><ol><li><strong>Oversampling the minority class </strong>— In order to balance both the classes, the minority class can be oversampled. This can be done using methods such as SMOTE for tabular data, and image augmentation techniques such as rotation, flipping etc. for image data. While augmenting data, we need to make sure that the label of the augmented data holds true. For example, a chest X-ray flipped horizontally leads to the heart of the patient pointing towards the right, which is a condition called dextrocardia.</li><li><strong>Undersampling the majority class </strong>— This involves removing some of the samples from the majority class, to make the dataset balanced. One of the disadvantages of this method is that valuable data from the majority class could be lost during the data removal process.</li><li><strong>Class weighing</strong> — We can modify the algorithm to make sure it deals well with the skewed dataset. This means we give more weightage to the minority class in the algorithm’s cost function, and this leads to higher penalty to the minority class during the training phase. A simple way to select the class weights is by taking the ratio of the other class to the total number of samples. This leads to the minority class penalty being higher than the majority class.</li></ol><p>Here’s an example below of one of the common ways of class weighing:</p><p>Suppose we have 10 data points, and 8 of them are the normal class (N) and 2 of them are the disease class (D). In order to calculate the weight for the ‘normal’ class (Wn) and weight (Wd) for the ‘disease’ class, we use the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*322TgtAoERCM6gYdmZCY4w.png" /><figcaption>Formula for calculating class penalty multiplier for unbalanced datasets. Image by author.</figcaption></figure><p>It is typically hard to spot problems in models trained on unbalanced datasets using metrics such as accuracy because of the dataset having only a small number of disease class examples. This leads to our second important point we need to consider:</p><h3><strong>Curating the test and validation set:</strong></h3><p>Going back to the problem of unbalanced dataset, we need to make sure that the test set and validation has examples of both the disease and normal class. This is important, and failing to do so will result in model performance metrics that are not a true representation of the model’s performance.</p><p>Let’s walk through a simple example:</p><p>We have a dataset of 100 data points. Only 10 of those data points (10%) belong to the ‘disease’ class. We split the dataset using sklearn’s train_test_split function, with 80% of your data in the training set, and the remaining 20% in the test set. Because this is a random split, it could very well be the case that not a single data point or just a few data points out of the 10 data points belonging to the ‘disease’ class ends up in our test set. Now, after training the model, and evaluating it on the test set, the model’s performance metrics might be very high. But if there is not a good representation of the disease class, these performance metrics will give us a false sense of the model’s actual capability.</p><p>So we need to make sure that the test set has examples of both the ‘disease’ and ‘normal’ class in the correct proportion. This split can vary between use-cases, and sometimes this split can be as high as a 50–50 split. This helps us truly test the trained model and make sure that the model has the ability to predict both the ‘disease’ and the ‘normal’ class.</p><p>Once we have a test set we are satisfied with, we create a validation set using the same distribution (percentage split) as the test set</p><p>There are two methods by which we can curate our test set, based on the distribution of data points of each class we want on the test set:</p><h4>Stratification:</h4><p>If we want equal distribution of the classes in both the training and the test set, we can stratify it. Stratification of the dataset is when we want equal distribution of the classes in both the training and validation set. For example, if a dataset has 20% labels for the ‘disease’ class and 80% of the labels for the normal class, and we want to maintain that ratio after splitting the dataset for training and testing, we can use stratification This can be done simply in sklearn using the parameter stratify when calling train_test_split helper function. I put together a simple <a href="https://github.com/bikramb98/ai_in_medicine_specialization/blob/main/stratification_test.ipynb">Jupyter notebook</a> here to show the differences in the distribution of all the classes in the train vs test set, with and without using stratification.</p><h4>Custom split:</h4><p>If we want a more custom split (for example 40% of class ‘normal’ and 60% of class ‘disease’) in the test set, we’d have to do that manually. Please follow <a href="https://github.com/bikramb98/ai_in_medicine_specialization/blob/main/custom_split.ipynb">this link</a> to the Jupyter Notebook for the detailed code. A code snippet of the function is given below, showing how to do that for a dataset with 3 different classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*CNRQq75R49rfhbxaGddkWQ.png" /><figcaption>Custom split function for 3 different classes. Detailed code in GitHub repository. Image by author.</figcaption></figure><p>Once we have the validation and test dataset with the right percentage splits of our choice, we then go on to create the training set. We have already discussed how to achieve a balanced training dataset.</p><h3>Other important points:</h3><p>Few other points to keep in mind when working with medical data:</p><ol><li><strong>Patient overlap</strong> — It is important to split the dataset by Patient ID rather than splitting by data points/ image. This is to make sure that the model does not learn parts of the data that are not relevant to predicting whether the patient has the disease we are interested in or not. This problem is similar to the data-leakage problem, where the same data exists both in the training and validation set, thus making the results of the validation set less of a true measure of the model’s capacity to predict.</li><li><strong>Reaching consensus among data labellers</strong> — Label consistency must be mainained across the dataset. Different labellers might have different opinions on what the label for a particular data point should be. In case this happens, various other labellers should be consulted and the majority vote be taken as the final decision. Other techniques, such as biopsy to determine the ground truth, can be used, although these tend to be more expensive and time consuming.</li></ol><p>I hope this blog post gave you some insights into how to deal with medical datasets — the same concepts can be applied to domains like manufacturing. Stay tuned for Part 2 of this series, where I’ll talk about the different ways to evaluate a model built for medical diagnosis. Feel free to connect with me on <a href="https://twitter.com/baruahbikram05">Twitter</a> and <a href="https://www.linkedin.com/in/bikramb/">LinkedIn</a>! Have a wonderful day ahead :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b746e8bda9e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ai-in-medical-diagnosis-dealing-with-medical-datasets-b746e8bda9e5">AI in Medical Diagnosis — Dealing with Medical Datasets</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Big Transfer to predict malaria]]></title>
            <link>https://medium.com/data-science/using-big-transfer-to-predict-malaria-9e4d1b1e6f02?source=rss-613e0875cc8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e4d1b1e6f02</guid>
            <category><![CDATA[healthtech]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bikram Baruah]]></dc:creator>
            <pubDate>Thu, 22 Apr 2021 21:50:50 GMT</pubDate>
            <atom:updated>2021-04-24T09:19:06.928Z</atom:updated>
            <content:encoded><![CDATA[<h4>Classifying blood smear slides as uninfected or infected by malaria causing parasite using transfer learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZHMZtnxtOgZijbrbKlExQ.jpeg" /><figcaption>Photo by Pixabay on <a href="https://www.pexels.com/photo/black-white-mosquito-86722/">Pexels</a></figcaption></figure><p>Transfer learning is the process of using knowledge gained in one task to solve a different task. The previously trained model is used as the base, on top of which a layer is added to fine tune the model to solve the new task.</p><p>The main aim of this blog is to give the reader an understanding of what Big Transfer is, and how it can be fine tuned and applied to problems in a completely different domain from the pre-trained models with minimal effort.</p><p>In the <a href="https://arxiv.org/pdf/2101.05913v3.pdf">paper</a> ‘Supervised Transfer Learning at scale for medical imaging’, researchers from Google proved that using Big Transfer (<a href="https://arxiv.org/pdf/1912.11370.pdf">BiT</a>), the accuracy on a variety of medical tasks, such as mammography cancer identification, chest x-ray interpretation, and skin condition classification can be improved. The paper also found that using BiT models, they were able to achieve baseline performance using only 30%-60% of the training data.</p><p>Prior to this, researchers were not clear about how transfer learning on a set of natural images can be applicable to medical images, because of differences in image size, domain differences and the use of local variations in texture in medical images to detect pathologies of interest.</p><p>I came across Mark Rober’s <a href="https://youtu.be/Qf-D1Upn-KU">video</a> on how a team at Stanford has developed a microscope (<a href="https://www.foldscope.com/">Foldscope</a>) and a paper centrifuge (<a href="https://news.stanford.edu/2017/01/10/whirligig-toy-bioengineers-develop-20-cent-hand-powered-blood-centrifuge/">Paperfuge</a>), which costs 68 cents in total and can be used to view slides and detect diseases such as malaria by a trained professional. Although I didn’t manage to get my hands on a dataset of slide images collected from the Foldscope, I found another <a href="https://lhncbc.nlm.nih.gov/LHC-publications/pubs/MalariaDatasets.html">dataset</a> where the slide images are collected by a smartphone attached to a conventional light microscope. This is important, as in poorer communities, where these tests are most needed, the lack of equipment and resources is the main reason why these tests are not easily accessible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*RO5Qw-5osnI2bsMjWH2Rsw.png" /><figcaption>Example of uninfected (left) and parasitized (right) slide from the dataset</figcaption></figure><p>Putting all of this together, and my interest to test how easy it is to fine tune BiT on a medical image dataset, I decided to try Big Transfer on this malaria dataset.</p><p>This blog will give you an idea of how easy it is to fine-tune BiT models on a specific task using BiT-HyperRule, a heuristic to determine all hyperparameters for fine-tuning and achieve great results. BiT-HyperRule is a great starting point, and that’s what I will be going through in this tutorial. I assume that the reader is armed with the basic knowledge about deep learning. You can view the Jupyter Notebook for this tutorial <a href="https://github.com/bikramb98/malaria_classification/blob/main/BiT-HyperRule.ipynb">here</a>.</p><h4>Big Transfer (BiT)</h4><p>The main feature of BiT is that pre-training is scaled up, using large datasets such as ImageNet-21k and JFT-300M. The model used in this tutorial is the BiT-M, which has been pretrained on ImageNet 21k, a dataset which contains 14 million images of 21,843 different classes, and is based on the ResNet-50x1 architecture. There are other variations of BiT available, listed <a href="https://tfhub.dev/google/collections/bit/1">here</a>.</p><p>The advantages of BiT are:</p><ol><li>Applicable on a wide variety of tasks, even those where there is a domain mismatch, such as medical imaging</li><li>Using BiT HyperRule, great results can be achieved, and this can be improved by further tuning of the hyperparameters (more on this below)</li><li>Quick converging of the model.</li></ol><p>With that in mind, let us begin.</p><p>I’d recommend going through the BiT paper found <a href="https://arxiv.org/pdf/1912.11370.pdf">here</a> before going through this tutorial.</p><h4>Data pre processing:</h4><p>The dataset contains 27558 images, with an equal split between uninfected and parasitised slides images. We then split the dataset into 3 different subsets: training set, validation set, and the test set. The training set is used to train the model and then based on the results on the validation set, the best model is chosen. Usually, the model’s hyperparameter would be tuned using the validation set, but because we are using the BiT-HyperRule, we will only use the validation set for selecting the best model. Finally, the test set is used to evaluate the model’s final performance. Note that the test set should be separate and never used for tuning the model.</p><p>In this case, the training set contains 90% of the images, the validation set contains 9% images, and finally the test set contains 1% of the images.</p><pre>train_size = int(0.90 * num_examples)<br>val_size = int(0.09* num_examples)<br>test_size = int(0.01 * num_examples)</pre><pre>full_dataset = ds.shuffle(reshuffle_each_iteration=False, buffer_size=len(ds))<br>train_dataset = full_dataset.take(train_size)<br>test_val_dataset = full_dataset.skip(train_size)<br>val_dataset = test_val_dataset.take(val_size)<br>test_dataset = test_val_dataset.skip(val_size)</pre><h4>Data augmentation and normalisation:</h4><p>Collecting and labelling data is an expensive process. Data augmentation is the method of creating more data with the existing data effortlessly. New images are generated from the existing ones by modifying them, such as rotation, flipping. Other data augmentation method includes techniques like cropping, however, that is not used in this case as it might result in the main feature of the image getting deleted.</p><pre>features[&#39;image&#39;] = tf.image.random_flip_left_right(features[&#39;image&#39;])<br>features[&#39;image&#39;] = tf.image.random_flip_up_down(features[&#39;image&#39;])</pre><p>We also normalised the image data such that the value is between 0–1. This helps to make sure that the data has a similar distribution and hence helps the model converge faster. It also helps improve the stability of the model.</p><pre>features[&#39;image&#39;] = tf.cast(features[&#39;image&#39;], tf.float32) / 255.0</pre><h4>Adding the output layer:</h4><p>Because the BiT model we will be using is a feature extractor, we need to add an output layer, with the number of neurons equal to the number of classes (2 in this case). We then initialise the weights of this layer to 0.</p><pre>class MyBiTModel(tf.keras.Model):<br>  &quot;&quot;&quot;BiT with a new head.&quot;&quot;&quot;</pre><pre>def __init__(self, num_classes, module):<br>    super().__init__()</pre><pre>    self.num_classes = num_classes<br>    <strong>self.head = tf.keras.layers.Dense(num_classes, kernel_initializer=&#39;zeros&#39;)</strong> <br>    self.bit_model = module</pre><h4>Setting hyperparameters using BiT-HyperRule:</h4><ol><li>Batch size: 512</li><li>Learning rate: 0.003</li><li>Schedule length: 500</li><li>Schedule boundaries= 720,1440,2160</li></ol><p>The BiT-HyperRule states that the schedule length for datasets greater with less than 20 k labelled examples should be 500 steps, and those with fewer than 500 k labelled examples should be 10 k steps. Because the number of labelled examples in this problem is 27558, which is just above 20 k labelled examples boundary, I decided to stick to 500 steps.</p><p>The initial learning rate is 0.003 and is decayed by a factor of 10 at steps 720,1440,2160. These steps represent 30%,60% and 90% of the entire training steps</p><p><strong>Early stopping callback to prevent overfitting:</strong></p><p>In order to prevent overfitting, early stopping is used, which is a method to stop training if the metric being monitored does not behave as expected. In this case, if the validation loss does not decrease for 10 epochs in a row, training is stopped and the model weights from the epoch with the least validation loss is restored.</p><pre>es = EarlyStopping(monitor=&#39;val_loss&#39;, mode=&#39;min&#39;, verbose=1, patience=10,restore_best_weights=True)</pre><h4>Optimizer and loss function:</h4><p>The stochastic gradient descent optimiser with momentum is used. The loss function of choice is the Sparse Categorical loss function. This loss function is used when the number of labels is 2 or more, and it expects the class labels to be integers.</p><pre>optimizer = tf.keras.optimizers.SGD(learning_rate=lr_schedule, momentum=0.9)<br>loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)</pre><h4>Training the model:</h4><p>Now is the exciting part, hitting Return + Enter and letting the model train! Go and make yourself a hot drink after this step, you’ve deserved it!</p><pre>model.compile(optimizer=optimizer,loss=loss_fn,metrics=[&#39;accuracy&#39;])</pre><p>In this case, the validation loss does not decrease after epoch 31, and so from epoch 31 is restored and used.</p><p><strong>Pre-train checks:</strong></p><p>Before spending time and resources on training the model on <em>x </em>epochs, it is important to perform certain sanity checks to make sure that the model is performing as expected.</p><p>The most important one is checking whether the output values make sense. In case of a classification model, the summation value of the probabilities should be one.</p><pre>test_logits = model(test_image) #running the model on a test image<br><strong>sum_proba = (np.sum(tf.nn.softmax(test_logits).numpy()[0]))</strong> #summimg the probabilities <br>#sum_proba should be 1. </pre><p><strong>Post-train check:</strong></p><p>It is important that for a particular image, the model output does not change when the image changes slightly, such as being rotated or flipped. This is known as an invariance check. To test this, we augment the images in the test set and check whether the prediction of the model is consistent across all the different variations of a single image.</p><pre>Pseudocode for post-train check: <br>1. Classify image with the trained model <br>2. Augment the image (rotate/ flip) and then classify it again <br>if result from 1 == result from 2:<br>   Model passes post-train check<br>else:<br>   Retrain model such that it is invariant to augmentations which does not change the main features of the image.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*he8cVdFLZy4YXtdTnxOjTQ.png" /><figcaption>Rotated images used for invariance check</figcaption></figure><h4>Evaluating the model:</h4><p>Once training completes, we make sure to fit the model with the weights from the best epoch. In this case, this is the model with the minimum validation loss.</p><pre>model.load_weights(&#39;best_model&#39;)</pre><p>Then, we can proceed to analyse the model by looking at the metrics below:</p><ol><li><strong>Accuracy on the test set</strong>: Using the entire test set of 274 images, we test it’s accuracy. We find that the accuracy is an impressive 97.46%</li></ol><p>2.<strong> Confusion matrix:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*090k68v29IevnEr4Xwr_0w.png" /></figure><p>The confusion matrix allows us to evluate the model in the form of NxN matrix, where N is the number of classes. It gives us a good idea of the models performance and the number of true positives, true negatives, false positives and false negatives. This data can also be used to then re-train the model to improve the results of a specific category. For example, in a healthcare setting, false negatives (patient being identified as healthy when he/she actually has a disease) is more costly than a false positive (patient being detected as having a disease when he/she doesn’t actually doesn’t).</p><p>Here, the number of misclassified examples is 7, with 5 of them being predicted as parasitised falsely. The other 2 images are being predicted to be uinfected when they were actually parasitised images.</p><p><strong>3. ROC-AUC:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*IdUGxwxDHf5A7rUNSdHOKw.png" /></figure><p>The area under the Receivers Operating Characteristic (ROC) curve is a really important measure of the models performance. The extract below is from a great simple explanation of ROC-AUC curve <a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">here</a>: <br>“AUC — ROC curve is a performance measurement for the classification problems at various threshold settings. ROC is a probability curve and AUC represents the degree or measure of separability. It tells how much the model is capable of distinguishing between classes. Higher the AUC, the better the model is at predicting 0s as 0s and 1s as 1s. By analogy, the Higher the AUC, the better the model is at distinguishing between patients with the disease and no disease”</p><h4>Conclusion:</h4><p>Using the BiT-HyperRule results in a model with 96.81% accuracy on the validation set and 97.46% accuracy on test set with a ROC-AUC of 0.99. This shows that BiT performs great in classifying on a medical dataset, even though the images on which it was trained on is quite different in nature.</p><p>One interesting observation is that the validation loss and accuracy flactuates quite heavily in the first few epochs before it starts stabilising.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*8p2oxdgSMPPPGnVOxAvBVA.jpeg" /><figcaption>Validation loss vs epoch plot</figcaption></figure><p>This could be due to the learning rate and the batch size. While experimenting with different hyperparameters, i.e by reducing the batch size to 64 (instead of 512) and lowering the learning rate from 0.003 to 0.0001, it was found that the validation loss follows a decreasing trend and does not flactuate as much as the above graph. However, further experiments need to be performed before any conclusions can be drawn.</p><p>AI can help make the diagnosis of these diseases affordable and more accessible, and when applied at scale, this will have a massive impact. I am optimistic and truly believe AI can truly revolutionise the state of healthcare, particularly in developing and underdeveloped countries, where cheap and easily accessible healthcare is most needed, and where deadly diseases such as malaria still exists.</p><p>Thanks to the researchers at Google who worked on <a href="https://arxiv.org/pdf/1912.11370.pdf">BiT</a>, and also thanks to the authors of the Google Colab <a href="https://colab.research.google.com/github/google-research/big_transfer/blob/master/colabs/big_transfer_tf2.ipynb">Notebook</a> showing how to use BiT.</p><p>The authors of ‘Supervised Transfer Learning at scale for medical imaging’ noted that the models can be further improved by hyperparameter optimisation. In the next blog, I will try improving the models performance by using custom hyperparameters. So stay tuned for Part 2!</p><p><em>Thanks for reading. If you have any questions, comment them down below. Follow me here on Medium to read Part 2 of this blog when it’s out. I am also available on </em><a href="https://www.linkedin.com/in/bikramb/"><em>LinkedIn</em></a><em> and </em><a href="https://twitter.com/baruahbikram05"><em>Twitter</em></a><em>. Hope you have a great day ahead </em>🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e4d1b1e6f02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-big-transfer-to-predict-malaria-9e4d1b1e6f02">Using Big Transfer to predict malaria</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Invasive Ductal Carcinoma using Convolutional Neural Network (CNN) in Keras]]></title>
            <link>https://medium.com/data-science/predicting-invasive-ductal-carcinoma-using-convolutional-neural-network-cnn-in-keras-debb429de9a6?source=rss-613e0875cc8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/debb429de9a6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Bikram Baruah]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 08:06:55 GMT</pubDate>
            <atom:updated>2019-03-04T11:08:58.144Z</atom:updated>
            <content:encoded><![CDATA[<h4>Classifying histopathology slides as malignant or benign using CNN</h4><p>In this blog, we will learn how to use CNN in a real world histopathology dataset. Real-world data requires a lot more preprocessing than standard datasets such as MNIST, and we will go through the process of making the data ready for classification and then use CNN to classify the images. I will also discuss the CNN architecture used and some of the hyperparameters tuned when building the model.</p><p>The different sections of this blog are:</p><ul><li>Introduction</li><li>Understanding the dataset</li><li>Loading the dataset</li><li>Data preprocessing</li><li>Tackling data imbalance by random undersampling</li><li>Model architecture</li><li>Compiling the model</li><li>Data Augmentation</li><li>Training the model</li><li>Making predictions</li><li>Evaluating the models performance</li></ul><p>I assume that the reader knows what convolutional neural networks are and the their basic working mechanism.</p><p>In this blog, we will only discuss the code which is important in the context of deep learning, and also avoid repeated explanation of code used more than once.</p><p>The Github repository for this post can be found <a href="https://github.com/bikramb98/invasive-ductal-carcinoma-cnn/blob/master/Predicting%20Invasive%20Ductal%20Carcinoma%20using%20CNN%20in%20Keras.ipynb">here</a>. I’d suggest you to follow along the Jupyter Notebook while going through this tutorial.</p><h4>Introduction</h4><p>Over the past couple of years, there has been a rise in using deep learning for medical image analysis with increasing success. Deep learning in the field of healthcare is used to identify patterns, classify and segment medical images. As with most image related tasks, convolutional neural networks are used to do this.</p><p>The classification problem tackled here is to classify histopathology slides of Invasive Ductal Carcinoma (IDC) as either malignant or benign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*dD7oWfCLnS8kHPZLqHo5yg.png" /><figcaption>Histopathology slide of a malignant tumour. Image credits: Department of Pathology at Johns Hopkins University</figcaption></figure><p>IDC is a type of breast cancer, where the cancer has spread to the surrounding breast tissue.</p><p>Cancer tumours can be classified into two types: malignant and benign. A benign tumor is one which does not invade its surrounding tissues whereas a malignant tumor is one which may spread to its surrounding tissues or other parts of the body.</p><h4>Understanding the dataset</h4><blockquote>The dataset we will use can be downloaded <a href="http://www.andrewjanowczyk.com/use-case-6-invasive-ductal-carcinoma-idc-segmentation/">here</a>. Scroll down to the Dataset Description section of the page and download the 1.6 GB zip file.</blockquote><p>The dataset consists of 162 whole mount slide images of breast cancer specimens scanned at 40x. From that,277,524 patches of size 50 x 50 were extracted, out of which 198,738 are IDC negative (benign) and 78,786 are IDC positive (malignant).</p><p>Each patch’s file name is of the format:</p><p>u_xX_yY_classC.png → example 10253_idx5_x1351_y1101_class0.png</p><p>Where u is the patient ID (10253_idx5), X is the x-coordinate of where this patch was cropped from, Y is the y-coordinate of where this patch was cropped from, and C indicates the class where 0 is non-IDC (benign) and 1 is IDC (malignant)</p><h4><strong>Loading the dataset:</strong></h4><pre>imagePatches = glob(&#39;C:/Users/asus/Documents/Breast cancer classification/**/*.png&#39;, recursive=True)</pre><pre>patternZero = &#39;*class0.png&#39;<br>patternOne = &#39;*class1.png&#39;</pre><pre>#saves the image file location of all images with file name &#39;class0&#39; classZero = fnmatch.filter(imagePatches, patternZero) </pre><pre>#saves the image file location of all images with file name &#39;class1&#39;<br>classOne = fnmatch.filter(imagePatches, patternOne)</pre><p>The dataset consists of 279 folders, with sub-folders 0 and 1 inside each of the 279 folders. We first create two variables classZero and classOne, which saves the image locations of all class 0 and class 1 images respectively</p><pre>def process_images(lowerIndex,upperIndex):<br>    &quot;&quot;&quot;<br>    Returns two arrays: <br>        x is an array of resized images<br>        y is an array of labels<br>    &quot;&quot;&quot; <br>    height = 50<br>    width = 50<br>    channels = 3<br>    x = [] #list to store image data<br>    y = [] #list to store corresponding class<br>    for img in imagePatches[lowerIndex:upperIndex]:<br>        full_size_image = cv2.imread(img)<br>        image = (cv2.resize(full_size_image, (width,height), interpolation=cv2.INTER_CUBIC))<br>        x.append(image)<br>        if img in classZero:<br>            y.append(0)<br>        elif img in classOne:<br>            y.append(1)<br>        else:<br>            return<br>    return x,y</pre><p>We then create a function <em>process_images</em> which takes as input the starting and end index of the images. This function first reads the image using OpenCV’s cv2.imread() and also resizes the image. Resizing is done because few of the images in the dataset are not 50x50x3. The function returns two arrays: X, which is an array of the resized image data and Y, which is an array of the corresponding labels.</p><pre>X, Y = process_images(0,100000)</pre><p>For this tutorial, we will only analyze images from index 0 to 60,000. The image data (pixel values) are now stored in a list X and their corresponding classes in a list Y.</p><h4><strong>Data preprocessing:</strong></h4><pre>X = np.array(X)<br>X = X.astype(np.float32)<br>X /= 255.</pre><p>The list X is first converted to a numpy array and then casted to the type float32 to save space.</p><p>The images are first normalized by dividing it by 255. This ensures that all the values are between 0 and 1. This helps us to train the model faster and also prevents us from falling into the vanishing and exploding gradients problem.</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.15)</pre><p>The dataset is split into training and test set, with 15% of the entire dataset reserved for testing. For a dataset of 60,000 , this means 51000 images are reserved for training and 9000 for testing.</p><h4>Tackling data imbalance by random undersampling</h4><pre>y_train.count(1)  #counting the number of 1<br>y_train.count(0)  #counting the number of 0</pre><p>Counting the number of 1’s and 0’s in the array Y, we find that there are 44478 images of class 0 and 15522 images of class 1.</p><p>This problem is known as data imbalance and can cause our model to be more biased towards one particular class, usually the one which has more samples. Particularly in fields such as healthcare, classifying the minority class (malignant in this case) as majority class (benign in this case) can be very risky. We will deal with data imbalance by randomly undersampling the majority class, i.e removing samples of the majority class to make the number of samples of the majority and minority class equal.</p><pre>y_train = to_categorical(y_train)<br>y_test = to_categorical(y_test)</pre><p>Before that, we need to one-hot-encode the output variable y_train and y_test.</p><pre>X_trainShape = X_train.shape[1]*X_train.shape[2]*X_train.shape[3]<br>X_testShape = X_test.shape[1]*X_test.shape[2]*X_test.shape[3]<br>X_trainFlat = X_train.reshape(X_train.shape[0], X_trainShape)<br>X_testFlat = X_test.reshape(X_test.shape[0], X_testShape)</pre><p>We also need to reshape X_train and X_test to use the Random Under Sampler.</p><pre>from imblearn.under_sampling import RandomUnderSampler<br>random_under_sampler = RandomUnderSampler(ratio=&#39;majority&#39;)<br>X_trainRos, Y_trainRos = random_under_sampler.fit_sample(X_trainFlat, y_train)<br>X_testRos, Y_testRos = random_under_sampler.fit_sample(X_testFlat, y_test)</pre><p>The parameter ‘ratio=majority’ states the random under sampler to under sample the majority class.</p><p>Checking the number of samples of each class again after performing random undersampling, we find that we have equal number of samples of both the classes. The image data is then converted back to its original shape of 50 x 50 x 3.</p><h4>Model Architecture</h4><p>We use a <em>similar </em>architecture to the one discussed in this <a href="http://www.apsipa.org/proceedings/2017/CONTENTS/papers2017/15DecFriday/FP-02/FP-02.3.pdf">paper</a>.</p><pre>batch_size = 256<br>num_classes = 2<br>epochs = 80</pre><pre>model = Sequential()<br>model.add(Conv2D(32, kernel_size=(3,3),<br>                 activation=&#39;relu&#39;,<br>                 input_shape=(50,50,3)))<br>model.add(MaxPooling2D(pool_size=(2, 2)))<br>model.add(Conv2D(64, (3,3), activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2,2)))<br>model.add(Conv2D(128, (3, 3), activation=&#39;relu&#39;))<br>model.add(Conv2D(256, (3, 3), activation=&#39;relu&#39;))<br>model.add(Flatten()) #this converts our 3D feature maps to 1D feature vectors for the dense layer below<br>model.add(Dropout(0.5))<br>model.add(Dense(128, activation=&#39;relu&#39;))<br>model.add(Dropout(0.5))<br>model.add(Dense(128, activation=&#39;relu&#39;))<br>model.add(Dense(num_classes, activation=&#39;sigmoid&#39;))</pre><p>The model is a sequential which allows us to create the model layer-by-layer. The architecture consists of convolutional layers, max pooling layers, dropout layers and fully connected layers.</p><p>The first layer is a convolutional layer with 32 filters each of size 3 x 3. We are also required to specify the input shape in the first layer, which is 50 x 50 x 3 in our case.</p><p>We will be using the Rectified linear unit (ReLU) activation function for all the layers except the final output layer. ReLU is the most common choice for activation function in the hidden layers and has shown to work pretty well.</p><p>The second layer is a pooling layer. The pooling layers are used to reduce dimension. Max Pooling with a 2x2 window only considers the maximum value in the 2x2 window.</p><p>The third layer is again a convolutional layer of 64 filters each of size 3 x 3 followed by another max pooling layer of 2x2 window. Usually, the number of filters in the convolutional layer grows after each layer. The first layers with lower number of filter learns simple features of the images whereas the deeper layers learn more complex features.</p><p>The next two layers are again convolutional layers with the same filter size but increasing number of filters; 128 and 256.</p><p>We need to flatten the 3D feature map output from the convolutional layer to 1D feature vectors before adding in the fully connected layers. This is where the flatten layer comes in.</p><p>The next layer is a dropout layer with a dropout rate of 0.5 . A dropout layer with dropout rate of 0.5 means 50% of the neurons will be turned off randomly. This helps prevent overfitting by making all the neurons learn something about the data and not rely on just a few neurons. Randomly dropping neurons during training means other neurons will have to do the work of the turned-off neurons, thus generalizing better and prevent overfitting.</p><p>The value 0.5 is taken from the original paper by <a href="https://arxiv.org/pdf/1207.0580.pdf">Hinton (2012)</a>, which has proved to be very effective. These dropout layers are added after each of the fully connected layers before the output. Dropout also reduces the training time for each epoch.</p><p>The following dense layer (fully connected layer) has 128 neurons. This is followed by another dropout layer with a dropout rate of 0.5</p><p>The next layer is another dense layer with 128 neurons.</p><p>The final output layer is another dense layer which has number of neurons equal to the number of classes. The activation function in this layer is sigmoid because the problem in hand is a binary classification problem. For multi-class classification problem, the activation function should be set to softmax.</p><h4>Compiling the model</h4><pre>model.compile(loss=keras.losses.binary_crossentropy,<br>              optimizer=keras.optimizers.Adam(lr=0.00001),<br>              metrics=[&#39;accuracy&#39;])</pre><p>The model is compiled with binary cross entropy loss function and the Adam optimizer is used. The ‘accuracy’ metric is used to evaluate the model.</p><p>Adam is an optimization algorithm which updates the network weights in an iterative manner.</p><p>Although the initial learning rate for Adam can be set (we have set it to 0.00001 in our case), this is the initial learning rate and the learning rate for each parameter is adapted as training begins. This is how Adam (short for adaptive moment estimation) is different from stochastic gradient descent, which maintains a single learning rate for all weight updates. A detailed explanation of the Adam optimization algorithm can be found <a href="https://machinelearningmastery.com/adam-optimization-algorithm-for-deep-learning/">here</a></p><p>The learning rate determines how fast we are adjusting the weights of our network towards the local minima. Too high of a learning rate can result in such high weight changes that it might result in overshooting the local minima. This causes the training or validation error to fluctuate drastically between consecutive epochs. Too low of a learning rate can result in taking longer time to train our network. Thus, the learning rate is one of the most important hyperparameters that needs to be tuned when building the model.</p><h4>Data augmentation</h4><pre>datagen = ImageDataGenerator(<br>    featurewise_center=True,<br>    featurewise_std_normalization=True,<br>    rotation_range=180,<br>    horizontal_flip=True,vertical_flip = True)</pre><p>Generally, the more data we have, the better deep learning tends to work. Keras ImageDataGenerator generates real time images during training using data augmentation. Transformations are performed on the mini-batches on-the-fly. Data augmentation helps generalize the model by reducing the network’s capacity to overfit the training data. Rotation, vertical and horizontal flipping are some of the common data augmentation techniques used.</p><p>Keras ImageDataGenerator provides a variety of data augmentation techniques. However, we will only use few of them.</p><blockquote>A histopathology slide labelled as malignant is still malignant if it is rotated 20 degrees and flipped vertically.</blockquote><h4>Training the model</h4><blockquote>Training the model using a GPU speeds up the training process. You will need a NVIDIA GPU to do so. I followed this <a href="https://medium.com/@ab9.bhatia/set-up-gpu-accelerated-tensorflow-keras-on-windows-10-with-anaconda-e71bfa9506d1">tutorial </a>to enable GPU training.</blockquote><p>We set the number of epochs to a high number , in our case 80, and use a regularization method called Early Stopping</p><pre>early_stopping_monitor = EarlyStopping(monitor=&#39;val_loss&#39;, patience=3, mode=&#39;min&#39;)</pre><p>Early stopping is a method used to avoid overfitting by stopping the training process when the parameter set to observe does not improve for a certain number of epochs.</p><blockquote>In our case, we tell EarlyStopping to monitor val_loss and if it does not improve for 3 epochs continuously, stop the training process.”</blockquote><p>The batch size is usually set to a power of 2 because it is more computationally efficient. We have set it to 256.</p><p>We use another Keras callback called ModelCheckpoint</p><pre>model_checkpoint = ModelCheckpoint(&#39;best_model.h5&#39;, monitor=&#39;val_loss&#39;, mode=&#39;min&#39;, verbose=1, save_best_only=True)</pre><p>Model checkpoint is used to save the model. The monitor parameter allow us to set a metric which we want to keep an eye on. In our case, we only save the model when the validation loss is the minimum. We save the best model to be used later to make predictions and thus evaluate the model’s performance.</p><blockquote>Combining both these callbacks, the best model (which has the minimum validation loss) is saved and following that, if validation loss does not improve (decrease) over the next 3 epochs (set by EarlyStopping), the model training stops.</blockquote><pre>training = model.fit_generator(datagen.flow(X_trainRosReshaped,Y_trainRosHot,batch_size=batch_size),steps_per_epoch=len(X_trainRosReshaped) / batch_size, epochs=epochs,validation_data=(X_testRosReshaped, Y_testRosHot), verbose=1, callbacks=[early_stopping_monitor, model_checkpoint])</pre><p>Because we are using ImageDataGenerator on the fly, we use model.fit_generator to train the model. We set it to a variable ‘training’ as we will later plot the training loss and validation loss. This helps us get an idea of the variance, i.e the difference between training error and validation set error.</p><p>For validation, we will use X_testRosReshaped and Y_testRosHot which we obtained after under-sampling the x_test and y_test set.</p><p>Training stops after 37 epochs due to Early Stopping. Hence, the best model saved is the one during epoch 34, with a validation accuracy of 79.10%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*2C8z5CyZwdsy4qo03NvWCw.png" /><figcaption>val_loss stopped improving after Epoch 34</figcaption></figure><p>Plotting the training set and validation set loss, we find that the variance is very low. This plot ensures that our model is not overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*5i7znHkADNL6_40jl2R2Pw.png" /><figcaption>Training and testing set loss</figcaption></figure><h4>Making predictions</h4><pre>from keras.models import load_model<br>from sklearn import metrics</pre><pre>model = load_model(&#39;best_model.h5&#39;)</pre><pre>y_pred_one_hot = model.predict(X_testRosReshaped)</pre><pre>y_pred_labels = np.argmax(y_pred_one_hot, axis = 1)<br>y_true_labels = np.argmax(Y_testRosHot,axis=1)</pre><p>We load the best model saved by ModelCheckpoint and use the predict function to predict the classes of the images in the array X_testRosReshaped. The predictions are now stored in the list y_pred_labels.</p><h4>Evaluating the model’s performance</h4><pre>confusion_matrix = metrics.confusion_matrix(y_true=y_true_labels, y_pred=y_pred_labels)</pre><p>We use a confusion matrix to evaluate the models performance. The confusion matrix in a binary classification matrix has four quadrants; false positives, false negatives, true positives and true negatives.</p><p>For our case, the four quadrants of the confusion matrix can be simplified as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*GQCxnaPXqHAQhiaVKgJ5kw.png" /><figcaption>Confusion matrix with description of the 4 quadrants for our case</figcaption></figure><p>The confusion matrix we get is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*B2gT86xCNPgrQYtyJCuvcg.png" /><figcaption>Resultant confusion matrix</figcaption></figure><p>In cases such as this, having a lower false negative is better than having a lower false positive. This is because identifying a malignant tumour as benign is more dangerous than identifying a benign tumour as malignant, since the former will result in the patient receiving a different treatment due to misdiagnosis, and the latter is likely to go through further tests anyway.</p><p>We can see that our model performs well with an accuracy of 79.10% on the test set. The confusion matrix only is also favourable for us and we have a model with low variance.</p><p>Applying deep learning is an iterative process. You can try and improve this model further by tuning the hyperparameters such as learning rate of the optimization algorithm, changing the batch size, changing the filters of the convolutional layers, adding in more layers or using more data.</p><p><em>Thanks for reading. If you have any questions, comment them down below. I will be writing regularly on topics such as deep learning, so follow me here on Medium. I am also available on </em><a href="https://www.linkedin.com/in/bikramb/"><em>LinkedIn</em></a><em>! :) Happy coding.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debb429de9a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/predicting-invasive-ductal-carcinoma-using-convolutional-neural-network-cnn-in-keras-debb429de9a6">Predicting Invasive Ductal Carcinoma using Convolutional Neural Network (CNN) in Keras</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>