<?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 Kevin Siswandi on Medium]]></title>
        <description><![CDATA[Stories by Kevin Siswandi on Medium]]></description>
        <link>https://medium.com/@kevinsiswandi?source=rss-40888f3ee19f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6fdxMgqPBlZnxYzJmQfdTQ.jpeg</url>
            <title>Stories by Kevin Siswandi on Medium</title>
            <link>https://medium.com/@kevinsiswandi?source=rss-40888f3ee19f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:50:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kevinsiswandi/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[Data Pipeline Engineering]]></title>
            <link>https://kevinsiswandi.medium.com/data-pipeline-engineering-58f4340b67f6?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/58f4340b67f6</guid>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 09:55:52 GMT</pubDate>
            <atom:updated>2024-09-22T08:51:31.004Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Miscellanous notes and learnings from architecting data pipelines in the modern data ecosystem.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RAYJWSGMmbdPfjE-" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Table of Contents</strong>:</p><p>— Overview<br>—Types of Data Pipeline<br> — ETL Pipeline<br> — Orchestration: Airflow<br> — Spark Pipelines</p><p>Data pipelines move data from one place, or form, to another. In one data pipeline, processes may include task scheduling or triggering, monitoring, workflow management, maintenance, optimization, etc. In the context of machine learning system, the pipeline that prepares and cleans raw data to create features is often referred to as the feature pipeline or ETL pipeline (depending on who you speak to).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*a6sPWrN2pCxGNj5yYOPBdQ.png" /><figcaption>Example architecture of an ETL pipeline (also called feature pipeline in MLOps space).</figcaption></figure><p>To work scalably with data pipelines, orchestration tools such as <strong>Apache Airflow</strong> are used to represent workflows as DAGs in code, which make our data pipelines more maintainable, testable, and collaborative.</p><p>In some use cases (such as cybersecurity), decisions must be made in real-time by the analysts, hence the need for stream analytics. Cloud Pub/Sub in GCP, for example, can be used to ingest and distribute streaming data. In general, ETL is an automated data pipeline engineering methodology to get and prepare data from multiple sources for downstream analytics, such as moving data from OLTP systems (that do not store historical data) to OLAP systems for analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5jbPfRoBPckey5Eq" /><figcaption>A real pipeline in the real world.</figcaption></figure><p>In this article, we discuss about the different tools and techniques that are used with ETL and data pipelines. In a typical enterprise environment, data might need to be integrated from disparate sources, multiple stakeholders requiring different analysis and insights, etc.</p><h3>Types of Data Pipeline</h3><p>Choosing the right data pipeline for a specific use case is a fine balance of latency, complexity, and quality. A system that processes data every minute is more like a REST API or server, compared to a CRON job that runs hourly or daily. The challenge is to ensure reliability, security, and integrity of data that are being acquired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*w2RJ8j40r8cdPqkOXjd3cA.png" /></figure><p>Some questions to ask to really understand the latency requirements and decide on batch/streaming pipeline:</p><ul><li>What is the impact of data delay?<br>➡️If the fallback is to use yesterday’s data, a batch pipeline is probably suitable here.</li><li>Are there automated responses from the data that are time-sensitive?<br>➡️If yes, it’s an indicator to use streaming. Example: threat detection.</li><li>Are there other engineers in the team who can help maintain streaming pipeline? If the answer is no, the result is frequent on-calls and burnout.</li><li>Typical use cases for streaming are: real-time recommendations, fraud detection, gaming events, and finance back office apps.</li></ul><p>When deciding between batch vs streaming data pipeline, consider also the emerging lambda architecture that combines both methods. It has 3 parts:</p><ul><li>a batch layer that takes historical data in batches.</li><li>a speed layer that streams real-time data.</li><li>a serving layer that integrates the batch and speed layers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*rSMtzm2hrwgTAdSp.png" /><figcaption>Example of a lambda architecture. Source: <a href="https://medium.com/@setiadi.gaiauser/journey-to-the-cloud-3-3-5806d3b4100">https://medium.com/@setiadi.gaiauser/journey-to-the-cloud-3-3-5806d3b4100</a></figcaption></figure><p>When there are multiple data streams, consider using parallel loading, esp. if the data is huge or travels long distances. Parallel loading also works on a single data file: split the file into smaller chunks for simultaneous loading.</p><ul><li>A strategy to handle unbalanced load on a pipeline is to use a non-linear (dynamic) pipeline. Here, we parallelize the slower stages by replicating them on multiple threads or CPU cores, distributing the data packets on these channels.</li><li>To synchronize the stages, I/O buffers are sometimes used to regulate the flow of data. They act as a holding area for data between processing stages, and used to distribute and gather loads on parallelized stages.</li></ul><h3>ETL Pipeline</h3><p>ETL (Extract, Transform, and Load) refers to the process of:</p><p><strong>E</strong>: curating data from multiple sources<br><strong>T</strong>: preparing the data for integration<br><strong>L</strong>: loading the data into a destination platform such as a data warehouse or an analytics environment.</p><p>ELT is a similar concept but loads the data in raw format, with the specific transformations to be applied at the discretion of the users in a <em>self-serve analytics</em> destination environment. In other words, the transformation step happens within the pipeline for ETL, but decoupled from the pipeline (i.e. happens in the target environment) for ELT.</p><p>ETL uses <strong>schema-on-write</strong>, where data must conform to a defined schema before loading into the relational DB. On the other hand, <strong>schema-on-read</strong> used in ELT applies the schema after reading the data. The transformation step in ETL can potentially result in information loss such as:</p><p>❌Lossy data compression<br>❌Filtering<br>❌Aggregation</p><h4>ETL Use Cases</h4><p>Typical use cases for ETL pipelines are:</p><ul><li>Digitizing analog data (e.g. paper documents, drawings, analog audio or video tapes) and storing them into a repository.</li><li>Capturimg data from OLTP system for analysis in OLAP system.</li><li>Integrating disparate structured data sources from APIs.</li><li>Preparing data sources (e.g. events via API) for ingestion by dashboards.</li><li>Cleaning data for training machine learning models.</li><li>Surveillance with edge devices (transferring only relevant features with edge computing) + data migration.</li></ul><p>An ETL pipeline could have an intermediate storage facility (a.k.a. <strong>staging area</strong>) for raw extracted data, where transformation processes are run prior to loading the result into a data warehouse/mart. IN ELT, this equivalent of a staging area is referred to as a data lake.</p><h4>ETL Techniques</h4><p>Data extraction is the first stage of the ETL process, where data is acquired from various source systems. Depending on the source of raw data, various <strong>data extraction tools</strong> exist, such as:</p><ul><li>OCR (to digitize text from paper docs),</li><li>Analog Digital Converter (ADC) sampling (to convert analog audio signals to digital),</li><li>Charged Coupled Devices (CCD) for digital imaging,</li><li>Surveys,</li><li>Logs/cookies,</li><li>Web scraping,</li><li>API (to source data from government databases, social networks, etc.)</li><li>Database querying</li><li>Edge devices</li><li>Genome sequencing</li></ul><p>In an ETL pipeline, the output from one process is the input to the next one (e.g. the extracted data is the input to the transformation step). There are a few common data transformation operations applied to raw extracted data:</p><ul><li><strong>Data typing</strong> casts data from one type to another, e.g. string to int,</li><li><strong>Data structuring</strong> converts one data format to another, e.g. XML to JSON,</li><li>Data anonymizing and encrypting,</li><li>Data cleaning removes duplicate records, filling missing values,</li><li>Normalizing converts data to a common unit,</li><li>Filtering, sorting, aggregating, binning, and joining/merging.</li></ul><p>The final step of an ETL pipeline, i.e. data loading has two forms.</p><p>🫷Pull: data warehouse pulls the data from source by subscribing (useful for scheduled extractions).<br>🫸Push: server pushes data to data warehouse (useful for real-time data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Ef_2JzwjE7ZLn2ds.png" /><figcaption>Example of an ETL pipeline on GCP. Source: <a href="https://cloud.google.com/blog/topics/developers-practitioners/orchestrating-your-data-workloads-google-cloud">https://cloud.google.com/blog/topics/developers-practitioners/orchestrating-your-data-workloads-google-cloud</a></figcaption></figure><h4>Incremental Loading: Streaming v.s. Batch</h4><p>Full loading refers to the process of loading an initial history into a new DB, marking the start of the tracking of transactions in the data warehouse. The subsequent loading of data that is appended to the existing data is referred to as <em>incremental loading, </em>which accumulates transaction history.</p><p>There are two kinds of incremental loading depending on the volume and velocity of data:</p><ol><li><strong>Batch pipelines</strong> extract and operate on batches of data.</li><li><strong>Streaming pipelines</strong> ingest data packets one-by-one in rapid succession, with continuous updates as the data arrives in real-time.</li></ol><p>Stream loading can be triggered by</p><ul><li>real-time data: sensor data from IoT devices or social media feed.</li><li>measures: data size (or other threshold values).</li><li>on-demand user requests: video or music streaming, web pages.</li></ul><p>On the other hand, batch loading is periodic (usually on a fixed schedule such as daily updates). A batch pipeline can be created with Bash scripts that can be run on a specific schedule using cron.</p><h3>Airflow: ETL Workflows as DAGs</h3><p>As a workflow orchestration tool, Apache Airflow breaks down the details of an ETL workflow into individual tasks and dependencies between those tasks. Airflow is used to programmatically author, schedule, and monitor workflows. It represents a workflow as a directed acyclic graph (DAG), and is essentially a configuation-as-code data pipeline platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*krRFlkqIsc0Ia5FZ.png" /><figcaption>Sample DAG in Airflow. Source: <a href="https://www.run.ai/guides/machine-learning-operations/apache-airflow">https://www.run.ai/guides/machine-learning-operations/apache-airflow</a></figcaption></figure><p>The key advantage of Airflow’s approach to representing data pipelines as DAGs is that they are expressed as code, which makes your data pipelines more maintainable, testable, and collaborative. Tasks, the nodes in a DAG, are created by implementing Airflow’s built-in operators:</p><ul><li><strong>Bash operators</strong> for running Bash code,</li><li><strong>Python operators</strong> for running Python code,</li><li><strong>SQL operators</strong> for running SQL queries</li></ul><p>while an edge represents the dependency between two tasks. There are different types of operators:</p><ul><li><strong>Sensor</strong> operators poll for a certain time or condition (e.g. check every 1 minute to see if a file exists or whether another DAG has finished).</li><li><strong>Email</strong> operators</li><li><strong>HTTP</strong> request operators</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9NT85ui3jl1UUNdG.png" /><figcaption>Basic Airflow architecture. Source: <a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/overview.html#airflow-components">https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/overview.html#airflow-components</a></figcaption></figure><p>Airflow scheduler deploys the DAG’s on an array of workers. The DAGs will start running based on the start date specified as code in each DAG, once a scheduler instance is started. The scheduler triggers subsequent DAG runs according to the specified schedule interval.</p><p>Workflow monitoring is an important aspect to ensure data integrity, and should cover:</p><ol><li>Latency (time taken to get past the pipeline)</li><li>Throughput (how many data packets can flow in a given period of time)</li><li>Warnings, errors, and failures</li><li>Utilization rate → how fully is the pipeline resources being used</li><li>Logging and alerting</li></ol><p>With Airflow, we create workflows with Python. Monitoring of the status of tasks happen through a web app UI. Ideally, a task should flow through the scheduler as so: no status → scheduled → queued → running → success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_6sU3Bl1qUViH79u.png" /><figcaption>Lifecycle of an Apache Airflow task state. Source: Airflow.</figcaption></figure><p>To start Airflow, simply do:</p><pre># start Apache Airflow with its web UI<br>start_airflow</pre><p>The Airflow pipeline is represented as a Python script, with the DAG, its tasks, dependencies, and scheduling instructions are defined as code in Python. The key components of a DAG definition file are:</p><ol><li>DAG arguments (e.g. schedule_interval )</li><li>DAG definition</li><li>Task definitions (by instantiating operators from airflow.operators )</li><li>Task pipeline</li></ol><p>In addition, we need to import the relevant Airflow libraries, a typical ones would look like:</p><pre># library imports<br><br># The DAG object to instantiate a DAG<br>from airflow import DAG<br><br># Operators to write tasks<br>from airflow.operators.bash_operator import BashOperator<br><br># Helper for scheduling<br>from airflow.utils.dates import days_ago</pre><p>DAG arguments specify settings for the DAG, for example:</p><pre>#defining DAG arguments<br><br># they can be overriden on a per-task basis during operator initialization<br>default_args = {<br>    &#39;owner&#39;: &#39;Jianhe Wu&#39;,<br>    &#39;start_date&#39;: days_ago(0), # days_ago(0) is today<br>    &#39;email&#39;: [&#39;work@jianhewu.com&#39;], # alerts are sent here<br>    &#39;email_on_failure&#39;: True, # should alerts be sent on failure<br>    &#39;email_on_retry&#39;: True, # should alerts be sent on retry<br>    &#39;retries&#39;: 1, # number of retries in case of failure<br>    &#39;retry_delay&#39;: datetime.timedelta(minutes=5) #pre-req: import datetime library<br>}</pre><p>To create a simple ETL pipeline with two tasks, we can start by defining the DAG and creating two Bash operators:</p><pre># define the DAG<br>dag = DAG(<br>    &#39;hello-world&#39;,<br>    default_args=default_args,<br>    description=&#39;A hello world extract, transform, and load pipeline.&#39;,<br>    schedule_interval=datetime.timedelta(days=1), #run daily<br>)<br><br># define the first task<br>extract = BashOperator(<br>    task_id=&#39;extract&#39;,<br>    # get the first, third, and sixth column in /etc/passwd<br>    bash_command=&#39;cut -d&quot;:&quot; -f1,3,6 /etc/passwd &gt; /home/jupyter/rawdata.txt&#39;,<br>    dag=dag,<br>)<br><br># define the second task<br>transform_and_load = BashOperator(<br>    task_id=&#39;transform-load&#39;,<br>    # convert the raw data into comma-separated values<br>    bash_command=&#39;tr &quot;:&quot; &quot;,&quot; &lt; /home/jupyter/rawdata.txt &gt; /home/jupyter/cleandata.csv&#39;,<br>    dag=dag,<br>)<br><br># task pipeline<br>extract &gt;&gt; transform_and_load</pre><p>In AIRFLOW_HOME directory, you can find airflow.cfg that contains Airflow configurations and the DAGS_FOLDER from which Airflow searches Python source files for DAG submission. Once you put the Python script containing the DAG above into the folder, the hello-world DAG would appear when you do airflow dags list. To see the tasks, do</p><pre>airflow tasks list hello-world</pre><p>Airflow logs can be stored locally and backed up into cloud storage, such as Google Cloud Storage, or Elastic Search for indexing, retrieval and analyis.</p><p>Airflow produces three metrics for monitoring components’ health:</p><ol><li><strong>Counters</strong> are metrics that always increase (e.g. total count of successful or failed tasks).</li><li><strong>Gauges</strong> are metrics that may fluctuate (e.g. the number of currently running tasks, DAG bag sizes, or number of DAGs in production.</li><li><strong>Timers</strong> are metrics related to time duration (e.g. time to finish a task).</li></ol><h3>Choosing Spark API for Your Pipelines</h3><p>Apache Spark is offered in three API’s:</p><ol><li>DataFrames</li><li>Datasets</li><li>SparkSQL</li></ol><p>SparkSQL is usually used for project that is built in collaboration with non-engineers with data sources that are already in a data warehouse. However, SparkSQL is not an ideal choice for pipelines that need modularity, such as:</p><ul><li>Interfacing with third party apps that are not tabular in nature, such as REST API’s, Kafka topics, etc.</li><li>Needing extensive unit and integration test coverage</li></ul><p>If you need third party integrations such as from REST API’s, an option is to use the DataFrame API. <a href="https://github.com/MrPowers/chispa">Chispa</a> also provides extensive unit and integration test coverage for PySpark. However, it doesn’t offer static typing guarantees that the Dataset API provides.</p><p>Datasets are the least common API (as it’s only in Java and Scala) since the rise of PySpark. However, it’s the most powerful especially for:</p><ul><li>CI/CD — unit testing is a breeze.</li><li>Integrations with JVM-based apps (backend like Spring Boot).</li><li>Heterogenous pipelines with many dependencies (to tap on dependency management such as Gradle).</li></ul><p>Having said that, due to the high learning curve for Scala, take note that the Spark Datasets API also has slower iteration cycle: uploading a built JAR is significantly slower than uploading a PySpark script or a SparkSQL.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58f4340b67f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HPC and Parallel Computing]]></title>
            <link>https://kevinsiswandi.medium.com/hpc-and-parallel-computing-2d55c919034d?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d55c919034d</guid>
            <category><![CDATA[high-performace-computing]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 06:07:37 GMT</pubDate>
            <atom:updated>2024-07-01T06:07:37.687Z</atom:updated>
            <content:encoded><![CDATA[<p>This article introduces the fundamentals of high-performance and parallel computing, including:</p><ul><li>Components of a distributed HPC system</li><li>Types of parallel programming models: data v.s. task parallelism</li><li><strong>Shared</strong> vs <strong>distributed</strong> vs <strong>hybrid memory parallelism</strong></li><li>Speedup, efficiency, and (weak/strong) scaling</li><li>Compute, data, and cost requirements for a project or workflow</li></ul><p>💡For high throughput computing with many small jobs, refer to the Open Science Grid <a href="https://osg-htc.org/">https://osg-htc.org/</a>.<br>📃See also SLURM docs at <a href="https://slurm.schedmd.com/sbatch.html">https://slurm.schedmd.com/sbatch.html</a><br>🕸️Check out my blog at <a href="https://hpc-sw.blogspot.com/">https://hpc-sw.blogspot.com/</a>.</p><p>Also, check out my blog at <a href="https://hpc-sw.blogspot.com/">https://hpc-sw.blogspot.com/</a>.</p><h3>Node Types</h3><p>An HPC infrastructure consists of login node, compile nodes, and compute nodes. Login node is great for script editing and job submission, but not to be used for heavy computation or running memory intensive applications. The compile nodes have the same software stack as the compute nodes, so it is the place to compile C, C++, or Fortran code. However, some languages such as Matlab, Python, and R do not need compilation.</p><p>Compute nodes are where the submitted jobs run, and are accessible only through job scheduler (e.g. SLURM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oV23iqTHDnhNZMZw.png" /><figcaption>Source: <a href="https://www.marquette.edu/high-performance-computing/architecture.php">https://www.marquette.edu/high-performance-computing/architecture.php</a></figcaption></figure><p>There are two job types:<br><strong>Batch jobs</strong>: a job that is submitted to a queue, creating a text file containing information about the job. Batch jobs are run when resources are available.<br><strong>Interactive jobs</strong>: interactive command line at the compute node.</p><h3>Scheduling</h3><p>Simple Linux Utility for Resource Management (SLURM) distributes jobs on a supercomputer and manages the resources. It keeps track of which nodes are busy/available, and which jobs are running/queued.</p><p>To submit a batch job to SLURM, use the sbatch command. The syntax is</p><pre>sbatch &lt;options&gt;</pre><p>The list of options available is in <a href="https://slurm.schedmd.com/sbatch.html">https://slurm.schedmd.com/sbatch.html</a>. In addition, you may want to set SLURM environment variables such as:</p><ul><li>$SLURM_NTASKS</li><li>$SLURM_MEM_PER_CPU</li></ul><p>which can be passed to your script or programs (instead of hardcoding the numbers). To view information about jobs in the SLURM scheduling queue, use the squeue command. For example, the following checks for the jobs submitted by user kevin:</p><pre>squeue --u=kevin</pre><p>The output provides information about the job ID, the partition (i.e. which group of nodes the job is running on — e.g. can be a set of nodes with higher memory, certain kinds of processors, or more memory), status, nodes, etc.</p><p>A sample SLURM bash script is below:</p><pre>#!/bin/bash<br>#SBATCH --time=00:01:00<br>#SBATCH --nodes=4<br>#SBATCH --ntasks-per-node=1<br>#SBATCH --output=slurm1.txt<br><br>cd $HOME/scratch<br>pwd<br>echo $SLURM_NODELIST<br>echo $SLURM_NTASKS_PER_NODE<br><br>module purge<br>module load mpich<br><br>mpif90 myfortran.f90 -o myfortran.out<br>mpirun -np 4 ./myfortran.out</pre><p>Here, the job compiles and executes a Fortran script that uses the Message Passing Interface (MPI) library to run simple parallel calculations.</p><h3>Message Passing Interface</h3><p>Below is a Fortran script that prints “Hello World” on every core it is run on and then performs natural exponential based on the rank of the process.</p><pre>PROGRAM hello<br><br> USE mpi<br><br> INTEGER, PARAMETER:: dp=KIND(0.d0)<br><br> INTEGER ::  ierr, comm_size, comm_rank, length<br> REAL(dp) :: RESULT<br> CHARACTER (len=MPI_MAX_PROCESSOR_NAME) :: proc_name<br><br> CALL MPI_Init(ierr)<br> CALL MPI_Comm_size(MPI_COMM_WORLD, comm_size, ierr)<br> CALL MPI_Comm_rank(MPI_COMM_WORLD, comm_rank, ierr)<br> CALL MPI_Get_processor_name(proc_name, length, ierr)<br><br> WRITE(*,*) &quot;Hello World from process = &quot;, comm_rank, &quot; on processor &quot;, proc_name<br><br> RESULT = EXP(REAL(comm_rank, dp))<br><br> WRITE(*,*) &quot;Exp(&quot;, comm_rank, &quot;) = &quot;, RESULT<br><br> CALL MPI_Barrier(MPI_COMM_WORLD, ierr);<br> IF (comm_rank == 0) THEN<br>    WRITE(*,*) &quot;Number of mpi processes = &quot;, comm_size<br> ENDIF<br> CALL MPI_Finalize(ierr);<br><br>END PROGRAM hello</pre><p>To improve efficiency of your program, it is helpful to time it. The primary candidate for timing is loops, as loops are often the bottleneck. To time the entire program, one can also use the Linux time command:</p><pre>time mpirun -np 4 ./myprogram.mpi</pre><p>The output of the time command is:</p><ol><li>real: wall clock time</li><li>user: the sum of wall clock time used by all threads</li><li>sys: system overhead</li></ol><p>To time a part of the program (fine-grained timing), one can use the built-in functions available in the programming language, for example:</p><ul><li>Python: time.time()</li><li>R: sys.time()</li><li>C++: clock()</li><li>Fortran: system_clock()</li></ul><p>A problem can be broken down into a set of discrete instructions. In serial processing, only one instruction is executed at a time on a single processor. In parallel processing, many instructions are carried out simultaneuously across a computing system. The speedup of parallel processing is at most n times if there are n processors (with diminishing return as n increases) due to factors such as communication overhead and resource contention.</p><p>Other than communication overhead, there might also be other overheads:</p><ul><li>startup time</li><li>synchronizations</li><li>libraries and/or compilers</li><li>termination time</li></ul><h3>The Many Kinds of Parallelism</h3><p>Parallel processing can be achieved using one of two interfaces:</p><ol><li>OpenMP — Parallelism across processors/threads.</li><li>MPI — Parallelism across multiple nodes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*uFSuz33IS9t0Iwcu.png" /><figcaption>Distributed memory model. Source: <a href="https://help.rc.ufl.edu/doc/Memory:_Shared_vs_Distributed">https://help.rc.ufl.edu/doc/Memory:_Shared_vs_Distributed</a></figcaption></figure><p>Three common types of parallel memory models are:</p><ol><li>Shared — all cores share the same pool of memory<br>👍Benefit: data sharing is fast<br>👎Drawback: memory contention by multiple processors</li><li>Distributed — each core has its own memory and shares data through network connection and/or communication protocol (e.g. MPI)<br>👍Benefit: scalability (no resource contention as # processors goes up)<br>👎Drawback: complex/tedious programming for data relocation</li><li>Hybrid — blend of shared and distributed memory model (which is most HPC clusters today).<br>👍Benefit: scalability<br>👎Drawback: high programming effort for inter-node communication (e.g., MPI)</li></ol><p>In MPI with a distributed memory system, the programmer must explicitly manage the remote memory access. Similarly, we also distinguish between:</p><ul><li><strong>Data parallelism</strong> ➡ distribute the data across processors (for e.g., split the elements of an array onto node 1 and node 2). There are two types of data parallelism as follows.<br>1. <strong>SIMD (Single Instruction, Multiple Data)</strong>, where the same instruction (vector operation) is carried out simultaneously on different elements of the dataset, e.g. addition, subtraction, multiplication, and division.<br>2. <strong>SPMD (Single Program, Multiple Data)</strong>: the same program is carried out multiple times on different elements of the dataset. Ex: calculate the wind direction from wind components.</li><li><strong>Task parallelism</strong> ️️➡ distribute the compute tasks (on the same dataset) among processors (a.k.a. distributed programming).</li></ul><p>For a comprehensive tutorial on parallel computing, check out the tutorial at <a href="https://hpc.llnl.gov/documentation/tutorials/introduction-parallel-computing-tutorial">https://hpc.llnl.gov/documentation/tutorials/introduction-parallel-computing-tutorial</a>.</p><h3>ROI of Parallelization</h3><p>Speedup is defined as the ratio of serial runtime to the parallel runtime of a problem, with the parallel runtime dependent on # processors (N):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/0*d8a-gt567ILKMpRz" /><figcaption>Source: <a href="https://hpc-wiki.info/hpc/Scaling">https://hpc-wiki.info/hpc/Scaling</a></figcaption></figure><p>In the ideal case where there are no overhead and resource contention, we would have linear speedup. To measure speedup, one can run test problem at multiple core counts and measure the elapsed time t(N).</p><p>Efficiency is defined as the amount of time that a processor is usefully utilized, i.e. efficiency = expected_time/actual_time. The expected time is problem-dependent:</p><ul><li>For contant problem size, expected time is t(1)/N.</li><li>For problem size that increases with number of cores, expected time is simply t(1).</li></ul><p>For the perfect speedup (linear scaling), the parallel efficiency is 1.</p><p>Scalability is the measure of how well a program uses multiple processors to reduce time to solution or solve a larger problem. There are two types of scaling as follows.</p><ol><li>Weak scaling: increase problem size alongside the number of cores</li><li>Strong scaling: increase core count while fixing the problem size</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*lL-aI6K_H9vbHirj" /><figcaption>Source: <a href="https://cvw.cac.cornell.edu/parallel/efficiency/scaling">https://cvw.cac.cornell.edu/parallel/efficiency/scaling</a></figcaption></figure><p>Weak scaling indicates if one can solve a larger problem (when core count is independent of time to solution), while strong scaling tells us if we can reduce the time to solution (ideally by 1/N, i.e. linear speedup).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/0*5Z_uMxxDJMKCjrO0" /><figcaption>Source: <a href="https://cvw.cac.cornell.edu/parallel/efficiency/scaling">https://cvw.cac.cornell.edu/parallel/efficiency/scaling</a></figcaption></figure><p>Usually, there is a diminishing return at large core counts due to overhead. Hence, it might be useful to also monitor the efficiency against core count to ensure that efficiency doesn’t drop much (e.g. maintain it at &gt; 80%). This could happen due to reasons such as:</p><ul><li>dependencies (algorithmic limitations)</li><li>bottlenecks on the computer system (due to shared resources such as execution units in a core, shared path to main memory, or I/O devices).</li><li>startup/shutdown overhead</li><li>communication (data exchange) overhead</li><li>load imbalance (when some workers reach synchronization points earlier than the others), resulting in idle processors while waiting for other processors to finish computation.</li><li>OS jitter (noise in the operating system due to separate OS being run on each node which can arise from cron jobs, log files read/write, and disk flush).</li></ul><p>One common way to reduce communication overhead is by overlapping communication and computation to hide the communication cost.</p><p>For further reading on scalability, including Amdahl’s and Gustafson’s law, check out <a href="https://www.kth.se/blogs/pdc/2018/11/scalability-strong-and-weak-scaling/">https://www.kth.se/blogs/pdc/2018/11/scalability-strong-and-weak-scaling/</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d55c919034d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Primer to Language Model]]></title>
            <link>https://kevinsiswandi.medium.com/a-primer-to-language-model-eaf4b41aec5f?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaf4b41aec5f</guid>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 17:07:11 GMT</pubDate>
            <atom:updated>2024-04-25T10:00:48.774Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Language modeling is the foundation to large models such as GPT.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ysJfHc3CJQRhnmAp" /><figcaption>Photo by <a href="https://unsplash.com/@joshua_hoehne?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A language model measures the probability of a piece of text given a corpus (reference text).</p><p>🟢 Causal Language Model = measures the probability of the next word</p><p>🟢 Masked Language Model = measures the probability of a word masked out in the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*o7z5ZxavbwXr9EjP.png" /><figcaption>MLM from Bert. Source: <a href="https://www.sbert.net/examples/unsupervised_learning/MLM/README.html">https://www.sbert.net/examples/unsupervised_learning/MLM/README.html</a></figcaption></figure><p>🟢 N-Gram Language Model = measures the number of times the N-gram sequence appears in the corpus (i.e. maximum likelihood estimation of the exact sequence).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*JkXK2csEMnZr0YjKOe6hug.png" /><figcaption>Probabilities of an entire sequence of N-gram. Source: <a href="https://web.stanford.edu/~jurafsky/slp3/3.pdf">https://web.stanford.edu/~jurafsky/slp3/3.pdf</a></figcaption></figure><p>There are two ways to evaluate a language model:</p><ol><li>Intrinsic evaluation = how well the model estimates the probability on a held-out text</li><li>Extrinsic evaluation = how well the model helps perform another task.</li></ol><p>Intrinsic evaluation can be measured on the validation/test set using perplexity, which indicates how “surprising” the text is.</p><ul><li>Low perplexity: high probability for the text (less surprising)</li><li>High perplexity: low probability for the text (more surprising)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*cY8Odug5dJ__2JKq.jpeg" /><figcaption>Formula for perplexity. Source: <a href="https://community.deeplearning.ai/t/confused-about-perplexity-formula/205866/3">https://community.deeplearning.ai/t/confused-about-perplexity-formula/205866/3</a></figcaption></figure><p>For extrinsic evaluation, a typical task to test the language model is to do basic arithmetic: e.g. what’s 1 + 2 equal to?</p><ul><li>Use established benchmarks for extrinsic evaluation.</li><li>The test set should not be part of training data.</li></ul><h3>Text Generation in Tradional Language Models</h3><h4>Greedy Search</h4><p>A simple generation strategy is the greedy search (iteratively generate the most likely word given the previous text).</p><p>✅Pros: simple and deterministic.</p><p>❌Cons:</p><ul><li>doesn’t necessarily lead to the overall highest probability sequence.</li><li>tend to generate short and uninteresting text.</li></ul><h4>Beam Search</h4><p>Beam search builds on the greedy search to keep the k-highest probability sequences (i.e. greedy search is beam search with k=1).</p><p>✅Pros: deterministic and can generate higher-probability sequences than greedy search.</p><p>❌Cons:</p><ul><li>more computationally expensive than greedy search.</li><li>tend to generate bland or uninteresting text.</li></ul><h4>Sampling</h4><p>Sampling randomly chooses the next word, weighted by probability.</p><p>✅Pros:</p><ul><li>generates more interesting sequences</li><li>can be combined with other text generation strategies.</li></ul><p>❌Cons: not deterministic</p><p>As a side note: I built a next-word prediction app based on N-gram back in 2014. To use it, simply enter at least two words, and it will suggest some possible next words. The app is built to be simple, fast (near-instantaneous result), reactive (possesses prediction reactively as user types input) and lightweight (minimal RAM and CPU requirement). However, the app is hosted on the free shinyapps.io platform, hence it may take some time to load when accessing it for the first time.<br>Here’s the link to the app ➡️ [<a href="https://kevinsis.shinyapps.io/wordapp/">https://kevinsis.shinyapps.io/wordapp/</a>]</p><h3>The Transformer Architecture</h3><p>To begin with, we need to represent text as numerical vectors, where words with similar meanings be represented as similar vectors (vector similarity can be defined with e.g., Euclidean or cosine distance). This is where word embeddings come into play, as it allows the computational processing of N-dimensional word vectors.</p><p>The word vectors should also consider the context, as the same words may mean different things in different contexts → the notion of context vectors.</p><h4>Tokenization</h4><p>Tokenization is the splitting a block of text into smaller texts called tokens. The popular method is to use subword tokens (as splitting into words is not enough but splitting into individual characters is overkill). Algorithms such as Byte-Pair Encoding (BPE) can be used for subword tokenization that also handle new words as follows.</p><p>Strategies to deal with new words: split uncommon words into two or more subwords, as the individual subwords are likely more common and seen by the model, the subwords can often give a clue to the meaning of new word. Example: <strong>crypto</strong>currency, <strong>deep</strong>fake, etc. Furthermore, the subword tokens are to be represented using context vectors.</p><h4>Self-attention Mechanism</h4><p>The objective of a neural language model can be either to predict the next token in the sequence, or to calculate the probability of a whole sequence of text. The input to the neural network is the word embeddings, they are transformed via a series of nonlinear operations to produce a token output (probability scoring is typically done via softmax).</p><p>Neural language models may store a lookup of vectors for every token, then use a context vector maker to contextualize them into context vectors. This context vector maker also weights the importance of other words to decide on the meaning to use for a word that might have multiple meanings. Here, we need a function to calculate the relevance of one word for the context of another word, given the word vectors (without context) as the input.</p><p>The context vector for a particular word is then just a linear combination of transformed word vectors, with weighting based on the relevance scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*M9-2u4AVCOoT-xt8.png" /><figcaption>The transformer block. Source: Wikipedia.</figcaption></figure><p>The transformer block uses self-attention in the following way:</p><ul><li>use positional encoding to include information about position of tokens.</li><li>include a feed-forward neural network to introduce nonlinearity.</li><li>stack multiple self-attention layers to get multi-head attention: lower transformer layers likely dealing with basic syntax, and the higher level layers dealing with more complex reasoning. LLM models such as GPT3 may have 96 layers.</li></ul><h4>SESAME Street: BERT (vs. GPT)</h4><p>Transformer training works well because:</p><ul><li>it parallelises (previous approaches are serial — one word at a time).</li><li>it can be trained effectively with GPU/TPU (which PyTorch and TF does).</li></ul><p>BERT (Bidirectional Encoder Representations from Transformers) focus on masked language modeling. The context vector maker used by BERT is the encoder transformer that produces ready-to-use context vectors (for e.g., to another classifier for sentiment analysis using CLS token).</p><p>GPT focuses on causal language modeling using the decoder architecture. The text given to a causal language model is known as a prompt. However, other language models may have been trained for e.g., instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*b3-qoKAwSkDigqBVb2V5aw.png" /><figcaption>Source: Wikipedia.</figcaption></figure><p>Aside: <a href="https://openai.com/research/instruction-following">the trend of using Sesame Street characters</a> to name LLM’s started with ELMo (by Allen Institute) in 2017, then BERT (by Google) in 2018, soon followed by ERNIE, KERMIT, and so on.</p><h3>Practical Aspects of Working with LLM</h3><p>Large Language Models (LLM), such as GPT-3 and beyond, can do broad tasks when given some examples (a.k.a. few-shot) or even no examples (i.e. zero shot) without any gradient updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*oDE8JvDzFzrt5BK_" /><figcaption>Source: <a href="https://arxiv.org/abs/2005.14165">https://arxiv.org/abs/2005.14165</a></figcaption></figure><p>As training an LLM from scratch can be prohibitively expensive, use pre-trained models that can be downloaded using the Python transformers library from HuggingFace.</p><p>When deploying an LLM-based application, note also of two well-known problems: <a href="https://www.ibm.com/topics/prompt-injection">prompt injections</a> and <a href="https://en.wikipedia.org/wiki/Hallucination_(artificial_intelligence)">hallucinations</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FKQFCINjjsSMbSgf.jpg" /><figcaption>Prompt injection attack on Bing Chat. Source: <a href="https://arstechnica.com/information-technology/2023/02/ai-powered-bing-chat-spills-its-secrets-via-prompt-injection-attack/">https://arstechnica.com/information-technology/2023/02/ai-powered-bing-chat-spills-its-secrets-via-prompt-injection-attack/</a></figcaption></figure><h4>Reinforcement Learning with Human Feedback (RLHF)</h4><p>In reinforcement learning, we define a way to obtain a reward (the higher the better) for each output. Similarly, in RLHF, the language model is fine-tuned to maximise expected rewards across all outputs. Here, we prepare a dataset of pairwise comparisons to train human preferences as a separate NLP problem. Note that RLHF agents are rewarded for responses that are preferred by humans, but not necessarily factual (i.e. it can still hallucinate but the output is improved).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGK69Kn804PfhHacty62qw.png" /><figcaption>RLHF to train InstructGPT. Source: <a href="https://openai.com/research/instruction-following">https://openai.com/research/instruction-following</a></figcaption></figure><h3>Contact the Author</h3><p>If you would like to scale up your organization’s LLMOps capability, feel free to contact me.</p><p>👆<a href="https://github.com/physicist91">https://github.com/physicist91</a><br>👆<a href="https://www.linkedin.com/in/kevinsiswandi/">https://www.linkedin.com/in/kevinsiswandi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaf4b41aec5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Productionalising Machine Learning Models]]></title>
            <link>https://kevinsiswandi.medium.com/productionalising-machine-learning-models-8ba95fc65457?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba95fc65457</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 10:36:10 GMT</pubDate>
            <atom:updated>2024-06-24T15:16:03.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SbjjsxV2z3Xp_D9l" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Productionalization of a machine learning model demands a considerable engineering effort. While model prototyping typically focuses on accuracy metrics, deploying a model to production would also consider additional operational metrics so as to optimize inference, such as:</p><ol><li><strong>Latency</strong>, which is the time taken for the model to process a single input and produce a prediction, or the delay between sending a request to the model and receiving the response. Latency is important for real-time or interactive applications, such as chatbot or live STT transcriptions.</li><li><strong>Throughput</strong>, which is the number of inference requests the model can handle in a given time period. Throughput is important for applications with high volume of requests, for e.g. social media or e-commerce apps.</li><li>Runtime (for batch inference).</li><li><strong>Resource utilization</strong>, such as the amount of memory the loaded model takes up. This is important e.g., for deployment in edge devices where the hardware specs are limited.</li></ol><p>Hence, the productionalization effort must strike a balance between model complexity (which correlates with accuracy) and practical challenges (such as scalability and ease of maintenance), following MLOps best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*zuH2kPizc-l7kg40.png" /><figcaption>The Machine Learning Lifecycle. Source: <a href="https://www.datascience-pm.com/the-genai-life-cycle/">https://www.datascience-pm.com/the-genai-life-cycle/</a></figcaption></figure><h3>Deployment Strategies</h3><p>Typically, the output of a model development phase is twofold:</p><ol><li>model artifact</li><li>inference script (perhaps a .py) that loads the model artifact, does the necessary data preprocessing/feature engineering, and use the features to generate predictions.</li></ol><p>Now, the main objective of model deployment is to serve the model so that it is available for inference (i.e. return predictions upon an inference call). This is usually done using a REST API (e.g. FastAPI or Flask wrapper) that is packaged into a Docker container, ready to be shipped to production (such as a compute engine).</p><p>Some popular tools to help with this are the following.</p><p>🐦<a href="https://github.com/microsoft/hummingbird">Hummingbird</a>: converts scikit-learn models that run only on one single CPU core into tensor computations so as to allow for parallelization (such as inference on a GPU).<br>🌍<a href="https://www.modelbit.com/">Modelbit</a>: returns an API endpoint that is ready to serve end users upon deployment request from a Jupyter notebook.<br>🔦<a href="https://pytorch.org/docs/stable/jit.html">TorchScript</a>: runs PyTorch models in script mode (c.f. eager mode used for prototyping that is Python-centric) language agnostic and more suitable for deployment.</p><h4>Model Compression</h4><p>In many cases, deploying the exact same model as it was in development is probably not practical. Rather, model compression techniques are used to achieve lower inference latency (hence faster predictions), reduced computational cost (better scalability), and smaller memory footprint in production settings.</p><p>The most common ones are:</p><ul><li><strong>Knowledge distillation</strong> (a.k.a. teacher-student model), which have many use cases for LLM, such as <a href="https://huggingface.co/docs/transformers/model_doc/distilbert">DistillBERT</a>, a student model of <a href="https://arxiv.org/abs/1810.04805">BERT</a>. Being 40% smaller than the teacher model, <a href="https://arxiv.org/abs/1910.01108">DistillBERT still retains 97% of the NLU capability of BERT</a> and is 60% faster in inference.</li><li>Quantization</li><li>Pruning</li><li>Low-rank factorization</li></ul><h4>MLOps</h4><p>MLOps is a set of best practices and workflows that helps machine learning practitioners to move prototypes to production environments effectively. A typical workflow would look like:</p><ol><li>Use version control such as Git to track code changes. The new model is to be pushed to a new branch. A pull request is then opened to merge it to the master branch. This is important because in a typical production environment, the master branch contains the code version that is being deployed in the REST API.</li><li>Trigger a Continuous Integration pipeline (e.g. via Github Actions) when a pull request is opened. The CI pipeline will run unit tests, execute the training script to produce model artifacts, and validate the model (using for e.g., <a href="https://github.com/Giskard-AI/giskard">Giskard</a>).</li><li>If the CI tests pass, the model is automatically pushed to model registry and the branch gets merged to master.</li><li>Trigger a Continuous Deployment pipeline (e.g. via Github Actions) that builds a Docker image using the Dockerfile in the repo and pushes it to a container registry. The deployment to the desired compute engine can be done via Kubernetes by kubectl apply -f a manifest file.</li></ol><p><strong>Integration Testing</strong>: end-to-end testing of ML systems is usually performed by deploying it onto a so-called <strong>staging</strong> environment to get a staging REST API where requests are sent and metrics are logged. Here, the accuracy and latency of the responses are evaluated.</p><p><strong>Production Testing</strong>: if the ML system passes the integration tests, it will be further tested in production. There are several variants of this:</p><ol><li>AB Test</li><li>Shadow Test</li><li>Canary Deployment</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kiE1uEHd_Gae30bW" /><figcaption>Photo by <a href="https://unsplash.com/@jcotten?utm_source=medium&amp;utm_medium=referral">Joshua J. Cotten</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In AB test and canary deployment, often there’s an API gateway that routes incoming requests to either the existing model in production (base model) or the model to be evaluated (test model). The performance of each model is then monitored and compared. In a canary deployment, a small fraction of requests is routed to the canary model (e.g. 5%) to mitigate risks.</p><p>Now, productionalization doesn’t stop at hosting the model somewhere and obtaining an API endpoint…</p><h3>Post-deployment Considerations</h3><p>Post-deployment tasks that the team might take include:</p><ol><li>Identifying better features for the model</li><li>Fine-tuning the hyperparameters</li><li>Optimizing the deployment infrastructure</li><li>Collecting and labeling new data</li><li>Retraining the model to adapt to changing conditions (e.g. via adaptive learning).</li></ol><p>To do those tasks effectively, we will need the tools below.</p><h4>Version Control</h4><p>To effectively collaborate in a team and ensure reproducibilty of results, we need version control.</p><p>In ML projects, we need git-based functionalities not just for the codebase but also for the data, models, and other artifacts. This includes rolling back to the previous version of the model when it starts underperforming, and to track the dependencies across multiple versions of code, configurations, data, model, etc.</p><h4>CI/CD</h4><p>In software engineering, CI/CD involves building, testing, and deploying code efficiently. In a Machine Learning system, the CI pipeline may have:</p><ol><li>Automatic code checking</li><li>Automatic builds</li><li>Automatic testing</li></ol><p>The automated verification processes might kick in once the changes are committed to the repository. On the other hand, the CD of an ML system involves automation of the deployment process (e.g. to the API endpoint) so that the updated model is available to the end users.</p><h4>Model Monitoring</h4><p>Some risks that machine learning models face in production are:</p><ol><li>Training-serving skew due to mismatch between training data and input data in production. This would manifest itself immediately after moving into production.</li><li>Model decay over time. Identify model decay rate by doing analytics for the optimal retraining strategy.</li><li>Excessive latency due to volume of input data, data pipeline process, or choice of model.</li><li>Concept drift resulting from shift in the relationship between input and output, such as changes in preference or consumer behaviour.</li><li>Data drift due to shifting distribution of features that can occur slowly or quickly over time, such as population shifts or adversarial reactions (e.g. spam identification). Mitigation strategies include reweighting the training data, or using domain adaptation techniques.</li><li>Nonstationarity. Mitigation strategies include adaptive learning.</li></ol><p>To address the issues above, the deployed model needs to be continously monitored (e.g. using proper logging) for:</p><ol><li><strong>Model outputs and predictions<br></strong>🟢 Monitoring of model performance metrics over time to identify the optimal retraining frequency.<br>🟢 Monitoring of distribution of predicted values v.s. the actual values to identify potential concept drift (or just bias).<br>🟢 Monitoring of model performance across different subgroups to get consistent performance in all subgroups.<br>🟢 Inspecting of impact of different features for generating predictions, e.g. with feature importance, SHAP or LIME.</li><li><strong>Input data<br>🟢 </strong>Basic quality checks such as schema/encoding, expected volume of data, numeric values within range, missing values, and so on.<br><strong>🟢 </strong>Data distribution monitoring (via visualization or statistical tests) to flag potential data drift.<br><strong>🟢 </strong>Correlation of features to target to identify potential concept drift.</li><li><strong>Data pipeline</strong><br>🟢 Monitoring of disparities between training data and data used for inference in production.<br>🟢 Monitoring of data distribution pre- and post- processing.<br>🟢 Sanity check of feature values prior to model training.</li><li>Resource utilization</li><li>Latency</li></ol><h4>Containerization</h4><p>Dockerization is often use to encapsulate the entire environment for the ML system, including dependencies, libraries, and configurations. This would ensure that the same environment can be replicated across the dev, staging and production by providing a way to document/track the versions of all software components, libraries, and dependencies.</p><h3>Notebook Prototype vs Live System</h3><p>Typically, Machine Learning scientists are very good in building algorithms and experimentation but may not have deep skills in software engineering, MLOps, or infrastructure management. On the other hand, engineers who specialize in deployment may not have in-depth knowledge of the ML algos to make code changes and optimizations.</p><p>This issue makes it challenging to scale ML models in production that has an impact on performance and reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*LiICk3WUO4io6E02" /><figcaption>Example of an ML system on Google Cloud.</figcaption></figure><p>In a nutshell, the two primary objectives of productionalization are</p><ol><li>optimize the model for deployment.</li><li>ensure robustness and reliability of the system.</li></ol><p>This involves testing the system against various edge cases and scenarios to ensure that it can gracefully handle unexpected inputs and situations. Once the model is in production, it needs ongoing support such as:</p><ul><li>Monitoring systems and processes (e.g. Prometheus + Grafana)</li><li>Model maintenance (e.g. retraining and updating)</li><li>Model versioning</li></ul><p>Such ops support would require commitment from the data science team members. Moreover, the team must also support users of the ML systems by providing documentation, conducting user training, explaining model predictions, and guiding users on recourse for model issues.</p><p>Feel free to hit me up if your organization needs help with end-to-end data science and machine learning:</p><p>👆 <a href="https://www.linkedin.com/in/kevinsiswandi/">https://www.linkedin.com/in/kevinsiswandi/</a><br>👆 <a href="https://github.com/physicist91">https://github.com/physicist91</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba95fc65457" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can we predict deadly chronic disease early using data science?]]></title>
            <link>https://kevinsiswandi.medium.com/can-we-predict-deadly-chronic-disease-early-using-data-science-d43ac55bea97?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d43ac55bea97</guid>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Fri, 21 May 2021 16:50:12 GMT</pubDate>
            <atom:updated>2021-05-21T16:50:12.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nV4adfTSkcsl2UJA" /><figcaption>Photo by <a href="https://unsplash.com/@nhiamoua?utm_source=medium&amp;utm_medium=referral">Nhia Moua</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Chronic Obstructive Pulmonary Disorder is currently one major causes of death worldwide. It also poses <a href="https://pubmed.ncbi.nlm.nih.gov/17765526/">a global public health challenge</a> due to its high prevalence — bringing mortality, disability, and socioeconomic burden to high income and low income countries alike. As we abolish infectious diseases, the rates of chronic diseases such as cardiovascular diseases have also increased, particularly in regions with high levels of urbanization and industrialization (such as China, India, Mexico, Brazil, etc.). Early diagnosis and prevention of non-communicable diseases is thus important. In this article, we will focus on COPD and take a data-driven approach to predict COPD development.</p><p>The widely regarded gold-standard for COPD diagnosis is <a href="https://en.wikipedia.org/wiki/Spirometry">spirometry</a>, we say that a patient has COPD if the forced expiratory volume (FEV) is less than a certain threshold value. While the most important risk factor for COPD is smoking, other risk factors also play an important role, such as occupational exposure to fumes, dust, air pollution, as well as genetic factors and lifestyle habits (i.e. physical activity and diet). In fact, <a href="https://pubmed.ncbi.nlm.nih.gov/20802169/">several people with COPD</a> have never smoked in their life. Although lung function is the gold standard for a clinical diagnosis of COPD, it alone is still <a href="https://pubmed.ncbi.nlm.nih.gov/28492202/">not sufficient for an early detection</a>.</p><p>Meanwhile, the possibility of developing a <a href="https://www.nature.com/articles/s41591-018-0335-9">risk model</a> that takes into account a combination of the known risk factors and genetic polymorphisms for diagnosing and predicting diseases has been met with some success. Here, we use data consisting of DNA polymorphisms and clinical features from a <a href="https://translational-medicine.biomedcentral.com/articles/10.1186/s12967-020-02312-0">clinical study </a>with <strong>441 COPD patients and 192 healthy controls in Chinese hospitals </strong>to develop a predictive model for COPD development.</p><h3>Part I: What does the data suggest about the risk factors for COPD?</h3><p>Comparing COPD patients and healthy controls in the dataset, one can see rather significant differences in age, gender, and smoking status. BMI levels are however similar in both groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*Q8g04RdIm_w2zUmcCcCRQQ.png" /><figcaption>Figure 1: Proportion of people smoking, BMI, age, and proportion of male in both COPD patients (orange) and healthy controls (blue).</figcaption></figure><p>The results suggested that COPD patients were more likely to be men than women, older, and smoking at some point in life. It would be more interesting to combine these risk factors with genetic polymorphisms to build risk models for COPD.</p><h3>Part II: Which machine learning model predicts the test data best?</h3><p>We evaluate six prediction models: kNN, Linear Regression, Support Vector Machine, decision tree, XGBoost, and feed-forward neural network using area under the ROC curve (AU-ROC) as the performance metric. Based on the AUC score, the three highest performing models are kNN, Linear Regression, and XGBoost, although all six models show good performance on the test dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*a9KS0B8g6XPdRpF3v9LoHA.png" /><figcaption>The area under receiver operating characteritic is highest for XGBoost, but all models are significantly better than random chance (dashed line).</figcaption></figure><p>Furthermore, all models also show decent overall predictive power measured using various metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_A60WlWdR004peLQD0YN7A.png" /><figcaption>Comparison of the six machine learning models evaluated on the test set. KNN=k-nearest neighbour, LR= Linear Regression, SVM=support vector machine, DT=decision tree, MLP=multi-layer perceptron.</figcaption></figure><p>Because XGBoost is the best-performing model based on AUC, it is further used to analyse feature importance in the next part.</p><h3>Part III: Which are the most important features that play a major role in the predictive model?</h3><p>The XGboost model is used to analyze the importance of features, where the feature score rankings (i.e. F score) were measured by the <em>total_gain</em> metric in the <em>plot_importance</em> function from Python’s <em>xgboost</em> library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mv_LI30HOKVEqc7FFxmjtw.png" /><figcaption>The relative importance of clinical features (location, age, BMI, sex, smoking status) and DNA polymorphisms (rs***) in the xgboost model.</figcaption></figure><p>It should be noted here that the absolute values of the F score mean little to us. What matters here is the relative value of the F score of one feature w.r.t. the others.</p><p>With that being said, there are two major takeaways from this result:</p><ol><li>The five clinical features (location, age, BMI, sex, and smoking status) are generally more important than genetic polymorphisms</li><li>Location plays the most important role in predicting COPD, which is not surprising because the air quality in different Chinese cities can differ by quite a large margin.</li></ol><p>Interestingly, smoking is not as big a risk factor here according to the model, which is actually the classical culprit for COPD in developed countries. However, this is probably overshadowed by the high levels of ambient air pollution in some parts of China. It should be noted here that we can only make reports about association, and NOT causation, since we have no data from a randomized controlled trial (a.k.a. randomized experiment).</p><h4>Conclusion</h4><p>In this article, we looked at how data science can be used to recognize COPD based on clinical features and DNA data. There is no cure for COPD and it is progressive, so early detection is of paramount importance for any treatment to control its severity and reduce its impact on daily life.</p><p>The findings here are based on just one study with a rather limited dataset that specifically focus on the Chinese population, so further studies would be necessary to validate these findings. Therefore, the problem remains:</p><blockquote>We need more DATA and SCIENTISTS to help with early diagnosis for effective treatment of chronic diseases!</blockquote><p>The analysis code and more details can be found in the project <a href="https://github.com/Physicist91/copd-ml">Github repo</a>. The data and original study can be found in this <a href="https://translational-medicine.biomedcentral.com/articles/10.1186/s12967-020-02312-0">BMC Medicine journal</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d43ac55bea97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Interactive Visualization Tool Will Supercharge Your Data Narrative]]></title>
            <link>https://kevinsiswandi.medium.com/this-interactive-visualization-tool-will-supercharge-your-data-narrative-30a52569acae?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/30a52569acae</guid>
            <category><![CDATA[visualization-tool]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[wikidata]]></category>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Mon, 10 May 2021 21:59:18 GMT</pubDate>
            <atom:updated>2021-05-15T00:46:55.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EfaAx6GfRJkFQSaW" /><figcaption>Photo by <a href="https://unsplash.com/@madebyjens?utm_source=medium&amp;utm_medium=referral">Jens Lelie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>EntiTree is an effort that started in mid-2020 and is a merger of other <a href="https://www.wikidata.org/wiki/Wikidata:Tools/Visualize_data">wikidata visualisation tools</a> about trees, with some extra features that make it more usable and navigable.</p><p>The mission of EntiTree is to support the following people:</p><ul><li>researchers of any level that want to explore wikidata connections in a visual way 🧪</li><li>scientists that are keen to use an interactive taxonomy tree 🔬</li><li>historians investigating royal families 👑</li><li>students of any kind of discipline, that want to enrich they knowledge 🎓</li><li>curious random and non English-speaking people from around the globe, thanks to the multilingual feature 🌎🌍🌏</li><li>Wikidata editors and contributors, especially if they are interested in spotting missing or duplicate links 🤓</li></ul><h3>Example Usage</h3><p>With EntiTree, you can interactively visualize the family trees of <a href="https://medium.com/family-trees/tagged/silicon-valley">silicon valley’s magnates</a>, <a href="https://medium.com/family-trees/tagged/indonesia">Indonesian conglomerates</a>, <a href="https://medium.com/family-trees/tagged/us-politics">US Politicans</a>, and much more. Some examples can be found below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R9Rob7McDDJ8ckQg.png" /><figcaption>Harry Tanoesoedibjo’s Family Tree. Built with EntiTree: <a href="https://www.entitree.com/en/family_tree/Q102422470">https://www.entitree.com/en/family_tree/Q102422470</a></figcaption></figure><p>From the tree above, one gets a visual map of Harry Tanoesoedibjo’s family: The Indonesian billionaire, who is the founder of MNC Group, has four daughters and one son.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v7BweO5-AnTOjxgq.png" /><figcaption>Sudono Salim’s Family Tree. Built with EntiTree: <a href="https://www.entitree.com/en/family_tree/Sudono_Salim">https://www.entitree.com/en/family_tree/Sudono_Salim</a></figcaption></figure><p>While Harry Tanoesoedibjo is a second-generation Indonesian-born Chinese, Sudono Salim is a first-generation Chinese Indonesian who was born in the Fuzhou province in China in 1916 and migrated to Indonesia in 1936.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iNL6dbIENti1bjoP.png" /><figcaption>Mark Zuckerberg’s Family Tree. Built <a href="https://www.entitree.com/en/family_tree/Q20900225">with EntiTree: https://www.entitree.com/en/family_tree/Q20900225</a></figcaption></figure><p>Traveling across the ocean to the USA, EntiTree now shows you the beautiful family tree of the Facebook billionaire. Mark and Priscilla have two little kids: Maxima Chan Zuckerberg and August Chan Zuckerberg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xmGiX-lyx0VfrCMx.png" /><figcaption>Joe Biden’s Family Tree. Built with EntiTree: <a href="https://www.entitree.com/en/family_tree/Joe_Biden">https://www.entitree.com/en/family_tree/Joe_Biden</a></figcaption></figure><p>The US president Joe Biden, on the other hand, has a richer publicly available data of his family. You can further explore the tree interactively to dig into the current US president eventful family tree: <a href="https://medium.com/family-trees/joe-bidens-family-tree-8f135b63038d">https://medium.com/family-trees/joe-bidens-family-tree-8f135b63038d</a></p><p>Please feel free to get in touch with any member of the EntiTree team, for technical queries or help around the user interface <a href="https://github.com/ogroppo">Orlando</a> is the right guy, for anything related to (wiki)data <a href="https://medium.com/u/ebdd7d0df2e1">Martin</a> will be more than happy to help you. You can follow EntiTree on <a href="https://twitter.com/EntitreeApp">Twitter</a> too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30a52569acae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Family Tree of Indonesia’s Famous Individuals]]></title>
            <link>https://kevinsiswandi.medium.com/family-tree-of-indonesias-famous-individuals-e2c9ade360a3?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c9ade360a3</guid>
            <category><![CDATA[wikidata]]></category>
            <category><![CDATA[visualization-tool]]></category>
            <category><![CDATA[family-tree]]></category>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Mon, 10 May 2021 21:23:54 GMT</pubDate>
            <atom:updated>2021-05-10T21:23:54.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NUOXP7jLqUo0rOtd" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybishop?utm_source=medium&amp;utm_medium=referral">Jeremy Bishop</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>EntiTree is an interactive visualization tool that lets you explore the family tree of a subject from wikidata connections. Some examples from <a href="https://medium.com/u/ebdd7d0df2e1">Martin</a>:</p><ul><li><a href="https://medium.com/family-trees/tubagus-chasan-sochibs-family-tree-9c961b67ee8d">Tubagus Chasan Sochib (politician)</a></li><li><a href="https://medium.com/family-trees/susilo-bambang-yudhoyonos-family-tree-d2064fe97d0a">Susilo Bambang Yudhoyono (politician)</a></li><li><a href="https://medium.com/family-trees/hartono-brothers-family-tree-842ca8babdf1">Budi Hartono and Bambang Hartono (businessmen)</a></li><li><a href="https://wikidata.medium.com/family-tree-of-oei-tiong-ham-a5836eaa9366">Oei Tiong Ham (businessman)</a></li><li><a href="https://medium.com/family-trees/hamengkubuwono-family-tree-b223e0c6647e">Sultan Hamengkubuwono (royal family)</a></li><li><a href="https://wikidata.medium.com/family-tree-of-abdurrahman-wahid-e5d299f16b0">Abdurrahman Wahid (politician)</a></li><li><a href="https://medium.com/family-trees/jokowis-family-tree-keluarga-jokowi-1fd8bc055d32">Joko Widodo (polician)</a></li><li><a href="https://medium.com/family-trees/suhartos-family-tree-keluarga-suharto-88fac9c79cad">Suharto (politician)</a></li><li><a href="https://medium.com/family-trees/family-tree-of-megawati-sukarnoputri-ab4b18b86cd">Megawati Sukarnoputri (politician)</a></li><li><a href="https://medium.com/family-trees/prabowos-family-tree-ancestry-42a959380d56">Prabowo Subianto (politician)</a></li><li><a href="https://medium.com/family-trees/eka-tjipta-widjaja-family-tree-8c945224207d">Eka Tjipta Widjaja (businessman)</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aYuD-it9meg5wpME.png" /><figcaption>Family Tree of Ratu Atut. Built with EntiTree: <a href="https://www.entitree.com/en/family_tree/Q25469489">https://www.entitree.com/en/family_tree/Q25469489</a></figcaption></figure><p>You can do much more with EntiTree: you can “tree” the <a href="https://medium.com/family-trees/british-royal-family-eye-color-tree-122bf9207f3e">eye color of the British royal family</a>, the <a href="https://medium.com/family-trees/pan-pans-family-tree-a3acb03dae85">children of cute giant panda Pan Pan (or Tian Tian or Gu Gu)</a>, or perhaps <a href="https://medium.com/family-trees/paul-simons-family-tree-d305f8c99b52">your favourite singer</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c9ade360a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Is The Data Science Process All Data Scientists Use]]></title>
            <link>https://kevinsiswandi.medium.com/the-data-science-process-135c76c0926b?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/135c76c0926b</guid>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Fri, 07 May 2021 20:28:52 GMT</pubDate>
            <atom:updated>2021-05-11T13:54:01.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-bLvCD67wymn6p3L" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Nowadays, data science is not restricted only to the tech giants, but is already used by organizations across many industries, from FMCG to the financial services. Although the exact data science process varies depending on the specific use case, there is a common framework that is used to deliver data science solutions: the cross-industry standard for data mining (<a href="https://en.wikipedia.org/wiki/Cross-industry_standard_process_for_data_mining">CRISP-DM</a>). The CRISP-DM framework is widely regarded as the industry standard for developing predictive analytics solutions.</p><p>CRISP-DM consists of six major phases:</p><ol><li>Developing <strong>business understanding</strong></li><li>Gaining <strong>data understanding</strong></li><li>Conducting <strong>data preparation</strong></li><li>Doing <strong>predictive modeling</strong></li><li><strong>Evaluating</strong> the results against your business problem/question of interest</li><li><strong>Deploying</strong> your solution/changes</li></ol><p>First phase (<em>business understanding</em>): The first step in CRISP-DM involves understanding the problem that is valuable to the business and asking the right question. For example, a startup that is in a hypergrowth mode would be interested in new user acquisition; in this context, the data science question could be: what is the most effective way to get new customers? In healthcare, a pharmaceutical company would probably be interested in studying if a new drug can cure a certain disease; in this context the question could be: is the new treatment significantly better than a control treatment?</p><p>Second phase (<em>data understanding</em>): Businesses tend to collect as much data as they can, insofar as their resources allow. This often results in huge amount of data that needs to be processed and analyzed. In this case, an <a href="https://en.wikipedia.org/wiki/Exploratory_data_analysis">exploratory data analysis</a> would help with data understanding. However, if the data are not yet already available, one needs to plan for a data acquisition effort that is designed to gather a dataset that can be used for answering the relevant business questions.</p><p>Third phase (<em>data preparation</em>): Even assuming that the data are already gathered for you, the data preparation (a.k.a. data wrangling or munging) step is often still the most tedious part in the whole data science process. This involves lots of programming and scripting for data cleaning purposes, such as identifying and getting the right variables/columns, generating more plots and charts, handling missing values, etc. You may also need to join multiple data tables, such as matching columns with their schema/description.</p><p>Datasets often contain missing values, encoded in different formats (e.g. NA, blank, zeros, etc.). This is probably the most frequently encountered artifact when working with a dataset, and while there are no hard and fast rules, the following pointers should help:</p><ul><li>Missing values in the data should be handled differently depending on the business requirement.</li><li>Missing values should be handled before fitting a predictive model.</li><li>Three common ways to handle missing values are: removing them, imputing them, or working around them.</li><li>Removing data points with missing values would result in a biased predictive model in the next phase, so I would rather engineer some new features around these missing values when it makes sense to do so (e.g. count of missing values for every observation).</li><li>In some cases, it would be OK to remove the missing values: when the values are due to technical/measurement errors (&amp; imputation might potentially lead to misleading values) or when the missing values are simply not needed (&amp; they are only a small fraction of your data).</li></ul><p>Fourth phase (<em>predictive modeling</em>): Predictive models are often constructed by using one of the machine learning tools/libraries (e.g. scikit-learn in Python). In a <a href="https://en.wikipedia.org/wiki/Supervised_learning">supervised learning problem</a>, we are interested in predicting a specific response given some known factors. For example, a common problem in the recruitment industry is to predict a candidate’s expected salary given her background and qualifications — here the response is the desired salary.</p><p>The process of creating a predictive model from data is called model training or model fitting. The portion of your dataset that is used for model fitting is called the training data, and the other portion that is used for evaluating how well your model performs is called the test data.</p><p>Fifth phase (<em>evaluation</em>): If your problem performs well on the training data but poorly on the test data, it’s called overfitting. Overfitting is a situation in which the model doesn’t generalize well to new instances that it has never seen before. Ideally, you would like your model to perform well on both the training and test data.</p><p>Sixth phase (<em>deployment</em>): Once the predictive model is ready to be used, it can be deployed (a.k.a. productionalized). A very common deployment is having the model running in real-time (or at some fixed period) to automate certain tasks (e.g. recommending products to buy or tagging uploaded photos). Another deployment scenario that is often encountered in advanced analytics settings is to carve out actionable insights from your findings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=135c76c0926b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Slice of Social Psychology — Expectations Matter]]></title>
            <link>https://kevinsiswandi.medium.com/a-slice-of-social-psychology-expectations-matter-3b840fc8cf84?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b840fc8cf84</guid>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 11:41:32 GMT</pubDate>
            <atom:updated>2021-05-11T13:55:21.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Slice of Social Psychology — Expectations Matter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jd0gF0d7wzX8h66W" /><figcaption>Photo by <a href="https://unsplash.com/@artbyhybrid?utm_source=medium&amp;utm_medium=referral">Hybrid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a famous <a href="https://www.sciencedirect.com/science/article/pii/S006526010860146X">study</a>, it was shown that beliefs (i.e. expectations) can actually bring about the expected behaviour, creating a reality. A famous example: people who expect to die young may smoke and take drugs, ending up dying young in reality. This phenomenon also holds true in social interactions, in what psychologists call <a href="https://www.sciencedirect.com/science/article/abs/pii/0022103178900215">behavioural confirmation</a>.</p><p>Our perception of reality (social or otherwise) is influenced by what we happen to be paying attention to, our emotions, prejudices, and so on. According to social psychology, we only see what we are expecting and usually do not notice what we are not expecting. This subtle trait innate to human behaviour is the key to achieving success and getting ahead in life.</p><ul><li>When people see faces of children, they check if the faces are happy/sad</li><li>When we see a close-up face, we wonder what the person is thinking — is he dangerous/friendly/etc?</li></ul><p>The psychological power of expectations encompass things like:</p><ul><li><a href="https://www.sciencedirect.com/science/article/abs/pii/0030507375900021">Hinsight bias</a> (i-knew-it-all-along phenomenon)</li><li>Confirmation bias — when people meet in a group, they seek to find out evidence that confirms their expectations</li><li>Self-fulfilling prophecy — fake it till you make it</li><li>Context effects</li></ul><p>Social judgements usually take place very rapidly and we tend to lock into them once they are formed. Although this psychological behaviour seems on the surface to be a mental shortcut that is prone to biases, they are also quite powerful for predicting interpersonal consequences with good accuracy. The suprising accuracy of the <a href="https://en.wikipedia.org/wiki/Thin-slicing">thin-slice judgement</a> may be tied to the evolutionary value for rapidly identifying competent leaders, potential threats, or possible partners.</p><p>In fact, social judgement is formed so quickly and unconsciously that we have a saying for it: <em>First impression lasts:</em></p><ul><li><a href="https://onlinelibrary.wiley.com/doi/abs/10.1207/s15327663jcp1601_2">A successful sale decided in 30 seconds</a></li><li><a href="https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1545-5300.1999.00293.x">Divorce among newlyweds predicted in three minutes of discussion</a></li><li><a href="https://journals.sagepub.com/doi/10.1177/1948550610385473">Career success judged from college yearbook photos</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b840fc8cf84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agile Methods: Kanban vs Scrum]]></title>
            <link>https://kevinsiswandi.medium.com/agile-methods-kanban-vs-scrum-4d797ee1944?source=rss-40888f3ee19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d797ee1944</guid>
            <dc:creator><![CDATA[Kevin Siswandi]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 18:52:08 GMT</pubDate>
            <atom:updated>2021-05-11T13:58:05.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EPS4_tTrLw_vc-31" /><figcaption>Photo by <a href="https://unsplash.com/@lazizli?utm_source=medium&amp;utm_medium=referral">Lala Azizli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>On its own, agile is more of a mindset, and there are several established frameworks that one can adopt to achieve agility.</p><p>The two most popular methods to achieve agile principles are Kanban and Scrum. <a href="https://en.wikipedia.org/wiki/Kanban_(development)">Kanban (Japanese: 看板</a>) is used to to manage a continous queue of work items, which was originally developed by Taiichi Ohno at Toyota for lean manufacturing. Adopted from the Toyota production system, core ideas of the Kanban method include:</p><ol><li>Limit amount of work in progress so that there are only pending issues that the team can sustainably handle.</li><li>Identify and remove bottlenecks in your workflow via root cause analysis.</li><li>Pull work from queue on-demand, instead of blindly pushing work</li></ol><p>The main advantage of the Kanban method is it being lightweight: it’s easy to adopt/get started with Kanban without team restructuring. Taiichi Ohno said that the idea behind the <a href="https://en.wikipedia.org/wiki/Toyota_Production_System">Toyota Production System </a>was inspired from US retail supermarkets, where supply and demand are matched by ordering when the inventory is low (i.e. a pull system a.k.a. just-in-time). The kanban system implements this pull method and controls the flow of work. Examples of kanban systems include food ordering queue at a restaurant (food is only prepared upon receiving an order), ticketing system at a sporting arena (to control the flow of spectators), etc.</p><p><strong>Note</strong>: the Toyota production model is actually implementing the principles of <a href="https://en.wikipedia.org/wiki/Lean_manufacturing">lean manufacturing</a>, which is very similar to agile. The <a href="https://agilemanifesto.org/">agile manifesto</a> was first conceived in 2001 in the context of software development but share many commonalities with the lean principles.</p><p><a href="https://www.scrumguides.org/">Scrum</a> is a framework for developing and sustaining complex products in projects with some degree of uncertainty. The main idea behind scrum is to start with a vision and incrementally build features through several iterations. After each iteration, the features on their own should be usable and desirable (i.e. help to achieve the vision). Feedbacks upon every iteration are used to adapt the vision to market changes and improve existing feature/add new features at the next iteration. Through several iterations, the product with all its features should resemble the vision more closely.</p><p>In scrum’s speak, every iteration is called a <em>sprint</em>, and the product that results from a sprint is called an<em> increment</em>. A sprint is typically a period of two weeks to work on an increment, but should be adapted to the needs of the team (longer sprint length may be necessary when the increment is harder and shorter sprint length can allow for better adaptation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gbI5afRUhv6bHzm2" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The scrum framework defines three components/parts:</p><ol><li>Artifacts (e.g. backlogs, boards, reports, etc.)</li><li>Roles (e.g. product owner, scrum master, developers, stakeholders, etc.)</li><li>Events (e.g. sprint, daily standups, sprint meetings, spring reviews, etc.)</li></ol><p>Besides enabling collaboration, scrum artifacts also play a role in providing project transparency because anyone can evaluate the status of the project (as well as the history and future planning) by looking at the artifacts. These include the product backlogs (e.g. features, improvements, bug fixes, and so on), sprint backlogs (i.e. list of issues to be completed in the sprint as well as the sprint details), spring boards, and scrum reports, among others. Usually visual reports are also prodided (such as burndown chart, velocity chart, etc.)</p><p>There are three roles in a scrum team: product owner, scrum master, and the development team. The stakeholders are not part of the scrum team but still play a part in the success of the project. Internal stakeholders include people within the company such as managers, executive officers, or perhaps other scrum teams. External stakeholders are typically clients, partners, investors.</p><p>The <strong>product owner</strong> is accountable to the stakeholders and should therefore interact with them on a regular basis. As part of the scrum team, the product owner is responsible for</p><ul><li>communicating and spearheading the vision for the product</li><li>planning sprints such that each increment is maximized</li><li>handling the product backlog</li></ul><p>The scrum master promotes scrum, coaches the scrum team, and educates the stakeholders on scrum. In addition, the <strong>scrum master</strong> should be the primary point in the team to remove bottlenecks that distract the current work as well as facilitate scrum events. The scrum master is responsible for:</p><ul><li>championing and supporting scrum</li><li>making sure that the team is well-informed of why and how things are done the way they are</li><li>helping the team to stay focus on high value tasks</li><li>keeping the project transparent to the stakeholders</li></ul><p>That is, the job of the product owner is to maximize the product value, and the job of the scrum master is to optimize team effectiveness. On the other hand, the development team (at least 3 and not more than 9 members as per the Scrum Guide) is the one who does the real job: the team creates the increment at each sprit and collaborate as necessary to produce the sprint increments. In addition, only the dev team can estimate issues and decide how much work can be done in a sprint.</p><p>A sprint consists of (in chronological order) sprint planning, daily standups, sprint review, and sprint debrief. Any of these events are also called <em>meetings</em>. Scrum meetings have the following common traits:</p><ul><li>fixed maximum time limit (but no minimum time limit)</li><li>mainly for collaboration (instead of status update — the status should be visible already to everyone at any point!)</li></ul><p>The real work (i.e. actual development) occurs in between all these meetings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d797ee1944" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>