<?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 Alex Yeo on Medium]]></title>
        <description><![CDATA[Stories by Alex Yeo on Medium]]></description>
        <link>https://medium.com/@alex-yeo?source=rss-8a60e34ce17e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ufyyAlJMESW7AYqT.jpg</url>
            <title>Stories by Alex Yeo on Medium</title>
            <link>https://medium.com/@alex-yeo?source=rss-8a60e34ce17e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:16:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex-yeo/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[abnormally detection Using statistical Method]]></title>
            <link>https://alex-yeo.medium.com/abnormally-detection-using-statistical-method-bd132b31c3e6?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd132b31c3e6</guid>
            <category><![CDATA[abnormal]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 15:26:59 GMT</pubDate>
            <atom:updated>2025-06-15T15:26:59.812Z</atom:updated>
            <content:encoded><![CDATA[<p>Abnormality detection is a common challenge across all industries. Fraudulent activities or unexpected behavior can cause serious damage to a company — ranging from financial losses and operational disruption to, in the worst cases, complete business shutdown. As a result, most companies build internal systems to monitor unusual behavior and send timely alerts to managers before issues escalate.</p><p>In this article, I’ll introduce one of the simplest forms of abnormality detection systems, built using a moving average, moving standard deviation, and p-value. This system can be implemented within a week and provides a basic yet effective safeguard for any organization.</p><p>At the core of any abnormality detection system is the goal of identifying <strong>outliers</strong>. For example, suppose you typically spend around $3 per day, but on one day, you suddenly spend $18. That’s a suspicious behavior — it could mean someone else accessed your account. If an alert system notifies you immediately, you’d likely double-check your activity. That’s a straightforward example. But what if your spending gradually increases from $3 to $18 over six months, then drops to $9 over the next six months? Should that still be considered abnormal?</p><p>It depends on the context. If the increase is due to a new subscription service with tiered pricing, it’s probably normal. But if you didn’t subscribe to anything and your spending continues to rise without explanation, you might want an alert to investigate. That’s why an effective abnormality detection system needs a mechanism to adjust its sensitivity based on context and tolerance.</p><p>In our system, <strong>p-value</strong> serves as this adjustment mechanism. It quantifies the likelihood that an observed data point is significantly different from the expected range. By setting a threshold (e.g., p-value &lt; 0.01), the system can flag potential anomalies with statistical confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hEr-CvM8KAzcTY95uc6dw.png" /></figure><p>Let’s quickly recap the concept of a <strong>normal distribution</strong> using a simple example. Suppose your daily spending is usually around $3, and it typically fluctuates between $2 and $4. Occasionally, however, you might spend as much as $18 on a single day.</p><p>Now let’s map these everyday observations to their corresponding statistical terms:</p><ul><li><strong>“$3 most of the time”</strong> corresponds to the <strong>mean</strong> (average value).</li><li><strong>“Fluctuation between $2 and $4”</strong> represents the <strong>standard deviation</strong> (a measure of how spread out your values are).</li><li><strong>“Occasionally spending $18”</strong> is an example of a value with a high <strong>z-score</strong> (a measurement of how far a value is from the mean in terms of standard deviations).</li></ul><p>These statistical terms have well-defined formulas, which we’ll cover next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*ImyscKmspA1RVxbCwdbgIQ.png" /></figure><p>We can visualize the formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRnL_r7vaLRqab8X7IhNMA.png" /></figure><p>The z-score tells us how many standard deviations the observed value is from the mean. A corresponding <strong>p-value</strong> is derived, representing the probability that a value from a normal distribution is more extreme than the observed z-score. If the <strong>p-value is less than 0.01</strong>, the observed value is considered <strong>statistically abnormal or an outlier</strong>. The graph visualizes this process, showing the bell curve of a normal distribution, the location of the z-score, and the tail area representing the p-value — highlighted in color and labeled as an outlier or abnormal region when it falls below the 0.01 threshold.</p><p>Using this simple statistical method, we can create a simple yet effective abnormal detection system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd132b31c3e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Web-services with Nginx, Certbot & FastAPI]]></title>
            <link>https://alex-yeo.medium.com/setup-web-services-with-nginx-certbot-fastapi-3621192a2ae5?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3621192a2ae5</guid>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[web-services]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 09:31:39 GMT</pubDate>
            <atom:updated>2025-06-09T09:31:39.601Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XII8H0sdJnfaNtb_TUC1aA.png" /></figure><p>Setting up a modern web service today involves more than just writing backend code — you need a solid stack that handles routing, performance, and security. In this post, we’ll walk through deploying a <strong>FastAPI</strong> application behind <strong>Nginx</strong>, and securing it with <strong>SSL certificates via Certbot</strong>.</p><p>This stack is perfect for developers who want high performance (FastAPI), reliability (Nginx), and HTTPS (Certbot). Whether you’re deploying a REST API, a backend for a frontend app, or a microservice, this guide will help you get it production-ready.</p><h3>Steps</h3><p><strong>Setup Web Server (NGINX).</strong></p><blockquote>A web server like <strong>Nginx</strong> plays a vital role in deploying and managing modern web applications. It listens on standard web ports (like 80 and 443) and forwards incoming requests to your FastAPI application running on an internal port (e.g., 8000). It efficiently manages high volumes of simultaneous connections, improving performance and scalability. Nginx also handles <strong>SSL termination</strong>, meaning it manages HTTPS connections and works seamlessly with tools like <strong>Certbot</strong> to provide free and automated SSL certificates, ensuring your site is secure. From a security standpoint, Nginx adds a protective layer, allowing you to set up rate limits, IP restrictions, and other filtering mechanisms to protect your backend. It can also be used for load balancing and routing traffic between multiple backend services, making it indispensable for building robust and scalable web services.</blockquote><ul><li>First, run terminal command/SSH into your server and Install Nginx:</li></ul><pre>sudo apt install nginx -y</pre><ul><li>Once the web server is installed, we can configure the web server setting to redirect to different files/services by creating a setting file in this location: <strong>/etc/nginx/sites-available/</strong></li></ul><pre>sudo touch /etc/nginx/sites-available/services<br>sudo vim /etc/nginx/sites-available/services</pre><ul><li>inside the services file, we can put in this content:</li></ul><pre>server {<br>    listen 80;<br>    server_name yourdomain.com www.yourdomain.com;<br><br>    location /fastapi/ {<br>        proxy_pass http://127.0.0.1:8000;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><ul><li>The setting is configured to listen on port <strong>80</strong>, which handles standard <strong>HTTP traffic</strong>, and responds to requests directed at the domain yourdomain.com or www.yourdomain.com. It defines a <strong>location block</strong> for any URL path starting with /fastapi/. When such a request is received (<strong>www.yourdomain.com/fastapi</strong>), Nginx <strong>forwards (proxies)</strong> it to a FastAPI application running locally on 127.0.0.1:8000. The proxy_pass directive handles the actual redirection, while the proxy_set_header lines ensure that important client request headers—such as the original host, real IP address, and protocol—are preserved and passed along to the backend application. This allows FastAPI to receive accurate information about the client making the request, which is useful for logging, security, and response customization. Overall, this configuration makes Nginx act as a <strong>gateway</strong>, exposing the FastAPI app under the /fastapi/ URL path while keeping the application itself isolated on an internal port.</li><li>Once we are satisfied with the service, we can Enable the configuration and test it with the following commands.</li></ul><pre>sudo ln -s /etc/nginx/sites-available/services /etc/nginx/sites-enabled/services<br>sudo nginx -t<br>sudo systemctl restart nginx</pre><p><strong>Setup FastAPI services</strong></p><ul><li>After setting up the web server with the FastAPI configuration, we can setup FastAPI services.</li></ul><pre>pip install fastapi uvicorn</pre><ul><li>Create a simple FastAPI app in main.py:</li></ul><pre># main.py<br>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>def read_root():<br>    return {&quot;message&quot;: &quot;Hello, world!&quot;}</pre><ul><li>launch the FastAPI web service:</li></ul><pre>fastapi dev main.py --root-path /fastapi</pre><ul><li>Once the FastAPI is launched, we can call the FastAPI service by sending a http request (<strong>http://www.yourdomain.com/fastapi</strong>).</li></ul><p><strong>Setup SSL for Web service</strong></p><ul><li>To make sure the communication of the web service is encrypted, we can run Certbot to get an SSL certificate and automatically configure Nginx:</li><li>Install Certbot and the Nginx plugin:</li></ul><pre>sudo apt install certbot python3-certbot-nginx -y</pre><pre>sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com</pre><ul><li>Follow the prompts to agree to terms and select redirection to HTTPS.</li><li>Verify that the certificate works:</li></ul><pre>sudo certbot renew --dry-run</pre><p><strong>Optional: Set Up Auto-Renewal</strong></p><ul><li>Certbot installs a cron job by default for automatic renewal. You can verify it with:</li></ul><pre>systemctl list-timers | grep certbot</pre><h3>Conclusion</h3><p>You’ve now successfully deployed a FastAPI application in production using Nginx and secured it with a free SSL certificate via Certbot. This setup gives you:</p><ul><li>A fast backend powered by FastAPI</li><li>A robust, scalable reverse proxy with Nginx</li><li>HTTPS encryption out-of-the-box with Certbot</li></ul><p>This setup is scalable, secure, and perfect for real-world deployments. You can further enhance it by adding Docker, CI/CD, monitoring, and database integrations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3621192a2ae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Affordable Webservice: Serverless services]]></title>
            <link>https://alex-yeo.medium.com/affordable-webservice-serverless-services-8848967c454b?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8848967c454b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[application]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 06:08:53 GMT</pubDate>
            <atom:updated>2025-06-09T06:08:53.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVncIek5rXL6ussNRTatEw.png" /></figure><p>Serverless services like <strong>Azure Functions</strong> provide a cost-efficient way to deploy web services by eliminating server management and c<strong>harging only for actual compute time</strong>. These event-driven solutions automatically scale with demand, making them ideal for APIs, microservices, and real-time data processing. With support for multiple programming languages and seamless integration with cloud services, serverless computing simplifies development while reducing infrastructure costs. Though best suited for short-lived tasks due to execution time limits, its pay-per-use model and auto-scaling capabilities make it a budget-friendly choice for modern, scalable applications. By adopting serverless architecture, businesses can focus on code rather than infrastructure, optimizing both performance and cost.</p><p>One of the easy ways to setup service is by using Visual Studio Code. The following sections will describe the steps in deploying web services to Microsoft Azure Functions.</p><h3>Environment Setup</h3><p>There are 3 pre-requisite tools that we need to install in order to deploy web services.</p><ul><li>Install Visual Studio Code</li><li>Install Azure function Core Tool. Click <a href="https://github.com/Azure/azure-functions-core-tools">here</a> to download.</li><li>Install Visual Studio Code Extensions; Azure Function and Azurite</li></ul><h3>Create and Deploy a basic HTTP request Trigger Function (API)</h3><p><strong>Create a local Project. This can be done by</strong></p><ul><li>Pressing <strong>F1 (fn+F1 for MacBook users)</strong> and search for <strong>Azure Functions: Create New Project…</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4y5ijCUUQiYFI1xQCoiwg.png" /></figure><ul><li>Multiple questions will be asked to create a new function. Please follow thet following table</li><li>A <strong>function_app.py </strong>file will be created as shown below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYgqTywVu6DAJOXJOOyaHw.png" /></figure><p>Start the Emulator (Run Azure Function Locally)</p><ul><li>Press F1 (Fn + F1 for MacBook users) again and select Azurite Start</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNviwysCdRbAcRhr_q8YBg.png" /></figure><p><strong>Run Azure Function Locally</strong></p><ul><li>Press F5 (Fn+F5 for MacBook users) to run the function.</li><li>The local API service will be shown in the terminal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5l5PkRKWmLB8-lE1WjTUjg.png" /></figure><ul><li>By now, the web service can be tested by inputting <strong>this http link (</strong><a href="http://localhost:7071/api/http_trigger?name=world"><strong>http://localhost:7071/api/http_trigger?name=world</strong></a>) into a web browser (google chrome, Safari, firebox, etc). The output will be shown as follow:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtvZyoY-lUqBwBmiPH8ItQ.png" /></figure><p><strong>Create Function in Azure</strong></p><ul><li>Starting from this step, an account for microsoft Azure is needed.</li><li>The account can be created by free in this link (<a href="https://azure.microsoft.com/en-us/pricing/purchase-options/azure-account">https://azure.microsoft.com/en-us/pricing/purchase-options/azure-account</a>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Suy7894LdpTGARCEAdUhCg.png" /></figure><ul><li>Once the account is created, please login to the portal and search for function app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0Dx3EMQiXaRtgYFcR1mfA.png" /></figure><ul><li>To try on this tutorial, consumption plan would be enough. For this tutorial, an <strong>asr-processor </strong>is created.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12D8kZwHaMBJ_BNCG7-qoA.png" /></figure><ul><li>If this function is successfully created, it can be viewed from the Function App portal.</li></ul><p><strong>Sign in Azure Portal from Visual Studio Code</strong></p><ul><li>Once the function is created in Azure Function portal, it can be found in Visual Studio Code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*DipRcTEtth13NjcLLX1jlw.png" /></figure><ul><li>Next, the function that has been created earlier in Visual Studio Code can be deployed to Azure Functions.</li><li>Deploy the functions to Azure</li><li>Press F1 (Fn+F1 for MacBook users) and enter Azure Functions: Deploy to Function App…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmljLb1F6nojy7463p6ynQ.png" /></figure><ul><li>After that, the Azure Function that has been created earlier will be shown for selection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DE18h88fAyONKwWzGVw3vw.png" /></figure><ul><li>Select the name of the function app and deploy the webservice to the Azure Function app. The status of the deployment can be seen in the terminal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hvS3H2j-AmiZCpNj4elxQ.png" /></figure><p><strong>Test the deployed Service</strong></p><ul><li>Once the service is deployed, it can be tested from Azure Function portal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXu0bg7W6raXehqqBEdarg.png" /></figure><ul><li>Besides azure function portal, it can be tested using Postman tool.</li></ul><p>Congratulations, your web service is now successfully onboarded to Azure Functions. One of the key advantages of using Azure Functions is its built-in authentication feature, which ensures that only authorized users with valid credentials can access the service. This added layer of security helps protect your application from unauthorized access, reinforcing the reliability and trustworthiness of your deployment. By leveraging the authentication capabilities and other integrated features of Azure Functions, you can deliver secure, scalable, and cost-effective web services with minimal infrastructure management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8848967c454b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free Question Answering Service with LLama 2 model and Prompt Template]]></title>
            <link>https://alex-yeo.medium.com/free-question-answering-service-with-llama-2-model-and-prompt-template-07a9e7f33b76?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/07a9e7f33b76</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[free]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 08:36:57 GMT</pubDate>
            <atom:updated>2023-10-22T08:51:03.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XI700ZEN2f37HxGzxLUCLA.jpeg" /><figcaption>LLama is assisting a student</figcaption></figure><p>Content Generation (CG-AI) is the most fancy term now with the introduction of ChatGPT, LLama, DALL-E and Diffusion Model.</p><p>Some of these services require subscription fee because these applications provide the simplicity to integrate their services with your applications. If we know the steps/processes to integrate our applications with the CG-AI services, we can use the services for free.</p><p>Therefore, in this Articles, we will train LLama2 with local HTML files information and use it as our personal Question Answering bot. Even better, we can use this service for free. Yes, use it for free!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vn8x7M1OVcYXk9PgDwa3eQ.png" /><figcaption>HTML files in “langchain-docs” folder</figcaption></figure><p>I have downloaded the langchain HTML files locally, but you can download any HTML files that you like and feed the HTML files to LLama 2. Before feeding the HTML files to LLama 2 model, we need to pre-process the HTML files and configure LLama 2 model to run the model effectively. For that to happen, we need know 3 important things : <strong>LangChain, Transformer and HuggingFace</strong>. LangChain contains most of the data processing functions and pipelines, Transformer contains an encoder and decoder working together for various tasks, while HuggingFace contains different types of machine learning models.</p><h4>LangChain (Data Preprocessing)</h4><p>Let’s start with LangChain. We will use few features provided by LangChain like directory loader, text splitter to pre-process our data. We can start with document loader. For this function, we need to specify the folder location and the file extensions that we are expecting. In our example, we are expecting HTML files. Then, to process these HTML files, we need a HTML parser and the parser can be found in beautiful soup library. This library is wrapped in “<strong>BSHTMLLoader</strong>” class file by Langchain.</p><pre>from langchain.document_loaders import DirectoryLoader<br>from langchain.document_loaders import BSHTMLLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>import os<br><br>from torch import cuda, bfloat16<br>import transformers<br>from langchain.embeddings import HuggingFaceEmbeddings<br>from langchain.vectorstores import FAISS<br>from langchain.llms import HuggingFacePipeline<br><br>from langchain.chains import ConversationalRetrievalChain<br>from langchain.prompts import PromptTemplate<br><br>model_id = &#39;meta-llama/Llama-2-7b-chat-hf&#39;<br>device = f&#39;cuda:{cuda.current_device()}&#39; if cuda.is_available() else &#39;cpu&#39;<br>hf_auth = &quot;hf_YOUR_AUTHENTICATION_ID&quot;<br>print(&quot;using : &quot;, device)<br><br><br>##### loading document<br>folder_location = &#39;./langchain-docs&#39;<br>files = os.listdir(folder_location)<br>loader = DirectoryLoader(folder_location, glob=&quot;**/*.html&quot;, loader_cls=BSHTMLLoader)<br>documents = loader.load()<br>print(len(documents))</pre><p>Once we have extracted the useful contents from the HTML files, we need to split the contents into short sentences. We can achieve this by using the “<strong>RecursiveCharacterTextSplitter</strong>” function in LangChain. This is a simple step. Let’s quickly move on to next step which is the indexing or embedding step.</p><pre>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=20)<br>all_splits = text_splitter.split_documents(documents)</pre><p>In the indexing step, we are converting every word in the sentences into a vector of number. For example, we could represent the word “LLama” to [0.2, 0.1. 0.3, 0.4, 0.9]. This vector of number is called embedding. For this process, we could use a pre-trained model to do the conversion. There are a lot of pre-trained models in the market, we are using FAISS model to do the indexing. If you are familiar with this process, you will know that we only need to do this once for our document. When we have new documents to feed to LLama 2 model, then, we need to do the indexing again. Therefore, I save the embedding of the documents locally so that I don’t need to do indexing every time.</p><pre><br>embeddings = HuggingFaceEmbeddings(model_name=model_name, model_kwargs=model_kwargs)<br># storing embeddings in the vector space. do this once only.<br>vectorstore = FAISS.from_documents(all_splits, embeddings)<br># save embedding file<br>vectorstore.save_local(&quot;faiss_index&quot;)<br># load embedding<br>loaded_vectorstore = FAISS.load_local(&quot;faiss_index&quot;, embeddings)</pre><h4>Transformer (Data Modeling)</h4><p>Great, so far so good! We have done with the data pre-processing parts. Next, we will go to the modeling part. In this part, we will configure the model and create rules for the model to behave nicely using the prompt template. Let’s start with the configuration of the LLama 2 Large Language Model. The configuration that we will make here is <strong>Quantization</strong>. Basically, the quantization process is to reduce the model weights to 4 bits floating number. This will reduce some precision but it will increase the prediction speed drastically. This is shown in the “<strong># setup quantization</strong>” part.</p><p>After that, we need to choose the task that we want to perform using the transformer model. As we know earlier, Transformer contains a encoder and decoder that can be used on various task. One of the tasks is machine Translation. if you are interested in it, you could refer to these 2 articles (<a href="https://medium.com/machine-learning-evaluation-metrics-precision/baby-steps-in-neural-machine-translation-part-1-encoder-human-is-solving-the-challenge-given-d3f36b977828">Baby steps in Neural Machine Translation Part 1 (Encoder)</a>, <a href="https://medium.com/analytics-vidhya/baby-steps-in-neural-machine-translation-part-2-decoder-human-is-solving-the-challenge-given-by-4d097c961e67">Baby steps in Neural Machine Translation Part 2 (Decoder)</a> ) for deeper understanding. For now, we will choose the “<strong>AutoModelForCausalLM</strong>” model for our Question Answering application. This part is shown in the “<strong># configure LLM to use quantization</strong>” part.</p><pre>##### setting up LLM #####<br># setup quantization<br>bnb_config = transformers.BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&#39;nf4&#39;,<br>    bnb_4bit_use_double_quant=True,<br>    bnb_4bit_compute_dtype=bfloat16<br>)<br><br># load llm model<br>model_config = transformers.AutoConfig.from_pretrained(<br>    model_id,<br>    use_auth_token=hf_auth<br>)<br><br># configure LLM to use quantization<br>model = transformers.AutoModelForCausalLM.from_pretrained(<br>    model_id,<br>    trust_remote_code=True,<br>    config=model_config,<br>    quantization_config=bnb_config,<br>    device_map=&#39;auto&#39;,<br>    use_auth_token=hf_auth<br>)<br><br># enable evaluation mode to allow model inference<br>model.eval()</pre><p>By now, we have configure the model properly. The next thing we want to do is to add in a tokenizer to the transformer model. So, what is the purpose of a tokenizer? if you have gone through the article “<a href="https://medium.com/machine-learning-evaluation-metrics-precision/baby-steps-in-neural-machine-translation-part-1-encoder-human-is-solving-the-challenge-given-d3f36b977828">Baby steps in Neural Machine Translation Part 1</a>” earlier, you might know the purpose of a tokenizer. Basically, a tokenizer is the way to split a sentence into a list of words. the easiest way is to use “space” as a indicator to split the sentence. There are a lot of researches have been done on the tokenizer, one of the famous tokenizer is byte-pair encoding. But this is out of the scope of this article. We will use the tokenizer suggested by the Transformer library to perform the Question Answer Task.</p><pre><br>##### setup pipeline<br># setup tokenizer<br>tokenizer = transformers.AutoTokenizer.from_pretrained(<br>    model_id,<br>    use_auth_token=hf_auth<br>)<br># configure LLM pipeline with the tokeniser and task<br>generator = transformers.pipeline(<br>    model = model,<br>    tokenizer=tokenizer,<br>    return_full_text = True, # langchain expects full text<br>    task=&#39;text-generation&#39;,<br>    #stopping_criteria=stopping_criteria, # without this model rambles during chat<br>    temperature=0.1, # &#39;randomness&#39; of outputs, 0.0 is the min and 1.0 is the max<br>    max_new_tokens=512, # max number of tokens to generate in the output<br>    repetition_penalty=1.1 # without this output begins repeating<br>)</pre><p>Up until here, we are done with the data modeling parts. Next thing, we will proceed with data-processing part by setting the rules for the LLM Model to behave.</p><p><strong>HuggingFace (Data Post-Processing)</strong></p><p>In this part, we will wrap the Transformer model with HuggingFace pipeline so that we can pass the rules to the Transformer model. To craft and pass the rules to the Transformer model, we can use the LangChain Prompt Template. In this prompt template, we can tell how the LLM should behave. This is shown in the “pre_prompt” variable. Next, we give some information or context to the LLM to refine our prediction. For example, we can tell the LLM that we are dicussing “Apple” product such as iphone, ipad and mac book, instead of discussing “Apple” as a fruit. With the context, we can pass in the relevant question as shown in the “prompt” variable.</p><p>Lastly, we want to chain everything together. These include, indexed HTML contents, Large Language Model, and Prompt Template(Rules). We can do this by using the HuggingFace class called “<strong>ConversationalRetrievalChain</strong>”.</p><pre># wrap the transformer model with Huggingface pipeline so that we can use prompt later<br>llm = HuggingFacePipeline(pipeline=generator)<br># creating prompt for large language model<br>pre_prompt = &quot;&quot;&quot;[INST] &lt;&lt;SYS&gt;&gt;\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don&#39;t know the answer to a question, please don&#39;t share false information.\n&lt;&lt;/SYS&gt;&gt;\n\nGenerate the next agent response by answering the question. Answer it as succinctly as possible. You are provided several documents with titles. If the answer comes from different documents please mention all possibilities in your answer and use the titles to separate between topics or domains. If you cannot answer the question from the given documents, please state that you do not have an answer.\n&quot;&quot;&quot;<br>prompt = pre_prompt + &quot;CONTEXT:\n\n{context}\n&quot; +&quot;Question : {question}&quot; + &quot;[\INST]&quot;<br>llama_prompt = PromptTemplate(template=prompt, input_variables=[&quot;context&quot;, &quot;question&quot;])<br># integrate prompt with LLM<br>chain = ConversationalRetrievalChain.from_llm(llm, loaded_vectorstore.as_retriever(), combine_docs_chain_kwargs={&quot;prompt&quot;: llama_prompt}, return_source_documents=True)</pre><h4>Prediction</h4><p>Great job by following all the steps until here. Everything is ready now. We can pass in our questions to the Question Answer service. Have fun and play with it for free!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*newPgdOPehzTwKVokZvXwQ.jpeg" /><figcaption>Trained Knowledgeable LLama</figcaption></figure><pre><br># testing the model<br><br>chat_history = []<br><br>query = &quot;What is LangChain and what applications can be created using LangChain?&quot;<br><br>result = chain({&quot;question&quot;: query, &quot;chat_history&quot;: chat_history})<br><br>print(&quot;answer&quot;, result[&#39;answer&#39;])<br>chat_history = [(query, result[&quot;answer&quot;])]<br><br>query = &quot;Please repeat the applications mentioned just now?&quot;<br>result = chain({&quot;question&quot;: query, &quot;context&quot; : result[&quot;answer&quot;], &quot;chat_history&quot;: chat_history})<br><br>print(&quot;answer&quot;, result[&#39;answer&#39;])<br>print(&quot;source_documents : &quot;, result[&#39;source_documents&#39;])</pre><p>Hope you enjoy the article and hope this article give your extra understanding on the LLama Large Language Model.</p><p>Before leaving, I have a shameless promotion on my <strong>Free</strong> Udemy course : <a href="https://www.udemy.com/course/real-world-sql-and-data-visualization/?referralCode=BAC2A145031B03ACBF34">Practical Real-World SQL and Data Visualization</a>. I find that the free visualization tool, Metabase, is very useful. Therefore, I spend weekends creating the course and I wish you could benefit from the course. Lastly, I really appreciate if you could take a look on the <a href="https://www.udemy.com/course/real-world-sql-and-data-visualization/?referralCode=BAC2A145031B03ACBF34">course</a> and even better, please give me a review on this course so that I can improve the course. Thank you!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07a9e7f33b76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Installation of Cuda, Cudnn & Virtual Environment on Ubuntu 22.04]]></title>
            <link>https://alex-yeo.medium.com/easy-installation-of-cuda-and-cudnn-on-ubuntu-22-04-8fde7c5da62b?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fde7c5da62b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cudnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 07:23:28 GMT</pubDate>
            <atom:updated>2023-10-11T11:28:23.175Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I have updated my Ubuntu Operating System to version 22.04 and I find out that the installation of CUDA and Cudnn is much more simpler that earlier version. Therefore, I have decided to create this blog to help others setting up the environment easily.</p><h4>Nvidia Drivers</h4><p>Let’s us start with Installation of Nvidia Driver. Basically this driver is installed when we update our Ubuntu Operation System. Basically we need to know which driver has been used by our Operating System. In Ubuntu 22.04, we can click the “show application” on the bottom left and type in “additional driver” to check for the Nvidia Driver that we are using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vlva4MoJzByPJBpmStetPA.png" /><figcaption>additional driver</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*zmjRCev6slCSvSQzVib5WQ.png" /><figcaption>Nvidia Drivers</figcaption></figure><p>As we can see, there are multiple Nvidia drivers and I have selected Nvidia-driver-525 to use. To install for multiple drivers, we can run these commands.</p><pre>sudo apt update<br>sudo apt upgrade<br>sudo ubuntu-drivers autoinstall<br>reboot<br>nvidia-smi</pre><h4>Cuda Toolkits</h4><p>Once we have chosen the Nvidia Driver (Nvidia-driver 525 for my case) suitable for us, we could start installing the Cuda toolkits.</p><pre>sudo apt update<br>sudo apt upgrade<br>sudo apt install nvidia-cuda-toolkit</pre><p>After installing the toolkit, we need to know the supported CuDNN version for the installed Cuda toolkits. We could run the following command.</p><pre>nvcc --version </pre><p>this is the output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*v52yOXzwq_Y2zXzXQU5ozg.png" /><figcaption>Suitable CuDNN version</figcaption></figure><h4>CuDNN</h4><p>From the output, we get to know the installed Cuda toolkits is version 11.x. Therefore, the corresponding CuDNN is <a href="https://developer.nvidia.com/downloads/compute/cudnn/secure/8.9.3/local_installers/11.x/cudnn-local-repo-ubuntu2204-8.9.3.28_1.0-1_amd64.deb/">Local Installer for Ubuntu22.04 x86_64 (Deb)</a>. If we go the <a href="https://developer.nvidia.com/rdp/cudnn-archive">nvidia CuDNN website</a>, we will notice that there are 2 versions of CuDNN for Cuda 12.x and Cuda 11.x. We could choose another version of CuDNN <a href="https://developer.nvidia.com/downloads/compute/cudnn/secure/8.9.3/local_installers/12.x/cudnn-local-repo-ubuntu2204-8.9.3.28_1.0-1_amd64.deb/">Local Installer for Ubuntu22.04 x86_64 (Deb)</a> if the installed Cuda is 12.x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFkYZH_DcLFvmoF0NCDkgQ.png" /><figcaption>List of CuDNN</figcaption></figure><p>Once we have downloaded the suitable CuDNN, we could run the following command to install the CuDNN.</p><pre>sudo dpkg -i cudnn-local-repo-ubuntu2204-8.9.3.28_1.0-1_amd64.deb<br>sudo cp /var/cudnn-local-repo-ubuntu2204-8.9.3.28/cudnn-local-7F7A158C-keyring.gpg /usr/share/keyrings/ </pre><p>After the command finish running, we are done with the installation! Before we celebrate the success, let’s us test the CUDA &amp; CuDNN installation from virtual environment using torch library.</p><h4>Virtual Environment</h4><p>Installation of virtual environment can be done using the following scripts.</p><pre>sudo apt-get install python3-pip<br>sudo pip3 install virtualenv<br>virtualenv -p py3.10 venv<br>source venv/bin/activate</pre><h4>CUDA &amp; CuDNN test : pytorch &amp; tensorflow</h4><p>Installation of pytorch library can be done using the following scripts.</p><pre>import torch<br>print(torch.cuda.is_available()) # should be True</pre><p>in additional, we could test it using tensorflow.</p><pre>pip3 install tensorflow</pre><p>This python script can be used to do the test.</p><pre>import tensorflow as tf<br>print(&quot;Num GPUs Available: &quot;, tf.config.list_physical_devices(&#39;GPU&#39;) , len(tf.config.list_physical_devices(&#39;GPU&#39;)))</pre><p>Once we see the following output, we can start celebrating by giving me a clap!!!</p><pre>Num GPUs Available:  [PhysicalDevice(name=&#39;/physical_device:GPU:0&#39;, device_type=&#39;GPU&#39;)] 1</pre><p>Before leaving, I have a shameless promotion on my Udemy course : <a href="https://www.udemy.com/course/real-world-sql-and-data-visualization/?referralCode=BAC2A145031B03ACBF34">Practical Real-World SQL and Data Visualization</a>. I have been working in the top travel platform company for years and I find that the free visualization tool, Metabase, is very useful. Therefore, I spend weekends creating the course and I wish you could benefit from the course. Lastly, I really appreciate if you could take a look on the <a href="https://www.udemy.com/course/real-world-sql-and-data-visualization/?referralCode=BAC2A145031B03ACBF34">course</a> and even better, please help me to share the <a href="https://www.udemy.com/course/real-world-sql-and-data-visualization/?referralCode=BAC2A145031B03ACBF34">course</a> with your friends just like I share the knowledge to you. Thank you!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fde7c5da62b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Adaptive Learning — Reinforcement Learning with Normal Distribution]]></title>
            <link>https://alex-yeo.medium.com/continuous-adaptive-learning-reinforcement-learning-with-normal-distribution-85d7ce502e0f?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/85d7ce502e0f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 13:43:23 GMT</pubDate>
            <atom:updated>2023-09-18T09:55:46.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>Continuous Adaptive Learning — Reinforcement Learning with Normal Distribution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kM_NOv7wAsQBVb0eiKJ-jg.png" /><figcaption>Adaptation from Summer to Winter</figcaption></figure><p>As a human, we always adjust ourselves to adapt to a new environments. One of the example is to adapt to seasonality. During summer, we will go for swimming or surfing and while during winter, we go for skating or snowboarding. By adapting to the new environment, we would be able to survive or find happiness within ourselves.</p><p>Similarly, we want our products to adapt to new environments in order to generate more incomes or to serve customers better. For example, we want our website to sell sweaters during winter and sell swimsuits during summer automatically. This sounds good. But how can we achieve this?</p><p>Thanks to reinforcement learning, our products can learn to adapt to new environment. The concept of reinforcement learning is simple, it has been well explained in this <a href="https://medium.com/machine-learning-evaluation-metrics-precision/reinforcement-learning-q-learning-6c9c0648c309">blog</a>. Let’s us quickly go through the concept of reinforcement learning by going through these terms: state, action, reward, policy, Q-table.</p><p><strong>policy </strong>: consist of state and action. eg. We are selling swimsuit today, but we want to change to sell sweaters tomorrow; or we are selling swimsuits today and we want to keep selling swimsuit tomorrow, etc. Let’s us define this is in array form. it will be written as [swimsuit, change, sweater] for the first case, and [swimsuit, keep, swimsuit] for the second case. After writing the 2 cases in array form, we should be able to identify the <strong>states </strong>and <strong>actions</strong>. In our case, <strong>swimsuits and sweaters are the states, while “keep” and “change” are the actions</strong>.</p><p><strong>Reward </strong>: The score that will be given to a policy. Positive score will be given if the policy is increasing our sales or customer satisfactions. Otherwise, negative score will be given.</p><pre>from statistics import mean<br><br>historical_sales = [100, 90, 120, 110, 80, 100, 70]<br>sales_avg = mean(historical_sales)<br><br>today_sales = 150<br>reward = 0<br>print(&quot;average sales : &quot;, sales_avg)<br><br>if today_sales &gt; sales_avg:<br>    reward = 1<br>else:<br>    reward = -1<br><br>print(&quot;reward :&quot;, reward)</pre><p><strong>Q-table</strong> : consist of a list of policies. Reinforcement Learning algorithm will choose the best policy among the policies in the Q-table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*jMDcyyVcuV2utoofB0sYoA.png" /></figure><p>As we can see from the Q-table, we want to choose the best policy when the season transits from from winter to summer. if we implemented the reinforcement algorithm correctly, the best policy will change from [sweater, keep, sweater] to [swimsuit, keep, swimsuit]. <strong>This process of finding the best policy is known as exploitation</strong>. However, in reinforcement learning algorithm, we want to introduce some randomness to explore opportunities. For example, we could try selling sweater during summer. Our sales might increase because the sweater price will reduce during summer due to low demand. Similarly, we could try selling swimsuit during winter because the swimsuit price will reduce due to low demand. <strong>This process of exploring other actions is known as exploration</strong>.</p><h4>Exploitation</h4><p>So now, we know that there are 2 processes (exploitation &amp; exploration) in reinforcement learning. In the exploitation process, we will update the score of the chosen policy using the stated formula below.</p><pre>Q[s][a] = Q[s][a] + ALPHA * (reward + GAMMA* maxQ[s_next][A] - Q[s][a] )</pre><p>Let’s assume we have chosen to change from selling sweater to swimsuit and we have increased the sale for today. This mean we can fill up the formula with positive reward due to the increase in sale.</p><pre>ALPHA = 0.2 # how fast you want to update your chosen policy<br>GAMMA = 0.1 # how many information you want to borrow from your next state to make decision on your current state<br>Q[&quot;sweater&quot;][&quot;change&quot;] = Q[&quot;sweater&quot;][&quot;change&quot;] + ALPHA * ( 1 dollar + GAMMA* max(Q[&quot;swimsuit&quot;][&quot;keep&quot;],Q[&quot;swimsuit&quot;][&quot;change&quot;]) - Q[&quot;sweater&quot;][&quot;change&quot;])</pre><p>Once we update the policy, Q[“sweater”][“change”], we need to choose what to sell tomorrow. We have 2 options now : keep selling swimsuit Q[“swimsuit”][“keep”] or change to sell sweater Q[“swimsuit”][“change”]. This the exploration part. The objective here is to maximize our sales by choosing the best policy as much as possible while giving chance for trying different policy. There are few strategies such as epsilon greedy, Thompson Sampling and Normal Distribution for exploration. For this example, we will go through the technique of using Normal distribution of rewards to choose the product to sell tomorrow.</p><h4>Exploration</h4><p>For the normal distribution technique, we will look into the rewards assigned to each (state, action) pair.</p><pre># reward[state][action] = [0]<br>reward[&quot;swimsuit&quot;][&quot;keep&quot;] = [0, 1, 1, 1, 1, 1, 1, -1]<br>reward[&quot;swimsuit&quot;][&quot;change&quot;] = [0, -1, -1, 1, -1]<br>reward[&quot;sweater&quot;][&quot;keep&quot;] = [0, -1, -1, -1]<br>reward[&quot;sweater&quot;][&quot;change&quot;] = [0, 1, 1, 1, 1]</pre><p>For the rewards of the (state, action) pairs, we will calculate the mean and standard deviation. The distribution will be similar to the chart below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHDWvinw_X1WVa2J6i5NWQ.png" /><figcaption>reward distributions of policies</figcaption></figure><p>As we can see from the chart, the reward distribution of the policy to change and sell sweater is moving toward -1 reward. this is because the policy reduces the company sale compare to historical sales. On the other hand, we could see the reward distribution of the policy to keep selling sweater is moving toward +1 reward. This is align with our expectation as we expect the sale of swimsuit to increase during summer.</p><p>Since we have the reward distributions of the 2 policies, we could get one sample from each reward distribution. By comparing the samples from the 2 distributions, we can decide on the policy for tomorrow sale.</p><pre>import numpy as np<br><br># example to get sample from each distribution<br>mean[&quot;swimsuit&quot;][&quot;keep&quot;] = 0.5<br>mean[&quot;swimsuit&quot;][&quot;change&quot;] = 0.5<br>std[&quot;swimsuit&quot;][&quot;keep&quot;] = 0.05<br>std[&quot;swimsuit&quot;][&quot;change&quot;] = 0.05<br><br>policy_change = np.random.normal(mean[&quot;swimsuit&quot;][&quot;change&quot;], std[&quot;swimsuit&quot;][&quot;change&quot;], 1)<br>policy_keep = np.random.normal(mean[&quot;swimsuit&quot;][&quot;keep&quot;], std[&quot;swimsuit&quot;][&quot;keep&quot;], 1)<br><br>next_state = &quot;&quot;<br>if policy_change &gt; policy_keep :<br>    next_state = &quot;sweater&quot;<br>else:<br>    next_state = &quot;swimsuit&quot;</pre><p>If the sample drawn from the reward distribution of the policy, to change to sell sweater, is higher than the sample drawn from the reward distribution of the policy, to keep selling swimsuit, we will start selling sweater on tomorrow. This is the mechanism that we used to do exploration.</p><p>The exploitation and exploration processes are clearly explained. Please give us a clap if you find this explanation helpful! See you in our next blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85d7ce502e0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create AB test From Scratch With Confidence using P-value — Fair Experimentation Platform]]></title>
            <link>https://alex-yeo.medium.com/create-ab-test-from-scratch-with-confidence-using-p-value-fair-experimentation-platform-59a9ce7cb51a?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/59a9ce7cb51a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ab-test]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 11:02:26 GMT</pubDate>
            <atom:updated>2023-09-17T14:31:13.976Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create AB test From Scratch With Confidence using P-value — Fair Experimentation Platform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uix1-n5JEQfyc4IEEZPavg.png" /><figcaption>Who will win?</figcaption></figure><p>How can we measure <strong>the new value added to a company product is actually coming from the change made by us?</strong> This change could be the size increase of the “buy” button in a website or the replacement of the product pictures in a website. All of these changes are arbitrary. Some people will argue that these changes will bring profits to our product because customers will feel refresh with the new look and buy our product. Some people will argue that these changes will bring losses to our product because customers cannot adapt to the new look and stop purchasing the product from us. Therefore we need to a mechanism to determine to impact of the change. If the change brought positive impact, we are all happy with it; However, if the change brought negative impact, we need to revert the change quickly and conduct further analysis. This is crucial because the negative impact could cause us losing moneys, increase in logged complaints and loss of customer satisfactions.</p><p>The solution to this issue is to <strong>setup an AB test for the change the we have made</strong>. The “<strong>A</strong>” in the AB test term means the <strong>current implementation</strong> (before change) while the “<strong>B</strong>” in the AB test term means the <strong>new implementation </strong>(after change). Basically, we are comparing the value before and after the change. By now, we know the meaning and purpose of AB test. The next step would be the implementation of AB test. To implement the AB test, there are few steps. Don’t worry, we will go through these steps one-by-one with brief explanation.</p><ul><li>Determine the evaluation metric for the A/B test.</li><li>Decide the AB group splitting/allocation factor.</li><li>Conduct AA analysis to make sure the splitting/allocation is fair.</li><li>Calculate the confidence of the AB test using z-score/p-val.</li></ul><p><strong>Determine the evaluation metric for the AB test</strong></p><p>For this step, we need to define a relevant metric related to our change. Usually, this metric will be related to business value. For example, in Hotel/Homestay booking platform, Booking number could be used as the evaluation metric. For property selling platform, click number could be the evaluation metric. Most of the time, Product Owner will work together with the team to determine the evaluation metric. For the illustration purpose, let’s us take booking number as our evaluation metric.</p><p><strong>Decide the AB traffic splitting/allocation factor</strong></p><p>For this step, we need to propose a way to split the customers into 2 group. 1 group will be allocated to A side (current implementation), 1 group will be allocated to B side (new implementation by increasing button size). There are multiple ways to split the customers into group A and group B. We can use <strong>customer ID</strong> to do the splitting. Customers with ODD id will be allocated to group A while customers with EVEN id will be allocated to group B. Then, we will get the bookings difference between group A (customers with ODD id) and group B (customers with EVEN id) to calculate the additional value contributed by Group B. However, some customers might not have customer IDs because they do not register as a member for the platform. In this case, we could use <strong>time-based</strong> allocation. In time-based allocation, we could allocate the customers who have made the Bookings in our website at ODD hour as group A, and the customers who have made the Bookings in our website at EVEN hour as group B. In additional, we could further make our <strong>allocations unbiased</strong> by allocating bookings on (ODD days, ODD hours), (EVEN days, EVEN hours) to group A, and (ODD days, Even hours), (EVEN days, ODD hours) to Group B as shown in chart below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uSvp_cs3INKVN_bEO2g4A.png" /><figcaption>Booking Difference between A and B</figcaption></figure><p><strong>Conduct AA analysis to prove the splitting/allocation is fair.</strong></p><p>As mentioned earlier, we need to make sure that our allocation is unbiased/fair when using time-based allocation. We could achieve this by conducting an AA analysis. In an AA analysis, we will split the bookings into 2 groups. The 2 groups will be using current implementation where there is no change implemented on the website. Let’s us call the Bookings on (ODD days, ODD hours), (EVEN days, EVEN hours) as A1 and the Bookings on (ODD day, EVEN hours), (EVEN days, ODD hours) as A2. Our expectation for the Bookings made on A1 and A2 should be approximately the same. Or the Bookings difference between A1 and A2 should be approximately 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHne0rYHb9paNHkkTKY4Vw.png" /><figcaption>Booking Difference AA Proving</figcaption></figure><p>Basically, we can verify this using the history Bookings. The codes below can be used to calculate the booking difference (<strong>BD</strong>) and standard deviation (<strong>STD</strong>) using 1 year data. Since we calculate the booking difference for 28-days, 1 year data can give us 12 data points from 12 AA tests. For example, BD1 shown in the chart below represents data point 1. This data is derived from the difference of sum A1 and sum A2 (sum A1 — sum A2) for 28 days (4 weeks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeHeFXZUN4_EC-Nf_0qOow.png" /><figcaption>Booking Differences from 12 AA tests</figcaption></figure><p>Based on the 12 data points, we have the mean and standard deviation of booking differences as 18 and 138 respectively. As we mentioned earlier, we want to have the mean of booking differences close to 0 and we get 18 as our result. In our case, we can claim that 18 is very close to 0 because the 18 booking difference is derived from the mean of differences of A1 bookings which are close to 50k bookings and A2 bookings which are also close to 50k bookings.</p><p>We choose 28-days because this is the duration for 1 cycle of AB test. we could choose different duration for 1 cycle of AB test. However, the shorter the duration, the higher the standard deviation. And the higher the standard deviation, the harder for us to claim that the B side is winning (reject null hypothesis). We can prove this using statistic and this will be explain in part 4.</p><pre>import os<br>import pandas as pd<br>import numpy as np<br><br>booking_path = r&quot;hourly_scale_bookings.csv&quot;<br><br>booking_content = pd.read_csv(booking_path)<br># the content is in this format <br>#   index  datadate  hour  bookings<br>#   3254  20220302     0      94.0<br>#   3336  20220302     1      79.0<br>#    825  20220302     2      73.0<br>#    566  20220302     3      73.0<br>#   5850  20220302     4      69.0<br><br>booking_content_sort = booking_content.sort_values(by=[&#39;datadate&#39;,&#39;hour&#39;])<br>booking_content_sort = booking_content_sort.reset_index()<br><br>print(booking_content_sort.head())<br>print(booking_content_sort.dtypes)<br><br><br>def calculate_std(bookings, time_interval, exp_time):<br>    &#39;&#39;&#39;<br>    time_interval : how many hour we do flip<br>    exp_time for how long we do the experiment<br>    &#39;&#39;&#39;<br>    day = 0<br>    bookings_diff = []<br>    AB_bookings = []<br>    a_sum = 0<br>    b_sum = 0<br>    off_site = 0<br>    a_hour = 0<br>    b_hour = 0<br>    for index, row in bookings.iterrows():<br>        hour = int(row[&quot;hour&quot;])<br>        booking_counts = int(row[&quot;bookings&quot;])<br>        if (int(hour / time_interval) + off_site) % 2 == 0:  # time_interval = flipping hours<br>            b_sum += booking_counts<br>            b_hour += 1<br>        else:<br>            a_sum += booking_counts<br>            a_hour += 1<br>        if hour == 23:<br>            day += 1<br>            off_site = (off_site + 1) % 2<br>            if day == exp_time:<br>                day = 0<br>                bookings_diff.append(b_sum - a_sum)<br>                AB_bookings.append([b_sum, a_sum])<br>                b_sum = 0<br>                a_sum = 0<br>    bookings_diff = np.array(bookings_diff)<br>    std = np.std(bookings_diff)<br>    return bookings_diff.mean(), std, bookings_diff, AB_bookings<br><br>mean, std, bookings_diff, AB_bookings = calculate_std(booking_content_sort,1,28)<br>print(&#39;mean:&#39;,mean,&#39;std:&#39;,std)<br><br><br># calculate z-score<br># z = (x - mean) / std<br>z = (501 - mean) / std<br>print(z, mean, std)<br><br># calculate p_value, right tail test<br>p_value = 1.0-stat.norm(0,1).cdf(z)<br>print(p_value)</pre><p><strong>Calculate the confidence of the AB test using z-score/p-val.</strong></p><p>By now, we have verified that the time-based allocation is unbiased. Next, we will run this AB test for 4-weeks. Let’s refresh our memory. During (ODD day, ODD hour) and (EVEN day, EVEN hour), we will use current button size. While during(ODD day, EVEN hour) and (EVEN day, ODD hour), we will use “BIG” size button. To determine whether the change on B side (increase of the Button Size) is significantly bringing additional value to the Booking platform, we need to see huge increase in Bookings on B side. Assuming we have additional 500 booking after 28-days run from A/B test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsGiPXYfWBlIxVcjDKGHHw.png" /><figcaption>Standard Deviation of AB test</figcaption></figure><p>Here, we need to understand few statistical terms such as mean, standard deviation and null hypothesis.</p><p><strong>mean </strong>: the average bookings from 12 data points.<br><strong>standard deviation</strong> : Determine the sparseness of the 12 data points. One standard deviation means we have 68% of the 12 data points which is 8 data points fall in the range of (18–138, 18+138). <br><strong>null-hypothesis</strong> : Change in B side (“Big” button size) performs the same as A side (No change).</p><p>In order for us to say the change in B is significantly adding new value to our product, we need to reject the null-hypothesis by calculating the z-score and perform the right-tail test to get the <a href="https://www.omnicalculator.com/statistics/p-value#what-is-p-value">p-value</a>. We will start with the explanation of z-score.</p><p>The concept of z-score is easy to understand. Since mean is close to 0, we simply divide the new value to standard deviation. This will tell us how far the new data (additional booking from “Big” button) is away from our historical data. From our example, we see that the new data is 3.49 time away from our historical data. This shows change in B side is very significant. However, we want to convey this information to non-technical people. They might not know the meaning of standard deviation and z-score. Therefore, we need to convert z-score into p-value. The formula to convert z-score to p-val is shown in the codes. Basically p-value will give us the confidence of our change. In our case, we have p-val = 0.00023. This mean, we have 0.023% chance that the change in button size will not tell us the increase in additional bookings. In the other hand,<strong> we could tell the non-technical people that we are 99.977% confidence that the change in button size will bring us additional bookings.</strong></p><p>We have gone through the 4 steps to create an unbiased experimentation platform. Hope that this explanation is helpful and give us a like if this blog bring some values to you. Next, we will apply this A/B test in reinforcement learning for continuous improvement. Hope we can go through this together is our next blog. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59a9ce7cb51a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Commonly-used distance calculation in Data Science : Levenshtein Distance, Haversine Distance]]></title>
            <link>https://alex-yeo.medium.com/commonly-used-distance-calculation-in-data-science-levenshtein-distance-haversine-distance-ecb738762028?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb738762028</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 10:24:27 GMT</pubDate>
            <atom:updated>2023-08-01T10:24:27.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Commonly-used distance calculation in Data Science : Levenshtein Distance, Haversine Distance</h3><p>There are multiple distance calculations commonly used in data science projects depending on the use cases. Usually, these distance calculations will act as input features for Machine Learning or Deep Learning models. Sometimes, people will relate the distance calculations to similarity with the assumption that 2 similar objects will “sit” close to each other. We will see this assumption in the following examples and the reason for using these distance calculation.</p><h3><strong>Levenshtein Distance</strong></h3><p><strong>Reason for Using </strong>: When Each character in a word carries important information</p><p><strong>Use cases</strong>: Location/Hotel/Building/Brand Name matching.</p><p><strong>use case 1</strong> : When we have 2 hotels that are located at the same location but the top floor with the hotel name “ABC A1” and the bottom floor with the hotel name “ABC A2”.</p><p><strong>Use case 2</strong> : When we have 2 brand that are similar like “Nike” and “Niki”.</p><p><strong>Implementation : </strong>When we have the scenarios as described in the use cases, Levenshtein distance will be a good measurement to determine the similarity of the 2 words. For simplicity, <strong>we could think that Levenshtein distance calculations is the calculation of minimum steps to transform 1 word to another words</strong>. Let’s go through this algo with the following example.</p><p>word 1 = SUNNY</p><p>word 2 = SAND</p><p>To transform SUNNY to SAND, we will need to take 3 steps.</p><ul><li>step 1 : substitute character 2 which is U to A</li><li>step 2 : substitute character 4 which is N to D</li><li>step 3 : delete character Y</li></ul><p>As we can see, the Levenshtein of SUNNY and SAND is 3.</p><p>However, there is a case where we can transform 1 word to another word faster by deleting characters instead of substituting characters. Let’s go for another Example</p><p>word 1 = SUUNNY</p><p>word 2 = SUNNY</p><p>Option 1 : we will take 1 step by deleting third character U to transform SUUNNY to SUNNY. the Levenshtein distance of SUUNNY and SUNNY is 1.</p><p>Option 2 : we will take 3 steps to transform SUUNNY to SUNNY.</p><ul><li>step 1 : substitute character 3 which is U to N</li><li>step 2 : substitute character 5 which is N to Y</li><li>step 3 : delete character 6 which is Y.</li></ul><p>As we can see, we have 2 options to transform SUUNNY to SUNNY. In the Levenshtein algorithm, we will chose the shortest distance.</p><p>Now, we know that logic behind this algorithm. For the next step, we need to understand the implementation of this logic. The implementation steps are displayed in the following chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnkKoA_bPmTFKqbP_5gNjg.png" /><figcaption>Levenshtein Algorithm</figcaption></figure><p>For the first step, we will create a metric and initialize the first row and first column with the character position.</p><p>Next step, we need to fill in the blue box one-by-one with the following rule.</p><ul><li>if the character of word 1 is same as the character of word 2, we will assign 0 + surrounding minimum scores (red color scores) to the blue box. This is shown in the second matrix on the top row.</li><li>else if the character of word 1 is <strong>not</strong> the same as the character of word 2, we will assign 1 + surrounding minimum scores (red color scores) to the blue box. this is shown in the third matrix on the top row.</li></ul><p>We could implement this algorithm using the following python code.</p><pre>def levenshtein_distance(s1, s2):<br>    # Create a matrix to store the distances<br>    rows = len(s1) + 1<br>    cols = len(s2) + 1<br>    matrix = [[0] * cols for _ in range(rows)]<br><br>    # Initialize the first row and column<br>    for i in range(rows):<br>        matrix[i][0] = i<br>    for j in range(cols):<br>        matrix[0][j] = j<br><br>    # Compute the distances for the rest of the matrix<br>    for i in range(1, rows):<br>        for j in range(1, cols):<br><br>            cost = 1<br>            if s1[i-1] == s2[j-1]:<br>                cost = 0<br><br><br>            matrix[i][j] = min(<br>                matrix[i - 1][j] + 1,         # Deletion<br>                matrix[i][j - 1] + 1,         # Insertion<br>                matrix[i - 1][j - 1] + cost   # Substitution<br>            )<br><br>    displayDistances(matrix, len(s1), len(s2))<br><br>    return matrix[rows - 1][cols - 1]</pre><p>The last matrix (bottom left) will give us the Levenshtein score shown in the Green color. For more details on the algorithm, we can refer to this <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">wikipedia </a>page.</p><h3>Haversine Distance</h3><p><strong>Reason for using</strong> : Get the distance of 2 locations in earth surface.</p><p><strong>Use cases</strong> : Match same shops/hotels/houses from different platform.</p><p><strong>Implementation </strong>: The implementation of this distance calculation is rather simple. We have the formula documented in this <a href="https://en.wikipedia.org/wiki/Haversine_formula">wikipedia </a>page. First, we need to convert the latitude and longitude of 2 locations to radian. Next, we apply the following formula to calculate the Haversine Distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*WUO83J7uBSrteJ0kG0htuA.png" /><figcaption>haversine distance formula</figcaption></figure><pre>def haversine_distance(lat1, lon1, lat2, lon2):<br>    # Convert latitude and longitude from degrees to radians<br>    lat1_rad = math.radians(lat1)<br>    lon1_rad = math.radians(lon1)<br>    lat2_rad = math.radians(lat2)<br>    lon2_rad = math.radians(lon2)<br><br>    # Haversine formula<br>    dlat = lat2_rad - lat1_rad<br>    dlon = lon2_rad - lon1_rad<br>    a = math.sin(dlat/2) ** 2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon/2) ** 2<br>    <br>    # Radius of Earth in kilometers<br>    radius_earth_km = 6371.0<br><br>    # Calculate the distance<br>    distance = 2 * radius_earth_km * ( math.asin( math.sqrt(a) ) )<br>    print(distance)<br>    <br>    return distance<br><br>latitude1, longitude1 = 37.7749, -122.4194  # San Francisco, CA<br>latitude2, longitude2 = 34.0522, -118.2437  # Los Angeles, CA<br>distance = haversine_distance(latitude1, longitude1, latitude2, longitude2)<br>print(f&quot;The Haversine distance between the two locations is: {distance:.2f} kilometers&quot;) </pre><p>We have introduced 2 distance calculations for different use cases. There is another famous distance calculation which is called cosine distance. However, this distance has been introduce earlier. Feel free to check out the explanation in the link below. Hopefully, this blog can enhance your understandings on different distance calculation and open up the possibilities to improve your data science projects.</p><h3>Cosine Similarity(Distance)</h3><p>Reason for using : compare multiple features at once.</p><p>Use cases : Comparing Apple to Orange, comparing father to mother.</p><p>Implementation : <a href="https://alex-yeo.medium.com/cosine-similarity-introduction-and-applications-in-nlp-92519407df1">https://alex-yeo.medium.com/cosine-similarity-introduction-and-applications-in-nlp-92519407df1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb738762028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idea Generator Guideline : Triz 40]]></title>
            <link>https://alex-yeo.medium.com/idea-generator-guideline-triz-40-b53eae4b5ec4?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b53eae4b5ec4</guid>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Sun, 21 Nov 2021 06:45:22 GMT</pubDate>
            <atom:updated>2021-11-21T06:45:22.547Z</atom:updated>
            <content:encoded><![CDATA[<h3>Idea Generator Guideline : Triz 40</h3><p><strong>Abstract</strong></p><ul><li>Segmentation</li><li>Taking out</li><li>Local Quality</li><li>Asymmetry</li><li>Merging</li><li>Universality</li><li>Russian dolls</li><li>Anti-weight</li><li>Preliminary anti-action</li><li>Preliminary action</li><li>Beforehand cushioning</li><li>Equipotentiality</li><li>The other way round</li><li>Spheroidality — Curvature</li><li>Dynamics</li><li>Partial or excessive actions</li><li>Another dimension</li><li>Mechanical Vibration</li><li>Periodic action</li><li>Continuity of useful action</li><li>Skipping</li><li>Blessing in Disguise</li><li>Feedback</li><li>Intermediary</li><li>Self-service</li><li>Copying</li><li>Cheap short-lived objects</li><li>Mechanics substitution</li><li>Pneumatics and hydraullics</li><li>Flexible shells and thin films</li><li>Porous materials</li><li>Colour changes</li><li>Homogeneity</li><li>Discarding and and recovering</li><li>Parameter changes</li><li>Phase transitions</li><li>Thermal expansion</li><li>Strong oxidants</li><li>Inert atmosphere</li><li>Composite materials</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b53eae4b5ec4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Baby steps in Reinforcement Learning — Q Learning]]></title>
            <link>https://medium.com/machine-learning-evaluation-metrics-precision/reinforcement-learning-q-learning-6c9c0648c309?source=rss-8a60e34ce17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c9c0648c309</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine]]></category>
            <dc:creator><![CDATA[Alex Yeo]]></dc:creator>
            <pubDate>Sat, 24 Jul 2021 09:02:54 GMT</pubDate>
            <atom:updated>2023-08-13T04:09:14.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>Baby steps in Reinforcement Learning — Q Learning</h3><p>Q learning. What is the definition of Q at the first place?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*7HwtaSxNVtA9gmbz0OTg2w.png" /><figcaption>Dr. Q</figcaption></figure><p>With these doubts in our mind, let’s start to crack these doubts one-by-one. First, we start with terminology:</p><ul><li><strong>State</strong> : position / situation ([Dark, Light…], [Head, Tail…])</li><li><strong>Action</strong> : action ([increase, stay, decrease]. Most of time is verb)</li><li><strong>Reward/Penalty</strong> : a score which is awarded to the taken action at that particular state.</li><li><strong>Policy</strong> : define the allowable actions from one state to another state.</li><li><strong>Quality of policies, Q-table</strong> : store the score of each policy based on the given reward.</li></ul><p>Usually, <strong>state</strong> can be used to define the positions or situations of an object. For example : when we flip a coin (Object), the coin can only be in either <strong>Head</strong> position or <strong>Tail</strong> position when it is landed on the floor.</p><p>Next, we would like to define the allowable <strong>actions</strong> that can be taken by the coin to change from one <strong>state</strong> to reach another <strong>state</strong>. we could have <strong>head-flip-tail</strong>, <strong>head-throw-tail</strong>, <strong>head-blow-tail</strong>… These allowable (state-action)s combination is called <strong>policies</strong>. But which policy is the best? To answer this question, we will construct a <strong>Q-table</strong> and assign a score to each policy. You might have question marks in your mind now. Let’s me clear your doubt with a state diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*xM_yXci-GPk1yiN8Pvpk9g.png" /><figcaption>Policy, action, state</figcaption></figure><p>In the policy, you specify that state_1 can only go to state_2 by taking action “increase”. Similarly, you also specify that state_3 can only go to state_2 by taking action “decrease”. Policy can be written in the list form as follow:</p><h4>policy 1 = [state_1, increase, state_2], <br>policy 2 = [state_2, increase, state_3], <br>policy 3 = [state_3, reduce, state_2], <br>policy 4 = [state_2, reduce, state_2]</h4><h4><strong>Q-table = [policy 1, policy 2, </strong>policy 3, policy 4<strong>]</strong></h4><p>I hope that policy, Q-table is clear to you now. Let’s crack the learning part of Q-table. This is an interesting part.</p><h4>The learning objective of Q-table is to select the best policy which is comprised of the best action at each state.</h4><p>Here, we need to know the definition of “<strong>best action</strong>”. “Best action” is the action that can give us the highest <strong>reward</strong>. Let’s me give you a scenario to visualise <strong>state</strong>, <strong>action</strong> and <strong>reward</strong>.</p><p>Exam season is coming. Usually, I study for 5 minutes. I increase my study time from 5 minutes to 10 minutes hoping to get good result and my parent will reward me with 1 dollar. If my result is poor, my parent will steal 1 dollar from my piggy bank. Such a bad parent!</p><p>On the exam day, I get a good result. This mean my action (<strong>increase</strong> 5 min to 10 min) is correct. This also convince me that I should always take “increase” action during exam season.</p><p>From this simple scenario, we clearly understand the states (5 min, 10 min), actions (increase, reduce) and reward (1 dollar). With full understanding of the terms, we can move to formulate this scenario where we will train the policy to always take the “increase” action at state_1(5 min) to optimise the reward(+ 1 dollar).</p><p>Initially, we will assign a random value to every action of every state. In programming language, we will assign random value to 2D arrays. Q[s][a] = random(). Then, we would like to update only the value of the taken action of the particular state. From our example earlier, we would like to update only the “increase” action taken from state_1(5 mins) using the formula below:</p><pre>Q[s][a] = Q[s][a] + ALPHA * (reward + GAMMA* maxQ[s_next][A] - Q[s][a] )</pre><p>This is a simple formula. Let’s me fill in the information from our example. This will be clearer and understandable.</p><pre>Q[5 min][increase] = Q[5 min][increase] + ALPHA * ( 1 dollar + GAMMA* max(Q[10 min][increase],Q[10 min][reduce]) - Q[5 min][increase])</pre><p>Basically, ALPHA is the learning rate. This is a constant where you can put any value to speed up the updating process. And GAMMA is the discounting factor that you want to assign to future state. The idea behind GAMMA is that, you want to select some percentage of future state to update your current state. Let’s say, you are 100% confident that the future state(10 min), regardless of what ever action, will affect my current state and action; then you can assign GAMMA to 1. Or, if you do not want the future state to affect my current state and action update, you could set the GAMMA to 0.</p><p>One more important thing to take note is the selection of best action in the next state using max function:<strong> max(Q[10 min][increase],Q[10 min][reduce]) function</strong>. In this function, we would like to select the maximum value from either Q[10 min][increase] or Q[10 min][reduce]. This is the gist in Q-learning. By now, I am sure that you have all the ingredients to update only the taken action of the particular state. If you are familiar with gradient descent, you may notice this formula is another form of gradient descent.</p><p>Q learning is as simple as that. If you are interested in the formula, you could dive deep into Bellman Equation. And here, I only explain the exploitation part which mean I will <strong>always</strong> increase 5 min study time during exam season. There is a possibility where we could reduce the study time and get good result. And what are the strategies that we could take to explore the “reduce” possibility? There are 3 strategies (<strong>Epsilon Greedy, UCB1 and Thomson sampling</strong>)explained here : <a href="https://alex-yeo.medium.com/reinforcement-learning-baby-steps-to-epsilon-greedy-and-ucb-1-ae84a5907f49">https://alex-yeo.medium.com/reinforcement-learning-baby-steps-to-epsilon-greedy-and-ucb-1-ae84a5907f49</a></p><p>If you find this article helpful, please like and share with your friends. Thank you!</p><p>You may also refer to this clip. <br><a href="https://www.youtube.com/watch?v=n-GsSNYOCJ0">https://www.youtube.com/watch?v=n-GsSNYOCJ0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c9c0648c309" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-evaluation-metrics-precision/reinforcement-learning-q-learning-6c9c0648c309">Baby steps in Reinforcement Learning — Q Learning</a> was originally published in <a href="https://medium.com/machine-learning-evaluation-metrics-precision">Machine Growth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>