<?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 Rian Rachmanto on Medium]]></title>
        <description><![CDATA[Stories by Rian Rachmanto on Medium]]></description>
        <link>https://medium.com/@rachmanto.rian?source=rss-b563db46863b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iEzhtl7QHa9R9mKgwPk9LA.jpeg</url>
            <title>Stories by Rian Rachmanto on Medium</title>
            <link>https://medium.com/@rachmanto.rian?source=rss-b563db46863b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:39:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rachmanto.rian/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[Utilizing Large Language Models for Information Retrieval from Reports in the Oil and Gas Industry]]></title>
            <link>https://ai.plainenglish.io/utilizing-large-language-models-for-information-retrieval-from-reports-in-the-oil-and-gas-industry-1a82320a52de?source=rss-b563db46863b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a82320a52de</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Rian Rachmanto]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 03:24:15 GMT</pubDate>
            <atom:updated>2024-09-23T13:37:02.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KcSnPW665UBQUkZY" /></figure><p>In many industries, reports are pivotal, especially for gathering information to make business decisions or plan project steps. However, standardization of reports is often lacking across various sectors. Formats can range from MS Word and Excel documents to PDFs. For instance, I once attended a meeting where an accountant mentioned that their team struggled to input data from printed invoices provided by vendors into spreadsheets, causing delays in completing financial analyses on actual spending.</p><p>The subsurface team faces similar challenges. They must collect daily reports from field operations, workover programs, drilling activities, and more. These reports are crucial for reviewing potential workover programs or gathering insights from drilling operations. A significant amount of time is spent reviewing each report to extract vital information that will inform planning for upcoming workover campaigns. With advancements in Large Language Models (LLM) and their capabilities in extracting information from external sources, many industries, including the oil and gas sector, are beginning to utilize technologies like Retrieval Augmented Generation (RAG) for information extraction.</p><p>When ChatGPT was released to the public in 2022, it created a hype and was considered to play important roles in accelerating the AI boom. Many people utilize ChatGPT for querying all kinds of information or simply for generating text for multiple purposes such as generating ideas, drafting emails, and many more. As someone who enjoys reading novels, one of my favorite novels is War and Peace by Leo Tolstoy. To give you an idea of how to retrieve information regarding the content of the novel, I asked ChatGPT about the appearance of Napoleon in the novel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-SqJbGJBWPk1qztmPDKOQ.jpeg" /><figcaption>Conversation with Chatgpt discussing War and Peace by Leo Tolstoy</figcaption></figure><p>Based on its response, I can tell that the answer is pretty spot on. My other favorite readings include manga and light novels, especially those adapted into anime series. So, I asked ChatGPT about a light novel that I’m currently reading, My Instant Death Ability Is So Overpowered, No One in This Other World Stands a Chance Against Me!, regarding a certain event in volume 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*HNrX7KZSBdvfT85-.jpg" /><figcaption>Currently I’m reading the Volume 5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZ2Jx2emyLvwWxivBdlUGw.jpeg" /><figcaption>After reading volume 4 I can assure you that Chatgpt hallucinates in its response</figcaption></figure><p>However, the response was incorrect, since Takatou did not directly kill the goddess. Based on these two responses, we can conclude that there is a possibility that ChatGPT may not have been trained on volume 4 of the said light novel.</p><p>What if ChatGPT had access to a light novel or another external resource? This is where Retrieval-Augmented Generation (RAG) comes into play. Essentially, RAG allows a an LLM to access an external source as a retrieval method, which in turn enhances the quality of the responses by providing more contextual information.</p><p>How exactly does Retrieval-Augmented Generation (RAG) apply in the oil and gas industry? As previously mentioned, various tasks such as preparing workover programs, completing initial completion after drilling operations, or even managing financial documents at an oil company often require browsing through documents. These documents are typically scattered across different locations in shared folders and stored in multiple formats like Excel, Word, and PDF. Imagine if all these documents were embedded and stored in a vector database. In such a scenario, information could be easily retrieved by simply querying the LLM. This is how the RAG method could significantly reduce the time needed to gather information from reports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*LTvmGfBbMQS_mIPT.png" /><figcaption>Architecture of RAG, taken from <a href="https://www.3-port.si/">https://www.3-port.si/</a></figcaption></figure><h4>Volve Drilling Report Dataset</h4><p>For this RAG (Retrieval-Augmented Generation) project, we will use drilling reports from the Volve dataset, which you can access <a href="https://data.equinor.com/dataset/Volve">Volve Dataset</a>. To access the dataset, the simplest method is to use Azure Storage Explorer. The drilling reports are primarily in PDF format (although I vaguely recall that they may be available in other formats as well). These reports provide detailed accounts of daily drilling activities, covering events over 24-hour periods.Now, imagine you’re a drilling engineer, and the subsurface team has proposed a new well to be drilled. To ensure that all potential hazards and risks are accounted for in this new drilling operation, you need to review previous drilling reports. This process might take days, or even months, to complete, as you’d have to go through every report from day one to the final completion of each well. Identifying risks, problems, or hazards encountered during the drilling of nearby wells could take several days per well. If there are five neighboring wells, this could easily turn into a week or more of reading.However, by using RAG to retrieve information from all the drilling reports, the time required for this task can be reduced significantly, enabling faster risk assessment and decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qTbWHtty2P1xOvcg" /><figcaption>Daily drilling reports from Volve dataset</figcaption></figure><h4>Llama 3.1</h4><p>For this project, we will be using Meta’s large language model, Llama. To facilitate this, we will run the model locally. The first step involves installing Ollama. Detailed installation instructions can be found <a href="https://ollama.com/">here</a>. Once Ollama is successfully installed, open your terminal and enter the following command to download the model:ollama pull llama3.1</p><pre>ollama pull llama3.1</pre><p>And for the embedding model we will utilize nomic-embed-text,</p><pre>ollama pull nomic-embed-text</pre><h4>Chroma As Vector Database</h4><p>In this project, we will extensively utilize both the Langchain community and core versions. Specifically, we will use Chroma, a vector database included with Langchain community, and the Recursive Character Text Splitter for document chunking. To proceed, you must install these three components in your development environment.</p><pre>pip install langchain,langchain-core,langchain-community</pre><h3>Assembling RAG piece by piece</h3><h4>Document handling</h4><p>For this project, the drilling reports are provided in PDF format. We are using the PyPDF2 library to handle these documents, but you are free to use any library that can process PDF files. The method we employ involves accessing all the PDF documents in a specific folder and consolidating them into a single DataFrame. To simplify the process, the dataframe then saved a CSV file, which later converted into a text format. Feel free to adopt any method that you find suitable for your needs.</p><pre>import os<br>import re<br>import pandas as pd<br>from PyPDF2 import PdfReader<br><br>def extract_data_from_pdfs(folder_path):<br>    # Initialize list to hold dataframes for each file<br>    df_list = []<br>    <br>    # List all PDF files in the folder<br>    for filename in os.listdir(folder_path):<br>        if filename.endswith(&#39;.pdf&#39;):<br>            # Extract wellbore name from the filename<br>            wellbore_name = filename.split(&#39;_&#39;)[0] + &#39;_&#39; + filename.split(&#39;_&#39;)[1]<br>            <br>            # Load the PDF file<br>            reader = PdfReader(os.path.join(folder_path, filename))<br>            first_page = reader.pages[0]<br>            text = first_page.extract_text()<br>            <br>            # Regular expression to find the Report creation time<br>            report_time_pattern = re.compile(r&quot;Report creation time:\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2})&quot;)<br>            report_creation_time = report_time_pattern.search(text).group(1) if report_time_pattern.search(text) else &quot;Unknown Time&quot;<br>            <br>            # Initialize lists to hold extracted data<br>            start_times, end_times, end_depths, activities, states, remarks = [], [], [], [], [], []<br>            <br>            # Regular expression to match the operations data pattern<br>            operations_pattern = re.compile(r&quot;(\d{2}:\d{2})\s+(\d{2}:\d{2})\s+(\d+)\s+(.*?)\s+(ok|fail)\s+(.*?)\n&quot;)<br>            <br>            # Extract data using the defined pattern<br>            for match in operations_pattern.finditer(text):<br>                start_times.append(match.group(1))<br>                end_times.append(match.group(2))<br>                end_depths.append(int(match.group(3)))<br>                activities.append(match.group(4))<br>                states.append(match.group(5))<br>                remarks.append(match.group(6))<br>            <br>            # Create a DataFrame for this file<br>            data = {<br>                &quot;Wellbore&quot;: [wellbore_name] * len(start_times),<br>                &quot;Report Creation Time&quot;: [report_creation_time] * len(start_times),<br>                &quot;Start Time&quot;: start_times,<br>                &quot;End Time&quot;: end_times,<br>                &quot;End Depth mMD&quot;: end_depths,<br>                &quot;Main - Sub Activity&quot;: activities,<br>                &quot;State&quot;: states,<br>                &quot;Remark&quot;: remarks<br>            }<br>            df = pd.DataFrame(data)<br>            df_list.append(df)<br>    <br>    # Concatenate all DataFrames into one, sorting by &#39;Wellbore&#39;<br>    if df_list:<br>        final_df = pd.concat(df_list)<br>        final_df.sort_values(by=&#39;Wellbore&#39;, inplace=True)<br>        return final_df<br>    else:<br>        return pd.DataFrame()  # Return an empty DataFrame if no files were processed<br><br># Example usage:<br>df = extract_data_from_pdfs(&quot;/Users/rianrachmanto/miniforge3/project/RAG_Drill_Report/data&quot;)<br>print(df)</pre><h4>Loading and chunking text documents</h4><p>For simplicity, the dataframe is saved as a text file and loaded using the LangChain Text Loader library. The text is then divided into sections with the LangChain Recursive Character Text Splitter. At this stage, your text document is prepared for chunking. “Chunking” refers to the process of breaking the document into smaller segments. This process involves two adjustable parameters: chunk size and overlap. The chunk size, measured in tokens, determines the maximum number of characters each segment can contain. The chunk overlap parameter specifies the number of characters that overlap with those from the adjacent segment. It is recommended that the chunk overlap occur every 100–200 tokens. A study conducted by LlamaIndex (detailed in this <a href="https://www.llamaindex.ai/blog/evaluating-the-ideal-chunk-size-for-a-rag-system-using-llamaindex-6207e5d3fec5">link</a>) found that the optimal faithfulness in text processing is achieved with a chunk size of 1024 tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*eIYM5enjbRDP-I3m.png" /><figcaption>Table of Chunk Size comparison. Source taken from llamaindex</figcaption></figure><p>What is the role of chunk size in information retrieval? A smaller chunk size typically yields more detailed information, while a larger chunk size can provide broader contextual insights. To illustrate this, consider two examples where the first uses a chunk size of 512 tokens and a chunk overlap of 10. As observed, the smaller chunk size of 512 tokens resulted in more detailed information being retrieved.</p><p><strong>Smaller Chunk (Image 1)</strong>: The response is more detailed for specific issues like the “slipped and cut drilling line,” which includes context about the troubleshooting process on Atlas equipment. It also mentions the depth at which the “45 T over pull at connection” occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4I_bDCvx1ZyFYHcejUCKw.jpeg" /></figure><p><strong>Larger Chunk (Image 2)</strong>: This output seems more general and less detailed. It mentions the same issues but omits specific details like the depth at which the over-pull occurred or the specific process of troubleshooting for the cut line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5bNTItXEal1BHucFCUBnA.jpeg" /></figure><p>And here is the example of the code for chunking documents,</p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br>def split_text(docs):<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=10)<br>    documents = text_splitter.split_documents(docs)<br>    return documents</pre><h4>Embedding, Storing to Vector Database, Setting Up Retriever</h4><p>After the documents have been divided into chunks, each chunk will be embedded. This process transforms the document fragments into numerical vectors that uniquely represent each chunk. These vectors are then stored in a vector database. For this project, we are using the ‘ollama nomic-embed-text’ model for the embedding process, and ‘Chroma’ as our vector database. For retrieving documents, we will utilize the LangChain Vector Store-Backed Retriever. Currently, our search method is set to ‘similarity’ with search parameters configured to return four documents.</p><pre>from langchain_community.vectorstores import Chroma<br>from langchain_community.embeddings import OllamaEmbeddings<br><br>def create_db(documents, embeddings):<br>    db = Chroma.from_documents(documents=documents, embedding=embeddings,persist_directory=&#39;./Chroma_DB&#39;)<br>    return db<br>def create_retriever(db):<br>    retriever = db.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 4})<br>    return retriever<br><br>def main():<br>    embeddings = OllamaEmbeddings(model=&quot;nomic-embed-text&quot;)<br>    db = create_db(documents, embeddings)<br>    retriever = create_retriever(db)<br>    <br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Setting Up Local Model and RAG Chain</h4><p>The final step, which is crucial, involves setting up the model that we have already downloaded to our local storage. For this task, I am using Llama 3.1 from Meta. This is followed by the most critical part of the RAG chain, in my view. Generally, the prompt provides guidance to the LLM, enabling it to deliver more accurate and effective responses.</p><pre>def create_llm(local_model):<br>    llm = ChatOllama(model=local_model, num_predict=400,<br>                 stop=[&quot;&lt;|start_header_id|&gt;&quot;, &quot;&lt;|end_header_id|&gt;&quot;, &quot;&lt;|eot_id|&gt;&quot;])<br>    return llm<br><br>def create_rag_chain(retriever, llm):<br>    prompt_template = &quot;&quot;&quot;<br>    &lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;<br>    You are a drilling engineer and an analyst. Your task is reading the drilling report,<br>    withing the context of the drilling report, answer the question based on the context of the document.<br>    All you need to answer what you can find in the document. If you can&#39;t find the answer, you can say &quot;I don&#39;t know&quot;.<br>    Question: {question}<br>    Context: {context}&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;<br>    &quot;&quot;&quot;<br><br>    prompt = PromptTemplate(<br>        input_variables=[&quot;context&quot;, &quot;question&quot;],<br>        template=prompt_template,<br>    )<br><br>    rag_chain = (<br>        {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>        | prompt<br>        | llm<br>        | StrOutputParser()<br>    )<br>    return rag_chain</pre><p>Now the complete code should look like this,</p><pre>from langchain_community.document_loaders import TextLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain_community.vectorstores import Chroma<br>from langchain_community.embeddings import OllamaEmbeddings<br>from langchain_community.chat_models import ChatOllama<br>from langchain.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough<br>import time<br><br>def loader_text(path):<br>    loader = TextLoader(path)<br>    docs = loader.load()<br>    return docs<br><br>def split_text(docs):<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=10)<br>    documents = text_splitter.split_documents(docs)<br>    return documents<br><br>def create_db(documents, embeddings):<br>    db = Chroma.from_documents(documents=documents, embedding=embeddings,persist_directory=&#39;./Chroma_DB&#39;)<br>    return db<br><br>def create_retriever(db):<br>    retriever = db.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 4})<br>    return retriever<br><br>def create_llm(local_model):<br>    llm = ChatOllama(model=local_model, num_predict=400,<br>                 stop=[&quot;&lt;|start_header_id|&gt;&quot;, &quot;&lt;|end_header_id|&gt;&quot;, &quot;&lt;|eot_id|&gt;&quot;])<br>    return llm<br><br>def create_rag_chain(retriever, llm):<br>    prompt_template = &quot;&quot;&quot;<br>    &lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;<br>    You are a drilling engineer and an analyst. Your task is reading the drilling report,<br>    withing the context of the drilling report, answer the question based on the context of the document.<br>    All you need to answer what you can find in the document. If you can&#39;t find the answer, you can say &quot;I don&#39;t know&quot;.<br>    Question: {question}<br>    Context: {context}&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;<br>    &quot;&quot;&quot;<br><br>    prompt = PromptTemplate(<br>        input_variables=[&quot;context&quot;, &quot;question&quot;],<br>        template=prompt_template,<br>    )<br><br>    rag_chain = (<br>        {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>        | prompt<br>        | llm<br>        | StrOutputParser()<br>    )<br>    return rag_chain<br><br>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br><br>def main():<br>    start_time = time.time()<br>    path=&quot;./data/remark.txt&quot;<br>    docs = loader_text(path)<br>    documents = split_text(docs)<br>    embeddings = OllamaEmbeddings(model=&quot;nomic-embed-text&quot;)<br>    db = create_db(documents, embeddings)<br>    retriever = create_retriever(db)<br>    local_model = &quot;llama3.1&quot;<br>    llm = create_llm(local_model)<br>    rag_chain = create_rag_chain(retriever, llm)<br>    question = &quot;List all problems encountered during drilling?&quot;<br>    print(question)<br>    print(rag_chain.invoke(question))<br>    print(&quot;--- %s seconds ---&quot; % (time.time() - start_time))<br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br><br></pre><p>As we can see, the model could provide us with a good response in this snippet,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxjb9-jLjNAIR-K39t_ABQ.jpeg" /><figcaption>Response from RAG</figcaption></figure><p>The entire process takes about 60 seconds to complete. This can significantly aid those who need to quickly extract information from multiple document pages, thereby facilitating more efficient and sound decision-making.</p><p>And if you are interested in looking at the code, you can find the source code in this github <a href="https://github.com/Rian021102/RAG_Well_hist">here</a>.</p><p>Thank you for making time reading this article, and hopefully you can find what you read applicable in any case or industries.</p><p>Cheers,</p><p>Rian</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a82320a52de" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/utilizing-large-language-models-for-information-retrieval-from-reports-in-the-oil-and-gas-industry-1a82320a52de">Utilizing Large Language Models for Information Retrieval from Reports in the Oil and Gas Industry</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Addressing Imbalance in Credit Card Fraud Detection Data]]></title>
            <link>https://medium.com/@rachmanto.rian/addressing-imbalance-in-credit-card-fraud-detection-data-46666c3636b1?source=rss-b563db46863b------2</link>
            <guid isPermaLink="false">https://medium.com/p/46666c3636b1</guid>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <dc:creator><![CDATA[Rian Rachmanto]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 12:21:39 GMT</pubDate>
            <atom:updated>2024-10-11T01:03:58.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KOOj0_cXQUe4THBw" /></figure><p>Over time, credit cards have experienced a notable rise in popularity as the favored choice for transactions, primarily due to their widespread acceptance and convenience. Nevertheless, the widespread adoption of credit cards has brought new challenges, with fraudulent transactions emerging as a notable issue. As the number of credit cards issued by banks continues to grow, automated fraud detection methods, including the utilization of machine learning, have been introduced as a proactive measure to address this growing concern.</p><p>This project aims to illustrate how machine learning can enhance banks’ ability to identify transaction anomalies. We employed the Kaggle <a href="https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud">Credit Card Fraud Detection</a> for this purpose. However, upon classifying the data, it became evident that the “Not Fraud” category comprises only 0.2%, making it the overwhelming majority class at over 99%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YbOQfhLkIuNeK0M4Iuu0kQ.png" /><figcaption>Highly imbalance class</figcaption></figure><p>Training the model quickly using logistic regression yields a remarkably high accuracy of 0.999 (99.9%). At first glance, one might conclude that our model is exceptionally accurate. However, considering our awareness of the highly imbalanced nature of the data, it is crucial not to take this accuracy at face value.</p><p>In the case of highly imbalanced data, we often observe that the model’s accuracy is high. However, a model trained on imbalanced data tends to be biased toward the majority class (Not Fraud in this case). Consequently, the model’s predictions are skewed toward the majority class.</p><p>Imagine a scenario where someone is using your credit card for a transaction, but the model fails to detect an anomaly in the transaction. Similarly, envision a model that overlooks a customer about to churn or fails to identify cardiovascular disease. In such cases, the limitations of relying solely on accuracy become apparent.</p><h3>Evaluating Models Trained on Imbalanced Data Using Precision, Recall and F1-Score</h3><p>Accuracy is frequently used as a metric to evaluate a model. It represents the ratio of the total number of correct predictions to the total number of predictions. As mentioned earlier, the trained model achieved 99.9% accuracy. But how did the model achieve this level of accuracy? Let’s plot the confusion matrix,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UOsi213t6m0hGlOgbMMFYA.png" /><figcaption>Confusion matrix of imbalance class</figcaption></figure><ul><li>True Negative is 56,855</li><li>False Positive is 9</li><li>False Negative is 41</li><li>True Positive is 57</li></ul><p>The model correctly predicts class 0 (negative) in 56,855 samples but fails to do so when the actual class is 1 (positive) in 41 samples. Additionally, the model falsely predicts class 1 when the actual class is 0 in 9 samples, while it correctly predicts class 1 in 57 samples. If accuracy is denoted as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NdHd0qn6wVHTBzqA" /></figure><p>Then it becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BPpfNUTFaM2iCV4x" /></figure><p>After looking at it, we realize that the model tends to favor majority class which is made of 99% of total sample. As mentioned earlier in the above section, the model tends to predict the majority class hence for this case, we cannot simply use accuracy as evaluation metrics. Hence we need others metrics, which in this case we will look at, precision, recall and F1-Score that give us,</p><ul><li>Precision 0.86</li><li>Recall 0.58</li><li>f1 score is 0.69</li></ul><p>The follow-up question now is: which metrics should be used? It’s hard to answer specifically since different metrics are influenced by different businesses or problems. For instance, correctly classifying patients with cancer is much more important than not, so we can consider using recall. On the other hand, banks might find it better to predict more non-default credit card users and risk losing potential customers due to denial; in this case, precision might be suitable.</p><h4>Addressing Imbalanced Data Through Class Weight Adjustment</h4><p>In this particular project, we will explore methods for addressing imbalanced data through algorithmic modification (using the Scikit-learn library). For the machine learning model itself, our emphasis will be on logistic regression, with the addition of XGBoost for the purpose of comparison. The approach involves simply incorporating different class weights into the cost function of the algorithm.</p><p>Cost function is defined as measurement of how well a machine learning model is performing in terms of its ability to predict the desired output. The cost function quantifies the difference between the predicted values and the actual values, providing a numerical value that the optimization algorithm seeks to minimize during the training process.</p><p>In logistic regression, we utilize log loss as the cost function, defined by the formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uRLY-A7JvHbkmsMr" /></figure><p>With Class Weight defined by the formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s3peVo14yFqOGSDs" /></figure><p>By adding class weight into the function, the log loss becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i0wYKnsF9UGppJ5K" /></figure><p>This modified log loss incorporates the class weights wo and w1 to adjust the contribution of each instance to the overall loss. The goal is to penalize misclassifications of the minority class (positive class) more heavily, addressing the imbalance in the dataset.</p><h4>Implementing Class Weights in Python</h4><p>Scikit Learn provides us a way to adjust class weight through arguments class_weight. When not stated class_weight by default for all class_weight is equal to 1. When you set class_weight to ‘balanced’, the model automatically it adjusts the weights inversely proportional to class frequencies. This means that the model gives more weight to the minority class, effectively addressing the imbalance.</p><pre>def log_reg_balance(X_train_scaled, y_train, X_test_scaled, y_test):<br>    logreg_balance = LogisticRegression(class_weight=&#39;balanced&#39;,max_iter=1000)<br>    logreg_balance.fit(X_train_scaled,y_train)<br>    y_pred=logreg_balance.predict(X_test_scaled)<br>    print(confusion_matrix(y_test,y_pred))<br>    #plot confusion matrix<br>    plt.figure(figsize=(10,8))<br>    sns.heatmap(confusion_matrix(y_test,y_pred),annot=True)<br>    plt.xlabel(&#39;Predict&#39;)<br>    plt.ylabel(&#39;Actual&#39;)<br>    plt.show()</pre><p>If you want to adjust manually (by giving each class its own weight), you can achieve it by using this formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P19mEBnp3Em2Exyl" /></figure><p>In this case, we have 227,451 samples for class 0 and 394 samples for class 1. Therefore, w0 is set to 0.5, and w1 is set to 289.</p><p>Plug in the class weight of each class in class_weight, will achieve the same result as set class_weight to ‘balanced’</p><pre>def train_class_weight(X_train_scaled,y_train,X_test_scaled,y_test):<br>    class_weight={0:0.5,1:289}<br>    logreg_class_weight=LogisticRegression(class_weight=class_weight,solver=&#39;newton-cg&#39;,max_iter=1000)<br>    #train model<br>    logreg_class_weight.fit(X_train_scaled,y_train)<br>    #predict<br>    y_pred=logreg_class_weight.predict(X_test_scaled)<br>    #print confusion matrix<br>    print(confusion_matrix(y_test,y_pred))<br>    #plot confusion matrix<br>    plt.figure(figsize=(10,8))<br>    sns.heatmap(confusion_matrix(y_test,y_pred),annot=True)<br>    plt.xlabel(&#39;Predict&#39;)<br>    plt.ylabel(&#39;Actual&#39;)<br>    plt.show()</pre><p>The updated model, after adjusting the class_weight, shows an improvement in terms of correctly predicting true positives, as observed from this confusion matrix,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*cDz22OmGsVTC8vQZ" /><figcaption>Confusion matrix using ‘balanced’</figcaption></figure><p>As evident, the number of true positives increases from 57 samples to 90 samples. However, conversely, the count of false negatives also rises significantly, escalating from 9 samples to 1,300 samples. This suggests that the model now places more emphasis on the minority class, even though it incorrectly predicts class 1 when the reality is class 0, resulting in an increase in false positives. This implies a trade-off between sensitivity and specificity, which is a common observation when dealing with imbalanced datasets and adjusting class weights. The changes in the number of true positives, false positives, true negatives, and false negatives automatically update the precision, recall, and F1 score, respectively.</p><ul><li>Precision 0.06</li><li>Recall 0.92</li><li>f1 score is 0.12</li></ul><p>Another approach involves determining optimal weights through hyperparameter tuning, specifically employing grid search. This process utilizes fractions, such as 0:0.1 and 1:0.99, to represent the assigned weights for each class,</p><pre>def param_log_reg(X_train_scaled, y_train, X_test_scaled, y_test):<br>    logreg = LogisticRegression(solver=&#39;newton-cg&#39;, max_iter=1000)<br>    # create class weight<br>    weights = {&#39;class_weight&#39;: [{0: x, 1: 1.0 - x} for x in np.linspace(0.0, 0.99, 200)]}<br>    grid_search = GridSearchCV(logreg, weights, cv=5, scoring=&#39;f1&#39;, n_jobs=-1)<br>    # Perform the grid search<br>    grid_search.fit(X_train_scaled, y_train)<br><br>    # Get the best model from the search<br>    best_model = grid_search.best_estimator_<br><br>    # Evaluate the best model on the test set<br>    y_pred = best_model.predict(X_test_scaled)<br><br>    # Print confusion matrix<br>    print(confusion_matrix(y_test, y_pred))<br>    # Plot confusion matrix<br>    plt.figure(figsize=(10, 8))<br>    sns.heatmap(confusion_matrix(y_test, y_pred), annot=True)<br>    plt.xlabel(&#39;Predict&#39;)<br>    plt.ylabel(&#39;Actual&#39;)<br>    plt.show()</pre><p>Hyperparameter tuning resulted in the optimal class weights are 0:0.095, 1:0.905, or class 1 is approximately 9.59 higher than class 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Nj6hs0HXueMHTaUv" /><figcaption>Confusion matrix using hyperparameter tuning</figcaption></figure><p>The results are intriguing as the number of true positives increases to 79 samples, while the false positives also increase, albeit not as significantly as when using class_weight=’balanced’. The false negatives decrease to 19. The updated precision, recall, and F1 score are now as follows:</p><ul><li>Precision: 0.79</li><li>Recall: 0.81</li><li>F1 Score: 0.80</li></ul><p>This approach, involving hyperparameter tuning to find optimal class weights, seems to offer a more controlled and effective way to balance the trade-off between sensitivity and specificity compared to the automatic adjustment with ‘balanced’ class weights. The model in the second statement achieves better precision, recall, and F1 score, indicating a more balanced performance in handling imbalanced datasets.</p><h4>Cost-Sensitive Learning</h4><p>In credit card fraud detection, failing to classify the minority class (fraud) is more detrimental than incorrectly classifying actual observations of the majority class (non-fraud). This implies that when we fail to classify fraud, the consequences are more costly than incorrectly classifying non-fraudulent transactions.</p><p>In cost-sensitive learning, a common heuristic approach involves using the imbalance ratio, which is defined as the number of samples in the minority class divided by the number of samples in the majority class.</p><p>The other approach is to strongly penalize mistakes in fraud classification. This is achieved by assigning a higher cost for misclassifying non-fraud transactions. This encourages the model to prioritize correct predictions for the minority class.</p><p>For example we can say that the cost of misclassifying a fraudulence (Class 1) as legitimate (Class 0) is 10 times higher than the cost of misclassifying a legitimate transaction as fraudulent, then we can set the class weight as follow,</p><pre>class_weight = {0: 1, 1: 10}  # Assuming class 1 (fraudulent) is 10 times more important</pre><p>Here, the weight for Class 1 is set to 10, indicating that misclassifying a fraudulent transaction carries 10 times the penalty compared to misclassifying a legitimate transaction.</p><p>By using these class weights in logistic regression, the model is encouraged to pay more attention to correctly classifying fraudulent transactions, even if they are fewer in number. This is a form of cost-sensitive learning where the model’s training is influenced by the specified class weights.</p><pre>def cons_learn_logreg(X_train_scaled, y_train, X_test_scaled, y_test):<br>    class_weight={0:1,1:10}<br>    logreg = LogisticRegression(class_weight=class_weight, solver=&#39;newton-cg&#39;, max_iter=1000)<br>    logreg.fit(X_train_scaled, y_train)<br>    y_pred = logreg.predict(X_test_scaled)<br>    print(confusion_matrix(y_test, y_pred))<br>    # Plot confusion matrix<br>    plt.figure(figsize=(10, 8))<br>    sns.heatmap(confusion_matrix(y_test, y_pred), annot=True)<br>    plt.xlabel(&#39;Predict&#39;)<br>    plt.ylabel(&#39;Actual&#39;)<br>    plt.show()</pre><h4>Adjusting Class Weight In XGBoost</h4><p>For comparison, we also include modifying class weight in XGBoost. In XGBoost, you can utilize the scale_pos_weight parameter to address imbalanced class distribution. This parameter plays a role similar to adjusting class weights in logistic regression, where the goal is to mitigate the impact of imbalanced classes on the model’s training process.</p><p>In logistic regression, you can assign different weights to classes using the class_weight parameter. This allows the algorithm to give more importance to the minority class during optimization. Similarly, in XGBoost, the scale_pos_weight parameter serves a comparable purpose by adjusting the weights assigned to positive instances. The value of scale_pos_weight is typically set based on the ratio of negative to positive instances in the dataset.</p><p>Both methods aim to address the challenge of imbalanced data by influencing the learning algorithm to pay more attention to the minority class. However, the specific implementation details and parameter tuning processes may differ between logistic regression and XGBoost.</p><p>It’s worth noting that while logistic regression directly incorporates class weights during optimization, XGBoost, being a tree-based ensemble method, uses boosting to adaptively assign weights to instances during each iteration. Cross-validation is often employed in both cases to fine-tune the weight parameters for optimal model performance.</p><pre>def param_xgb(X_train,y_train,X_test,y_test):<br>    # Calculate class weights<br>    class_counts = y_train.value_counts()<br>    scale_pos_weight = class_counts[0] / class_counts[1]<br><br>    # Set up XGBoost classifier with scale_pos_weight<br>    clf = XGBClassifier(scale_pos_weight=scale_pos_weight)<br><br>    # Train model<br>    clf.fit(X_train, y_train)<br><br>    # Predict<br>    y_pred = clf.predict(X_test)<br><br>    print(confusion_matrix(y_test, y_pred))<br>    # Plot confusion matrix<br>    plt.figure(figsize=(10, 8))<br>    sns.heatmap(confusion_matrix(y_test, y_pred), annot=True)<br>    plt.xlabel(&#39;Predict&#39;)<br>    plt.ylabel(&#39;Actual&#39;)<br>    plt.show()</pre><p>Now we can use a confusion matrix to compare with the methods discussed in the previous sections, specifically focusing on logistic regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*9eNUIMnuF6ZTWwdH" /><figcaption>Confusion matrix using class weight modification on XGBoost</figcaption></figure><p>And respective precision, recall and f1 score,</p><ul><li>Precision: 0.96</li><li>Recall: 0.83</li><li>F1 Score: 0.90</li></ul><h4>Summary</h4><p>Both XGBoost and logistic regression with hyperparameter tuning offer a more controlled and effective way to balance the trade-off between sensitivity and specificity compared to automatic adjustment with ‘balanced’ class weights. The model in the second statement achieves better precision, recall, and F1 score, indicating a more balanced performance in handling imbalanced datasets. However, the decision remains dependent on business requirements. For instance, if correctly identifying the positive class is more crucial and the cost of misclassifying the negative class when it’s actually the positive class is higher, then a cost-sensitive approach by setting class_weight = balanced could be a good option as well.</p><p>Some points that we can offer as follow:</p><ol><li>XGBoost and Logistic Regression with Hyperparameter Tuning:Offer a more controlled and effective way to balance sensitivity and specificity.Achieve better precision, recall, and F1 score, indicating a more balanced performance with imbalanced datasets.</li><li>‘Balanced’ Class Weights:Automatic adjustment with ‘balanced’ class weights may not perform as well in achieving a balance between precision, recall, and F1 score.</li><li>Decision Considerations:The decision on which approach to choose depends on business requirements.For instance, if correctly identifying the positive class is more important and misclassifying the negative class as positive is costlier, a cost-sensitive approach by setting class_weight = balanced might be a good option.</li></ol><p>You can access the source code here: <a href="https://github.com/Rian021102/credit_card_fraud_detection">Credit Card Fraud Detection Source</a></p><p>And I love to share these great reading here</p><p><a href="https://fraud-detection-handbook.github.io/fraud-detection-handbook/Chapter_1_BookContent/BookContent.html">Fraud Detection Handbook</a></p><p><a href="https://machinelearningmastery.com/cost-sensitive-learning-for-imbalanced-classification/">Cost Sensitive Learning for Imbalanced Classification</a></p><p><a href="https://www.analyticsvidhya.com/blog/2020/10/improve-class-imbalance-class-weights/">Improve Class Imbalance in Machine Learning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46666c3636b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sex Classification Based on Eyes Using Deep Learning]]></title>
            <link>https://medium.com/@rachmanto.rian/sex-classification-based-on-eyes-using-deep-learning-42d05d66ef71?source=rss-b563db46863b------2</link>
            <guid isPermaLink="false">https://medium.com/p/42d05d66ef71</guid>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rian Rachmanto]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 13:05:23 GMT</pubDate>
            <atom:updated>2024-01-08T13:54:29.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KJtsKbwIOJwQ4yc9" /><figcaption>Photo by <a href="https://unsplash.com/@ionfet?utm_source=medium&amp;utm_medium=referral">Ion Fet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>“Dari Mata Turun ke Hati” is a widely recognized Indonesian phrase, loosely translated into English as “falling in love begins from the sight,” akin to the concept of love at first sight. In the realm of artificial intelligence (A.I.), leveraging the eyes as tools can offer various benefits, such as identity identification and enhanced security, especially in the context of COVID-19 protocols that necessitate mask-wearing. Since only the eyes are visible, employing A.I. for sex identification becomes pivotal.</p><p>This project aims to address the challenges posed by limited facial visibility and contribute a solution to sex classification using a deep learning model, specifically Convolutional Neural Network (CNN). Beyond individual identification, the proposed system can find applications in businesses, aiding in sex-based customer segmentation. For instance, it can be utilized in stores to analyze the demographic distribution of visitors, providing valuable insights for business optimization.</p><h4>The Dataset</h4><p>The dataset employed in this project is sourced from Kaggle and is accessible <a href="https://www.kaggle.com/datasets/pavelbiz/eyes-rtte">here</a>. It comprises two folders: “femaleeyes” and “maleeyes.” To utilize the dataset, download it and copy the folders into your local directory. It’s important to note that the dataset lacks explicit labels. However, a labeling method will be employed, associating each image with its respective category based on the directory structure.</p><pre>def load_and_preprocess_images(file_paths, labels, image_size=100):<br>    data = []<br>    for path, label in zip(file_paths, labels):<br>        img = tf.keras.preprocessing.image.load_img(path, target_size=(image_size, image_size), color_mode=&#39;grayscale&#39;)<br>        img_array = tf.keras.preprocessing.image.img_to_array(img)<br>        data.append([img_array, label])<br>    return np.array([item[0] for item in data]), np.array([item[1] for item in data])<br><br>def load_data_and_preprocess(data_path):<br>    path_img = list(data_path.glob(&#39;**/*.jpg&#39;))<br>    labels = [os.path.split(path.parent)[1] for path in path_img]<br><br>    label_encoder = LabelEncoder()<br>    encoded_labels = label_encoder.fit_transform(labels)<br><br>    train_data = pd.DataFrame({<br>        &#39;File_Path&#39;: path_img,<br>        &#39;Labels&#39;: encoded_labels<br>    })<br><br>    train_data = train_data.sample(frac=1).reset_index(drop=True)<br><br>    X, y = load_and_preprocess_images(train_data[&#39;File_Path&#39;], train_data[&#39;Labels&#39;])<br><br>    return X, y</pre><h4>Binary Classification</h4><p>This project involves binary classification, where the desired output is either 0 or 1, representing female or male. It’s essential to comprehend the project’s objective, whether it entails regression or classification (either binary or multiple classes), as this understanding guides the selection of an appropriate activation function. Given that it is a binary classification task, we will employ the Sigmoid activation function in the last fully connected layer (dense layer) of our neural network to accomplish this objective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*o8vSglUxQg0dhSsdTvKx3A.png" /><figcaption>Sigmoid function</figcaption></figure><p>And when you plot Sigmoid function will give;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fPAy0ciBZrMM6ps4.png" /><figcaption>Sigmoid function plot</figcaption></figure><h4>Rectified Linear Unit (ReLU)</h4><p>The Sigmoid function presents certain disadvantages. Firstly, when the input deviates slightly from the coordinate origin, the function’s gradient becomes extremely small, almost zero. In the backpropagation process of neural networks, this results in the chain’s gradient being significantly reduced, hindering the impact of the weight on the loss function. This phenomenon, known as gradient saturation or gradient dispersion, poses challenges to effective weight optimization. Additionally, the function’s output not being centered on 0 diminishes the efficiency of weight updates. Furthermore, the sigmoid function involves exponential operations, leading to slower computations for computers. These drawbacks underscore the limitations associated with the use of the Sigmoid function.</p><p>o address the limitations of the Sigmoid function, a viable approach involves incorporating the Rectified Linear Unit (ReLU) activation in other hidden layers of the model. ReLU is defined as the function f(x) = max(0, x), ensuring that only positive values are passed through directly, while negative values are set to zero. This design choice allows ReLU to mitigate the vanishing gradient problem, especially in deep neural networks, as it maintains a more substantial gradient during backpropagation. Unlike Sigmoid, ReLU promotes efficient learning and helps overcome challenges associated with gradient saturation or dispersion. Integrating ReLU into the model architecture thus provides a practical solution to enhance the overall performance and effectiveness of the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*6l4KpIFPvoBSJYNWgOlQng.png" /><figcaption>ReLU</figcaption></figure><h4>Binary Crossentropy</h4><p>Binary crossentropy, also known as log loss, is a function that quantifies the disparity between true labels and the predicted probabilities (associated with a label) generated by your model using the Sigmoid activation function. Throughout the training process, the objective is to minimize the average cost. The binary crossentropy is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*W4Dy9vQngBKWtFahDy3Igg.png" /><figcaption>Binary Crossentropy</figcaption></figure><h4>Convolutional Neural Network (CNN)</h4><p>As our data is structured as images with a grid-like topology, the choice for training involves employing the Convolutional Neural Network (CNN) algorithm. CNN is preferred due to its effectiveness in handling grid-like structures, rendering it highly suitable for image processing tasks. Comprising multiple layers that process and transform input to generate an output.</p><p>A Convolutional Neural Network (CNN) typically consists of three fundamental types of layers: convolutional layers, pooling layers, and fully connected layers.</p><ol><li>Convolutional Layers: Convolutional layers play a pivotal role in capturing spatial hierarchies and patterns within the input data, especially in images. These layers utilize convolutional operations, employing filters (also called kernels) to scan the input data. These filters learn to detect specific features, such as edges or textures, contributing to the network’s ability to recognize more complex patterns in higher layers.</li><li>Pooling Layers: Pooling layers are employed to downsample the spatial dimensions of the input data while retaining its essential features. Max pooling and average pooling are common techniques used in this layer. Max pooling, for instance, selects the maximum value from a group of neighboring values, effectively reducing the spatial resolution. This downsampling aids in reducing the computational load and focuses on the most crucial information.</li><li>Fully Connected Layers: Fully connected layers, also known as dense layers, come into play towards the end of the network. They take the high-level features captured by the convolutional and pooling layers and use them for classification or regression tasks. Each neuron in a fully connected layer is connected to every neuron in the preceding layer, allowing the network to learn complex relationships between features and make predictions based on the learned representations.</li></ol><p>In summary, convolutional layers extract local patterns, pooling layers reduce spatial dimensions, and fully connected layers leverage the extracted features for final predictions in a CNN. This architecture proves effective for tasks such as image classification, object detection, and other image-related problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*Lxa2ClAzsOMTW6-5.png" /><figcaption>CNN Architecture</figcaption></figure><h4>Build Model</h4><p>Now, let’s transition from theoretical discussions to practical implementation by translating our insights into code. We’ll incorporate the Sigmoid activation function and binary crossentropy loss into a Convolutional Neural Network (CNN) structure. This coding step allows us to apply these concepts to real-world data, harnessing the power of these techniques for tasks such as binary classification on image data.</p><p>In the ensuing code, we’ll define the architecture of our CNN, specifying the layers with Sigmoid activation and utilizing binary crossentropy as our chosen loss function. This integration aligns with the principles we’ve discussed earlier, where Sigmoid is suitable for binary classification outputs, and binary crossentropy serves as an effective measure for optimizing our model.</p><p>Let’s dive into the practical implementation and bring the theoretical aspects to life through code.</p><pre>def build_model():<br>    with tf.device(&#39;/cpu:0&#39;):<br>        adam_optimizer = tf.keras.optimizers.Adam(learning_rate=0.00001)<br>        model = Sequential([<br>            layers.Conv2D(filters=128, kernel_size=(11, 11), strides=(4, 4), activation=&#39;relu&#39;, input_shape=(64, 64, 1)),<br>            layers.BatchNormalization(),<br>            layers.MaxPool2D(pool_size=(2, 2)),<br>            layers.Conv2D(filters=256, kernel_size=(5, 5), strides=(1, 1), activation=&#39;relu&#39;, padding=&quot;same&quot;),<br>            layers.BatchNormalization(),<br>            layers.MaxPool2D(pool_size=(3, 3)),<br>            layers.Conv2D(filters=256, kernel_size=(3, 3), strides=(1, 1), activation=&#39;relu&#39;, padding=&quot;same&quot;),<br>            layers.BatchNormalization(),<br>            layers.Conv2D(filters=256, kernel_size=(1, 1), strides=(1, 1), activation=&#39;relu&#39;, padding=&quot;same&quot;),<br>            layers.BatchNormalization(),<br>            layers.Conv2D(filters=256, kernel_size=(1, 1), strides=(1, 1), activation=&#39;relu&#39;, padding=&quot;same&quot;),<br>            layers.BatchNormalization(),<br>            layers.MaxPool2D(pool_size=(2, 2)),<br>            layers.Flatten(),<br>            layers.Dense(1024, activation=&#39;relu&#39;),<br>            layers.Dropout(0.5),<br>            layers.Dense(1024, activation=&#39;relu&#39;),<br>            layers.Dropout(0.5),<br>            layers.Dense(1, activation=&#39;sigmoid&#39;)<br>        ])</pre><p>We can simply summarize this model,<br>1. Architecture:</p><ul><li>The model starts with a convolutional layer with 128 filters, a kernel size of (11, 11), and a stride of (4, 4).</li><li>Batch normalization is applied after each convolutional layer to improve training stability.</li><li>Max pooling layers with specified pool sizes are employed for downsampling.</li><li>The second convolutional layer has 256 filters, a kernel size of (5, 5), and padding to maintain spatial dimensions.</li><li>Another max pooling layer follows with a pool size of (3, 3).</li><li>Two additional convolutional layers with different kernel sizes and filter counts are applied, each followed by batch normalization.</li><li>Max pooling is again performed with a pool size of (2, 2).</li><li>The model is then flattened to prepare for fully connected layer</li></ul><p>2. Fully Connected Layers:</p><ul><li>Two dense layers with 1024 units and a ReLU activation function are included.</li><li>Dropout layers with a dropout rate of 0.5 are used after each dense layer to prevent overfitting.</li><li>The output layer has a single unit with a sigmoid activation function, suitable for binary classification.</li></ul><p>3. Optimizer and Loss:</p><ul><li>The Adam optimizer with a learning rate of 0.00001 is chosen.</li><li>Binary crossentropy is employed as the loss function, appropriate for binary classification tasks.</li></ul><p>Visualizing the model will look like this (<em>somehow we cannot use legend since it keeps stop working with ImageFont library</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*5Li1GNm8k3WhOuHltTE-gQ.png" /><figcaption>Model Visualization</figcaption></figure><p>Legends are follow:</p><ul><li>Yellow is Conv2D</li><li>Red is Maxpooling2D</li><li>Green is dropout</li><li>Blue is Flatten</li><li>Navy blue is Dense</li></ul><h4>Result</h4><p>Let’s now delve into the apparent outcomes obtained after training the Convolutional Neural Network (CNN) with our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*QieAuaWrLTIwLdizol1tJQ.png" /></figure><p>We have</p><ul><li>True Negative of 762 samples</li><li>False Negative of 52 samples</li><li>True Positive of 1222 samples</li><li>False Positive of 269 samples</li></ul><p>That makes precision, recall and F1-score of;</p><ul><li>Precision: Approximately 0.819</li><li>Recall: Approximately 0.959</li><li>F1-score: Approximately 0.883</li></ul><p>Now, let’s examine the graphs depicting loss versus iterations and accuracy versus iterations. Some of the insights can be offered upon observing this graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*w_ypYUHGDMieQNx8G1UKaA.png" /><figcaption>Loss and Accuracy vs Iterations</figcaption></figure><p>We can see that during the begining of training, the train loss started high while validation starts quit low. The loss of both training and validation keeps decreasing for each epochs. Based on the loss vs epochs/iterations graph we can conclude that validation fluctuated but with each epochs the loss decreases. In the end there’s a gap between validation loss and training loss. In the end validation loss is smaller than training loss. Overall we can say that the model generalizes well to new, unseen data, as evidenced by the lower validation loss. This also confirmed by the accuracy graph where in the end loss accuracy is higher than the training (approximately 0.80 vs 0.85).</p><h4>Inferencing With Real Data</h4><p>Now, we can proceed to utilize the pre-trained model for inference with real data. Specifically, we aim to test the model’s performance on eye images sourced from Google. We will use random images obtained through Google searches to evaluate how well the model generalizes to real-world data.</p><ul><li>1st case starts with a False Negative. The image belongs to male however model incorrectly predicts that this eye belongs to female.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*g4x1HCugliRv5ZFF3UEJ-A.png" /><figcaption>False Negative</figcaption></figure><ul><li>2nd case is True Positive, in which model correctly predicts that the eye belongs to a male</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Pta9rDTQySuNkTwe-eebQA.png" /><figcaption>True Positive</figcaption></figure><ul><li>3rd case is True Negative where model correctly predicts that the eye belongs to a female</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pvcJQKVfomcAJRGBRFwfNA.png" /><figcaption>True Negative</figcaption></figure><p><strong>Enclosing</strong></p><p>While the CNN demonstrates promising performance in predicting a person’s gender based on their eyes in image recognition, there is still room for improvement in this project. Considerations for enhancements include adjusting hyperparameters such as learning rate and batch size, particularly to address fluctuations in the validation data.</p><p>Here’s we leave link to <a href="https://github.com/Rian021102/eyes_gender_classification">github</a> for the code.</p><p>Here’s also several link to the paper that discuss leveraging deep learning in classifying sex based on eyes;</p><ul><li><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6689381/">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6689381/</a></li><li><a href="https://thescipub.com/pdf/jcssp.2023.345.362.pdf">https://thescipub.com/pdf/jcssp.2023.345.362.pdf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42d05d66ef71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression in Building Credit Scorecard]]></title>
            <link>https://medium.com/@rachmanto.rian/logistic-regression-in-building-credit-scorecard-924bece9f953?source=rss-b563db46863b------2</link>
            <guid isPermaLink="false">https://medium.com/p/924bece9f953</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[credit-score]]></category>
            <category><![CDATA[forward-selection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rian Rachmanto]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 05:19:17 GMT</pubDate>
            <atom:updated>2023-11-05T12:25:45.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6XTvT0q2ul-56s4U" /><figcaption>Photo by <a href="https://unsplash.com/@leekos?utm_source=medium&amp;utm_medium=referral">Kostiantyn Li</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>A credit score stands as a pivotal indicator, portraying the financial trustworthiness of an individual. In the financial landscape, it holds a pivotal role, serving as a fundamental yardstick employed by lenders and various financial institutions to meticulously gauge the level of risk associated with extending loans or other financial services. Within the confines of this blog, we endeavor to elucidate how the application of logistic regression, a powerful statistical tool, can be harnessed for the creation of a credit scorecard.</p><p>In pursuit of this objective, we used dataset sourced from Kaggle, (Dataset link: <a href="https://www.kaggle.com/datasets/laotse/credit-risk-dataset">https://www.kaggle.com/datasets/laotse/credit-risk-dataset</a>). It is essential to note that the credit scoring model we develop may deviate significantly from the conventional standards established within the industry. This blog simply explores the process in building credit scorecard using logistic regression. You can access the full source code in this github:</p><p><a href="https://github.com/Rian021102/credit-scoring-analysis">https://github.com/Rian021102/credit-scoring-analysis</a></p><h4>1. Load Dataset, split into train and test and perform EDA</h4><p>Following the dataset loading, our immediate action is to divide it into training and testing sets. At glance here’s our features and their meanings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*Z0knWQSbsfB2C-nuGn_hdg.png" /></figure><p>Subsequently, we delve into Exploratory Data Analysis (EDA), a critical step in which we investigate the dataset. This involves scrutinizing aspects such as missing data, how the data is spread out, summarizing statistics, identifying any unusual data points (outliers), and examining data correlation heatmap, among other valuable insights that EDA can provide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tqUzayywXbCyNDd6rIvW-Q.png" /><figcaption>Person age histogram hue loan_status</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CssS8IqCTAIsL1gS3q4Feg.png" /><figcaption>Person age boxplot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BMtAPny-DQxLm_4xl4mSkg.png" /><figcaption>Data correlation heatmap</figcaption></figure><h4>2. Characteristic Binning</h4><p>Characteristic binning, at its core, involves the process of grouping diverse attributes or traits that describe individuals or entities. These attributes encompass elements like income, age, credit history, and other pertinent factors. While these attributes play a vital role in assessing an individual’s creditworthiness, they frequently appear in different formats, such as numerical data or categorical labels. By subjecting these characteristics to binning, we streamline the intricacy of the data, rendering it more accessible and understandable.</p><pre>def create_binning(data, predictor_label, num_of_bins):<br>        &quot;&quot;&quot;<br>        Function for binning numerical predictor.<br><br>        Parameters<br>        ----------<br>        data : array like<br>        The name of dataset.<br><br>        predictor_label : object<br>        The label of predictor variable.<br><br>        num_of_bins : integer<br>        The number of bins.<br><br><br>        Return<br>        ------<br>        data : array like<br>        The name of transformed dataset.<br><br>        &quot;&quot;&quot;<br>        # Create a new column containing the binned predictor<br>        data[predictor_label + &quot;_bin&quot;] = pd.qcut(data[predictor_label],<br>                                                q = num_of_bins)<br><br>        return data<br>    for column in num_columns:<br>        data_train_binned = create_binning(data = data_train,<br>                                        predictor_label = column,<br>                                        num_of_bins = 4)<br>    print(data_train_binned.T)<br>    print(data_train_binned.isna().sum())<br>    # # Define columns with missing values<br>    # missing_columns = [&#39;person_emp_length_bin&#39;,<br>    #                    &#39;loan_int_rate_bin&#39;,<br>    #                    &#39;cb_person_cred_hist_length_bin&#39;]<br><br>    # Define columns with missing values<br>    missing_columns = [&#39;person_emp_length_bin&#39;,<br>                       &#39;loan_int_rate_bin&#39;]<br>    <br>    # Perform grouping for all columns<br>    for column in missing_columns:<br><br>        # Add category &#39;Missing&#39; to replace the missing values<br>        data_train_binned[column] = data_train_binned[column].cat.add_categories(&#39;Missing&#39;)<br><br>        # Replace missing values with category &#39;Missing&#39;<br>        data_train_binned[column].fillna(value = &#39;Missing&#39;,<br>                                        inplace = True)<br>    print(data_train_binned.T)<br>    return data_train_binned</pre><p>Characteristic binning can provide a way to handle missing data by creating a separate category for missing values as shown in function code above. By creating specific bins or categories dedicated to missing data, we ensure that no valuable information is lost.</p><h4>3. Weight of Evidence and Information Value (WoE and IV)</h4><p>In the process of building a credit scorecard, two important concepts come into play: Weight of Evidence (WOE) and Information Value (IV). These statistical techniques are integral for evaluating the predictive power of individual characteristics in credit scoring models.</p><p>WoE is measurement of predictive power of each attributes in characteristic while IV is the measurement of total strength of a characteristic</p><p>WoE can be formulated as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*mq8SIWMurtj7KuWT3Qxm1w.png" /></figure><p>While Information Value (IV) can be formulated as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*QgfU5yy7uq7hc-GeCDdU5A.png" /></figure><p>And we can use this function to for our WoE and IV</p><pre>def create_woe_iv(crosstab_list):<br>    num_columns = [&#39;person_age&#39;,<br>                   &#39;person_income&#39;,<br>                   &#39;person_emp_length&#39;,<br>                   &#39;loan_amnt&#39;,<br>                   &#39;loan_int_rate&#39;,<br>                   &#39;loan_percent_income&#39;,<br>                   &#39;cb_person_cred_hist_length&#39;]<br><br><br>    # Define data with categorical predictors<br>    cat_columns = [&#39;person_home_ownership&#39;,<br>                   &#39;loan_intent&#39;,<br>                   &#39;loan_grade&#39;,<br>                   &#39;cb_person_default_on_file&#39;]<br>    <br>    # Define the initial list for WOE<br>    WOE_list = []<br><br>    # Define the initial list for IV<br>    IV_list = []<br><br>    #Create the initial table for IV<br>    IV_table = pd.DataFrame({&#39;Characteristic&#39;: [],<br>                             &#39;Information Value&#39; : []})<br><br>    # Perform the algorithm for all crosstab<br>    for crosstab in crosstab_list:<br><br>    # Calculate % Good<br>        crosstab[&#39;p_good&#39;] = crosstab[0]/crosstab[0][&#39;All&#39;]<br><br>        # Calculate % Bad<br>        crosstab[&#39;p_bad&#39;] = crosstab[1]/crosstab[1][&#39;All&#39;]<br><br>        # Calculate the WOE<br>        crosstab[&#39;WOE&#39;] = np.log(crosstab[&#39;p_good&#39;]/crosstab[&#39;p_bad&#39;])<br><br>        # Calculate the contribution value for IV<br>        crosstab[&#39;contribution&#39;] = (crosstab[&#39;p_good&#39;]-crosstab[&#39;p_bad&#39;])*crosstab[&#39;WOE&#39;]<br><br>        # Calculate the IV<br>        IV = crosstab[&#39;contribution&#39;][:-1].sum()<br><br>        add_IV = {&#39;Characteristic&#39;: crosstab.index.name,<br>                  &#39;Information Value&#39;: IV}<br><br>        WOE_list.append(crosstab)<br>        IV_list.append(add_IV)<br>    print(IV_list)<br>    print(WOE_list)<br>    return IV_list,WOE_list</pre><p>WoE list then is transformed into WoE table that looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*soicjl64mCqtGgcyvdTqWg.png" /></figure><p>While since IV is summation of strength in characteristic, we can use this rule of thumb by Naeem Siddiqi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YuKU7D4LQm4zW4JH.png" /></figure><p>Hence we have our Information Value as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*jM5Kr-fUDse6paeIM2Xh2g.png" /><figcaption>Information Value of Each Characteristic</figcaption></figure><h4>4. Forward Selection Using Logistic Regression</h4><p>Forward selection is a type of stepwise regression, where we start with no variables in the model, then add variables one-by-one, at each step adding the variable that improves the model the most, until no other variables improve the model significantly. We start first with function for forward selection</p><pre>def forward(X, y, predictors, scoring=&#39;roc_auc&#39;, cv=5):<br>    <br>    # Initialize list of results<br>    results = []<br><br>    # Define sample size and  number of all predictors<br>    n_samples, n_predictors = X.shape<br><br>    # Define list of all predictors<br>    col_list = np.arange(n_predictors)<br><br>    # Define remaining predictors for each k<br>    remaining_predictors = [p for p in col_list if p not in predictors]<br><br>    # Initialize list of predictors and its CV Score<br>    pred_list = []<br>    score_list = []<br><br>    # Cross validate each possible combination of remaining predictors<br>    for p in remaining_predictors:<br>        combi = predictors + [p]<br><br>        # Extract predictors combination<br>        X_ = X[:, combi]<br>        y_ = y<br><br>        # Define the estimator<br>        model = LogisticRegression(penalty = None,<br>                                   class_weight = &#39;balanced&#39;)<br><br>        # Cross validate the recall scores of the model<br>        cv_results = cross_validate(estimator = model,<br>                                    X = X_,<br>                                    y = y_,<br>                                    scoring = scoring,<br>                                    cv = cv)<br><br>        # Calculate the average CV/recall score<br>        score_ = np.mean(cv_results[&#39;test_score&#39;])<br><br>        # Append predictors combination and its CV Score to the list<br>        pred_list.append(list(combi))<br>        score_list.append(score_)<br><br>    # Tabulate the results<br>    models = pd.DataFrame({&quot;Predictors&quot;: pred_list,<br>                           &quot;Recall&quot;: score_list})<br><br>    # Choose the best model<br>    best_model = models.loc[models[&#39;Recall&#39;].argmax()]<br><br>    return models, best_model</pre><p>And next we perform forward selection for different numbers of predictors and keeps track of the best models and their associated predictors and recall scores. It serves as a step in the process of determining the optimal set of predictors for a predictive model.</p><pre>def list_predictors(X_train,y_train,forward_models):<br>    # Define list of predictors<br>    predictors = []<br>    n_predictors = X_train.shape[1]<br><br>    # Perform forward selection procedure for k=1,...,11 predictors<br>    for k in range(n_predictors):<br>        _, best_model = forward(X = X_train,<br>                                y = y_train,<br>                                predictors = predictors,<br>                                scoring = &#39;recall&#39;,<br>                                cv = 10)<br><br>        # Tabulate the best model of each k predictors<br>        forward_models.loc[k+1] = best_model<br>        predictors = best_model[&#39;Predictors&#39;]<br>    print(forward_models)<br>    return forward_models, predictors</pre><h4>5. Scaling and Creating Scorecard</h4><p>The term “scaling scorecard” encompasses the spectrum and configuration of scores within a scorecard, along with the rate at which odds change when scores increase. In mathematical form can be described as:</p><blockquote>Score + pdo = Offset + Factor * log (2 * odds of good)</blockquote><p>Where pdo refers to points to double to odds. While Factor and Offset can be described as follow:</p><blockquote>Factor = pdo/log(2)</blockquote><blockquote>Offset = Score — [Factor * ln(odds of good)</blockquote><p>In this case we use base score of 1000, base odds of 35, pdo of 80 and rate 2 (referring to this blog by Bruce Yang):</p><p><a href="https://towardsdatascience.com/end-to-end-guide-to-building-a-credit-scorecard-using-machine-learning-6502d8bb765a">End-to-End Guide to Building a Credit Scorecard Using Machine Learning</a></p><p>And this is the scorecard after scaling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fv05g2Rd05WxPcgsfRWWsQ.png" /><figcaption>Scorecard after scaling</figcaption></figure><p>Now to wrap things up, we can set cut off base on the characteristic. There are numbers of cut off can be applied, but for this particular project we used this cut off ;</p><blockquote>Score below 250 defined as Very Poor</blockquote><blockquote>Score between 250 and 300 defined as Poor</blockquote><blockquote>Score between 300 and 400 defined as Fair</blockquote><blockquote>Score between 400 and 500 defined as Good</blockquote><blockquote>Score between 500 and 600 defined as Very Good</blockquote><blockquote>Score between 600 and 700 defined as Exceptional</blockquote><blockquote>and Score above 700 defined as Excellent</blockquote><p>The last step in this project involves deployment. We’ve preserved the scorecard as a pickle file named “scorecards.pkl” and are hosting the model using FastAPI, making it accessible on Heroku.</p><p><a href="https://creditscorecard-670abc4179ee.herokuapp.com/docs">FastAPI - Swagger UI</a></p><p>And you can try this simple streamlit app as front end that makes request to API here:</p><p><a href="https://creditscorecard.streamlit.app/">https://creditscorecard.streamlit.app/</a></p><p>That’s it. The end result is not perfect since and there might require some revision in the future, but the objective of this blog is to encapsulate the process in creating credit scorecard. We hope you enjoy this piece and thank you for taking your time reading this blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=924bece9f953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Data Extraction to Dashboard: A Streamlined End-to-End Machine Learning Journey]]></title>
            <link>https://medium.com/@rachmanto.rian/from-data-extraction-to-dashboard-a-streamlined-end-to-end-machine-learning-journey-c3cc3d309f67?source=rss-b563db46863b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3cc3d309f67</guid>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[extract-transform-load]]></category>
            <category><![CDATA[heroku-deployment]]></category>
            <dc:creator><![CDATA[Rian Rachmanto]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 12:13:06 GMT</pubDate>
            <atom:updated>2023-10-30T03:27:39.432Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Leveraging OpenWeather Air Pollution API, BigQuery, Python, Heroku, and Looker Data Studio for Seamless Data Processing and Visualization</blockquote><p>This article discusses the idea of making machine learning practical, so anyone, from individuals to organizations, can use it to solve real-world problems. Whether it’s spotting credit card fraud or detecting hate speech in media using NLP techniques, we explore how machine learning, when presented as a ready-to-use solution, becomes versatile. In this article, we walk through a step-by-step project, starting with collecting data from the OpenWeather Air Pollution API, training a model, deploying it with Heroku, making predictions, storing those predictions in BigQuery, and finally, creating a user-friendly dashboard.</p><h4>Project Objective</h4><p>In this project, our main goal is to use the OpenWeather air pollution API to predict the air quality in a specific location, which, in our case, is Balikpapan. We’ll first train the model and then put it to work on Heroku as an API using fastapi. This API will help us make real-time air quality predictions, and we’ll store this information in BigQuery. Finally, we’ll use all this data to create a dashboard with Looker Data Studio. At this point, we assume that you have a basic understanding of how to use Heroku, BigQuery, and Looker Data Studio.</p><h4>Data Extraction, Transform and Load</h4><p>OpenWeather is an online platform that delivers global weather data using an API. In this project, we make use of the Air Pollution API to access both historical and current data, each serving a specific purpose. The historical data is utilized for training, while the current data is employed for making predictions.</p><p>To retrieve historical data, we make API requests using the following format:</p><pre>http://api.openweathermap.org/data/2.5/air_pollution/history?lat={lat}&amp;lon={lon}&amp;start={start}&amp;end={end}&amp;appid={API key}</pre><p>In these requests, we provide latitude, longitude, start time in Unix format, end time also in Unix format, and the required API key. The API responds with data in JSON format, which we then convert into a DataFrame. For training purposes, we save this DataFrame as a CSV file and additionally store it in BigQuery. Below, we provide a Python script that demonstrates how to extract historical data from OpenWeather, transform it into a DataFrame, and save as csv file, that we will use as train data for latter on.</p><pre># Replace &#39;your_api_key&#39; with the API key you&#39;ve been provided<br>api_key = &#39;e86609410bde86678446df12a768d48e&#39;<br><br># Define the start and end dates as Unix timestamps<br>start_date = datetime(2019, 1, 1, 0, 0).timestamp()  # January 1, 2019<br>end_date = datetime(2023, 11, 27, 23, 59).timestamp()  # September 30, 2023<br><br># Replace the latitude and longitude with Jakarta&#39;s coordinates<br>url = f&#39;http://api.openweathermap.org/data/2.5/air_pollution/history?lat=-1.2676&amp;lon=116.8270&amp;start={int(start_date)}&amp;end={int(end_date)}&amp;appid={api_key}&#39;<br><br><br># Send a GET request to the API<br>response = requests.get(url)<br><br># Check if the request was successful (status code 200)<br>if response.status_code == 200:<br>    data = response.json()<br>    <br>    # Transform the JSON data into a DataFrame<br>    df = pd.json_normalize(data[&#39;list&#39;])<br><br>    # Convert the dt column into a datetime object<br>    df[&#39;dt&#39;] = pd.to_datetime(df[&#39;dt&#39;], unit=&#39;s&#39;)<br><br>    df.to_csv(&#39;/Users/rianrachmanto/pypro/project/BalikpapanAirQ/data/Balikpapan_air_q.csv&#39;,index=False)<br>    <br>    # Process the DataFrame as needed<br>    print(df)<br>    <br>else:<br>    # If the request was not successful, print an error message<br>    print(f&quot;Error: {response.status_code} - {response.text}&quot;)</pre><p>Both the historical and current data we gather contain a particular variable referred to as “main.aqi.” This variable serves as an indicator of air quality at a given time and is categorized into levels 1, 2, 3, 4, and 5. These categories correspond to “Good,” “Fine,” “Medium,” “Poor,” and “Very Poor,” respectively. We will use this data to create a new variable named “air_quality,” which will serve as the target variable for our analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tw146XR08XL8DvbiMzswcg.png" /><figcaption>Extracted Historical Air Quality of Balikpapan as CSV</figcaption></figure><p>Furthermore, we’ve created an additional script to save the transformed data into BigQuery. This script facilitates the data transfer to BigQuery through the use of pandas_gbq. This stored data can serve multiple purposes, acting as both a training dataset and as the basis for constructing a dashboard in Looker Data Studio at a later stage.</p><pre>if response.status_code == 200:<br>    data = response.json()<br><br>    # Transform the JSON data into a DataFrame<br>    df = pd.json_normalize(data[&#39;list&#39;])<br><br>    df=processdata(df)<br><br>    <br>    # Initialize a BigQuery client<br>    client = bigquery.Client()<br><br>    # Define the BigQuery dataset and table where you want to load the data<br>    project_id = &#39;intricate-idiom-379506&#39;<br>    table_id = &#39;balikpapanairquality.balikpapanpollution&#39;<br><br>    table_schema=[<br>    {&#39;name&#39;: &#39;dt&#39;, &#39;type&#39;: &#39;TIMESTAMP&#39;},<br>    {&#39;name&#39;: &#39;co&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},  # Adjust the data types for other columns as needed<br>    {&#39;name&#39;: &#39;no2&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>    {&#39;name&#39;: &#39;o3&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>    {&#39;name&#39;: &#39;so2&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>    {&#39;name&#39;: &#39;pm2_5&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>    {&#39;name&#39;: &#39;air_quality&#39;, &#39;type&#39;: &#39;STRING&#39;},<br>    ]<br><br>    # Load the DataFrame into BigQuery with &quot;append&quot; mode<br>    pandas_gbq.to_gbq(df,table_id,project_id,if_exists=&#39;replace&#39;,table_schema=table_schema)<br>    # Process the DataFrame as needed<br>    print(df)<br>    <br>else:<br>    # If the request was not successful, print an error message<br>    print(f&quot;Error: {response.status_code} - {response.text}&quot;)</pre><h4>Train and Model Deployment To Heroku</h4><p>The training dataset is subsequently divided into training and testing datasets, allowing for exploratory data analysis (EDA) to be performed on the training dataset. Data preprocessing tasks include handling missing values, addressing outliers, and label encoding the target variable, if required. Following these steps, the data is ready for model training. In this particular instance, we have developed a custom function to train an XGBoost model.</p><p>After successfully training the model, we proceed to deploy it using Fastapi on the Heroku platform. The Fastapi application comprises three critical components: code for retrieving the current data from OpenWeather, making predictions utilizing the trained model, and storing the resulting predictions in BigQuery.</p><pre>app = FastAPI()<br><br>def processdata(df):<br>    # Convert &#39;dt&#39; to datetime<br>    df[&#39;dt&#39;] = pd.to_datetime(df[&#39;dt&#39;], unit=&#39;s&#39;)<br><br>    # Change column names from components.co to co, components.no to no, and so on<br>    df = df.rename(columns={&#39;components.co&#39;: &#39;co&#39;, &#39;components.no&#39;: &#39;no&#39;, &#39;components.no2&#39;: &#39;no2&#39;, &#39;components.o3&#39;: &#39;o3&#39;,<br>                            &#39;components.so2&#39;: &#39;so2&#39;, &#39;components.pm2_5&#39;: &#39;pm2_5&#39;, &#39;components.pm10&#39;: &#39;pm10&#39;,<br>                            &#39;components.nh3&#39;: &#39;nh3&#39;})<br>    # Drop the &#39;main.aqi&#39; column<br>    df.drop(columns=[&#39;main.aqi&#39;], axis=1, inplace=True)<br><br>    # Remove no, pm10, dt, and nh3 columns if they exist<br>    columns_to_remove = [&#39;no&#39;, &#39;pm10&#39;,&#39;nh3&#39;]<br>    df.drop(columns=columns_to_remove, axis=1, inplace=True, errors=&#39;ignore&#39;)<br><br>    return df<br><br>@app.post(&quot;/predict&quot;)<br>async def predict_air_quality():<br>    api_key = os.environ.get(&#39;OPENWEATHER_API_KEY&#39;)<br>    <br>    # Ensure that the GOOGLE_CREDENTIALS environment variable is set<br>    if &quot;GOOGLE_CREDENTIALS&quot; not in os.environ:<br>        return {&quot;error&quot;: &quot;GOOGLE_CREDENTIALS environment variable not set.&quot;}<br><br>    # Parse the Google Service Account JSON key<br>    google_credentials = json.loads(os.environ[&quot;GOOGLE_CREDENTIALS&quot;])<br><br>    # Configure the credentials using google-auth<br>    credentials = service_account.Credentials.from_service_account_info(google_credentials)<br>    <br>    url = f&#39;http://api.openweathermap.org/data/2.5/air_pollution?lat=-1.2676&amp;lon=116.8270&amp;appid={api_key}&#39;<br>    response = requests.get(url)<br><br>    # Check if the request was successful (status code 200)<br>    if response.status_code == 200:<br>        data = response.json()<br><br>        # Transform the JSON data into a DataFrame<br>        df = pd.json_normalize(data[&#39;list&#39;])<br><br>        # Convert the dt column into a datetime object<br>        df[&#39;dt&#39;] = pd.to_datetime(df[&#39;dt&#39;], unit=&#39;s&#39;)<br><br>        df = processdata(df)<br>        df2 = df.copy()<br>        df2.drop(columns=[&#39;dt&#39;], axis=1, inplace=True)<br><br>        # Load the model<br>        model = model = joblib.load(&quot;model.pkl&quot;)<br><br>        # Make predictions<br>        predictions = model.predict(df2)<br><br>        # Map numeric predictions to air quality categories<br>        if predictions == 0:<br>            predictions = &#39;Good&#39;<br>        elif predictions == 1:<br>            predictions = &#39;Fine&#39;<br>        elif predictions == 2:<br>            predictions = &#39;Medium&#39;<br>        elif predictions == 3:<br>            predictions = &#39;Poor&#39;<br>        else:<br>            predictions = &#39;Very Poor&#39;<br><br>        df[&#39;air_quality&#39;] = predictions<br><br>        # Define the BigQuery dataset and table where you want to load the data<br>        project_id = &#39;intricate-idiom-379506&#39;<br>        table_id = &#39;balikpapanairquality.balikpapanpollution&#39;<br><br>        table_schema = [<br>            {&#39;name&#39;: &#39;dt&#39;, &#39;type&#39;: &#39;TIMESTAMP&#39;},<br>            {&#39;name&#39;: &#39;co&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>            {&#39;name&#39;: &#39;no2&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>            {&#39;name&#39;: &#39;o3&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>            {&#39;name&#39;: &#39;so2&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>            {&#39;name&#39;: &#39;pm2_5&#39;, &#39;type&#39;: &#39;FLOAT64&#39;},<br>            {&#39;name&#39;: &#39;air_quality&#39;, &#39;type&#39;: &#39;STRING&#39;},<br>        ]<br><br>        # Load the DataFrame into BigQuery with &quot;append&quot; mode<br>        pandas_gbq.to_gbq(df, table_id, project_id, if_exists=&#39;append&#39;, table_schema=table_schema, credentials=credentials)<br><br>        return df.to_dict(orient=&#39;records&#39;)<br><br>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br><br>    # Use uvicorn to run the FastAPI application on 127.0.0.1 and port 8000<br>    uvicorn.run(&quot;app:app&quot;, host=&#39;0.0.0.0&#39;, port=int(os.environ.get(&#39;PORT&#39;, 8080)))</pre><p>In this particular scenario, we opt for Heroku as our deployment platform. The process of deploying an application on Heroku is relatively straightforward. You simply need to create a new app, provide it with a unique name to ensure availability, and then proceed with the deployment. Heroku offers three deployment methods, and in this case, we select the option to connect to our GitHub repository and enable automatic deployment. This setup means that each time you push changes to your GitHub repository, Heroku will automatically deploy your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8uV3nqxwwGuMsCf1j_Dzw.png" /><figcaption>Automatic Deployment to Heroku by Connecting to GitHub Repository</figcaption></figure><p>One of the remarkable advantages of Fastapi is the built-in user interface it provides. This user interface not only simplifies the process of making predictions but also offers an intuitive platform for immediate interaction with your model. You can seamlessly initiate predictions using this interface or, if you prefer more programmatic control, you have the flexibility to utilize request methods, ensuring that Fastapi caters to a wide range of user preferences and requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9h5YtBkv2wIjBlBX5J2Tw.png" /><figcaption>Fastapi Swagger User Interface</figcaption></figure><h4>Building Dashboard with Looker Data Studio</h4><p>With the historical and current data, including the predictions already stored in BigQuery, the next step is to simply query the data and construct the dashboard using Google Looker Data Studio. The resulting dashboard will continuously display real-time information every time you run an inference using Fastapi, ensuring that it remains up to date and constantly refreshed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOAhjxMafKanYU6nj7-7Mw.png" /><figcaption>Dashboard for Balikpapan Air Pollution Monitoring</figcaption></figure><h4>Automate the whole things with Heroku Scheduler Adds On</h4><p>Heroku provides an adds on called scheduler that we can use to schedule our apps to perform certain works (every 1 minute, every hour, every day or even every month). We simply developed a simple Python script to make request to the Fastapi that deployed on Heroku.</p><pre>import requests<br>import time<br><br>api_url = &#39;https://airpredbal-20720b5bac6d.herokuapp.com/predict&#39;<br>data = {&quot;input_data&quot;: &quot;Your_input_data&quot;}<br><br># Set the number of retries and delay between retries<br>max_retries = 3<br>retry_delay = 5<br><br>for retry in range(max_retries):<br>    response = requests.post(api_url, json=data)<br>    <br>    if response.status_code == 200:<br>        result = response.json()<br>        print(&quot;The prediction is:&quot;, result)<br>        break  # Successful response, exit the loop<br>    else:<br>        print(f&quot;Attempt {retry + 1}: Error code {response.status_code}&quot;)<br>        print(response.text)<br><br>    if retry &lt; max_retries - 1:<br>        print(f&quot;Retrying in {retry_delay} seconds...&quot;)<br>        time.sleep(retry_delay)<br>    else:<br>        print(&quot;Maximum retries reached. Exiting.&quot;)</pre><p>You can start your Scheduler adds on using CLI</p><pre>heroku addons:create scheduler:standard -a your_heroku_app</pre><p>And also using CLI to open your scheduler</p><pre>heroku addons:open scheduler -a your_heroku_app</pre><p>After that you can set enter job you want (in our case will be python app.py to execute the script), set the interval time (we choose daily at UTC 02:00 or it’s equal to UTC +8)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcIBnEi1x1pyuOgkHqT5hA.png" /><figcaption>Configuring Heroku Scheduler</figcaption></figure><p>That’s a wrap! In our complete machine learning project, we collected data using an API, fixed it up, taught our model with the improved data, saved everything in a data storage place, and then used it to create a dashboard.</p><p>For complete code you can access here:</p><p><a href="https://github.com/Rian021102/airqualityopenwr">GitHub - Rian021102/airqualityopenwr</a></p><p>For the FastAPI apps on Heroku you can access here:</p><p><a href="https://airpredbal-20720b5bac6d.herokuapp.com/docs">FastAPI - Swagger UI</a></p><p>And you can access the Dashboard here:</p><p><a href="https://lookerstudio.google.com/s/uHUWeiS-OEU">Easily Build Custom Reports and Dashboards - Looker Studio</a></p><p>We genuinely appreciate you taking the time to read this. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3cc3d309f67" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>