<?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 Chelsea on Medium]]></title>
        <description><![CDATA[Stories by Chelsea on Medium]]></description>
        <link>https://medium.com/@chelseaadhigiass?source=rss-6a7b9010fd0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JllON6nBflCgnaMIFvBY6Q.png</url>
            <title>Stories by Chelsea on Medium</title>
            <link>https://medium.com/@chelseaadhigiass?source=rss-6a7b9010fd0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:27:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chelseaadhigiass/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[Development of a Comprehensive Machine Learning Pipeline for Customer Churn Classification with…]]></title>
            <link>https://medium.com/@chelseaadhigiass/development-of-a-comprehensive-machine-learning-pipeline-for-customer-churn-classification-with-bf96b8b4f1ac?source=rss-6a7b9010fd0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf96b8b4f1ac</guid>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[grafana-prometheus]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Chelsea]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 14:06:39 GMT</pubDate>
            <atom:updated>2026-08-05T12:47:39.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Development of a Comprehensive Machine Learning Pipeline for Customer Churn Classification with Monitoring and Continuous Integration</h3><h3>Background</h3><p>The telecommunications industry is one of the most highly competitive business sectors, where every company is vying to retain its customers. One of the main challenges faced is the phenomenon of customer churn, a situation where customers stop using a service and switch to another provider. Continuous customer loss not only leads to a decline in revenue but also increases the cost of acquiring new customers, which is known to be far more expensive than retaining existing ones.</p><p>To address this issue, a machine learning-based approach can be used to predict customers at risk of churn early on, allowing companies to take more targeted preventive measures. However, building a predictive model alone is not enough; a comprehensive machine learning system is required, covering the entire model lifecycle from experimentation and training to deployment, monitoring, and workflow automation through Continuous Integration (CI).</p><h3>Preprocessing and EDA</h3><p>During the data preprocessing stage for the Telco Customer Churn dataset, I performed several steps to ensure the dataset was clean so it could proceed to the next stage of analysis. The first issue I encountered was a mismatch in the data types of a column. TotalCharges it should be a numeric data type, but in this dataset it is actually interpreted as an object. The second issue is the presence of redundant data. While the first and second data preprocessing steps relate to data quality, the third through fifth steps are designed to make it easier for the computer to learn from the data. These three processes are encoding categorical features, standardizing numeric data, and splitting the data into training and test sets.</p><p>In addition to cleaning and preparing the data for the subsequent modeling process, I also performed EDA to understand the content and proportions of the data I used. In this EDA, I visualized the proportions of churn and non-churn, the correlations among numerical features, and the relationship between categorical features and churn. Below are the results of the EDA I performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*7jR6Rx0w6DBv6ijbEs9nBA.png" /><figcaption>Figure 1 Customer Churn Distribution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*XoOuR2COgSV02_DVK5oGWw.png" /><figcaption>Figure 2 Numeric Feature Correlation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fM-kVPIgPiFR2jhxmxqVNg.png" /><figcaption>Figure 3 Correlation Between Categorical Feature for Churn</figcaption></figure><h3>Modeling</h3><p>For this customer churn data modeling, I used both a standard Random Forest Classifier and a Random Forest Classifier that I tuned. The hyperparameter grid I used is as follows</p><pre>param_grid = {<br>        &quot;n_estimators&quot;: [100, 200],<br>        &quot;max_depth&quot;: [None, 10, 20],<br>        &quot;min_samples_split&quot;: [2, 5],<br>}</pre><p>The evaluation metrics I used to measure the model’s performance were accuracy, precision, recall, F1 score, and ROC-AUC.</p><h3>Monitoring and Logging</h3><p>After the Random Forest model for customer churn prediction was successfully trained and tuned using the Telco Customer Churn dataset, the next important step was to deploy the model so it could be used to predict customers who are likely to churn in real situations. However, the process does not end after deployment. The deployed model must be monitored continuously to make sure the prediction service works properly and remains reliable.</p><p>This is where monitoring and logging become very important. Prometheus is used to collect real-time operational metrics, while Grafana is used to display these metrics in an easy-to-read dashboard and provide alerts when unusual conditions occur. The monitored metrics include model service availability (uptime), response latency for each prediction request, the number of inference requests, the distribution of prediction results by class (churn or non-churn), and system resource usage such as CPU and memory.</p><p>This process is directly related to the model that was trained earlier. Even though the model has gone through hyperparameter tuning and achieved good evaluation results on the test dataset, it may not perform the same way in a serving environment. Monitoring helps detect potential problems, such as an unresponsive model endpoint, increased response latency caused by heavy traffic, or an unbalanced prediction distribution that may indicate data drift. Therefore, monitoring and logging help ensure that the churn prediction model is not only accurate during the experiment stage but also reliable, stable, and trustworthy when running continuously in a production-like environment.</p><h3>Continuous Integration</h3><p>In machine learning system development, the model training process often needs to be repeated. This can happen because of changes in the preprocessing code, hyperparameter adjustments, or dataset updates. If this process is done manually every time there is a change, the risk of inconsistency and human error becomes much higher. Therefore, an automated process is needed to retrain the model consistently without manual work. This process is called a Continuous Integration (CI) workflow.</p><p>In this project, the CI workflow is implemented using GitHub Actions. It is configured to run automatically whenever there is a push or pull request to the main branch of the GitHub repository. When the CI pipeline is triggered, it automatically sets up the Python environment, installs all required dependencies, and runs the Random Forest model training on the Telco Customer Churn dataset using an MLflow Project (mlflow run). All evaluation metrics, including accuracy, precision, recall, F1-score, and ROC-AUC, are recorded automatically. The trained model artifacts are also uploaded to GitHub as proof that the pipeline has completed successfully.</p><p>This CI workflow is closely connected to the model training process completed earlier. During the experiment stage, the model was trained and tuned locally. Now, it is packaged as a standardized MLflow Project, allowing it to run in any environment in a reproducible way. With CI, every code change pushed to the repository is automatically validated through the retraining process. This helps ensure that new changes do not break the existing pipeline. The main benefit of this approach is a workflow that is automated, consistent, and well documented. These three aspects are essential for moving from local experiments to a machine learning system that is ready for a production environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf96b8b4f1ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StudioAI: Image Generation with Stable Diffusion]]></title>
            <link>https://medium.com/@chelseaadhigiass/studioai-image-generation-with-stable-diffusion-be981dcc0e00?source=rss-6a7b9010fd0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/be981dcc0e00</guid>
            <category><![CDATA[prompting-technique]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Chelsea]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 16:15:48 GMT</pubDate>
            <atom:updated>2026-07-16T16:15:48.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Imagine being able to type a single sentence for example, “an astronaut floating in space against a backdrop of a colorful galaxy” and then, in a matter of seconds, have AI turn that sentence into a complete image. That’s what generative AI technologies like Stable Diffusion can do, and through this project, I’m trying to understand and put into practice how it works from scratch.</p><p>The goal, simply put, is to get a closer look at how AI “draws” from text, and then to see to what extent it can be guided and relied upon as a genuine creative tool not just a one-time gimmick. To that end, I’m trying out a few things step by step. First, I tried to understand how the words in the prompt are translated into images, including how to control how “obedient” the AI is to our instructions through parameters like the guidance scale, and how detailed the results are based on the number of processing steps (inference steps). From this, I discovered a sort of balance: if it’s too free, the image doesn’t quite match the description; if it’s too constrained, the image ends up looking exaggerated and unnatural.</p><h3>Stage 1: Load Base Pipeline Model</h3><p>For the base model, I used one that was available on Hugging Face from Runway, but that model has since been taken down; you can look for models from other creators. Here’s how to load data from Hugging Face:</p><pre>MODEL_ID = &quot;runwayml/stable-diffusion-v1-5&quot;<br><br>pipe = StableDiffusionPipeline.from_pretrained(<br>    MODEL_ID,<br>    torch_dtype=dtype,<br>    safety_checker=None,         <br>).to(device)<br><br>pipe.enable_attention_slicing()   <br>print(&quot;Base pipeline is ready.&quot;)</pre><h3>Stage 2: Generate Image</h3><p>After loading the model, I started crafting a prompt to generate the image I wanted. Here’s a tip: provide as much detail as possible specify whether you want a realistic style or something else. To generate an image that better matches your expectations, use a negative prompt. Unlike a typical prompt, a negative prompt lists the elements you don’t want to appear in your final image. By combining both, your final image will better align with your expectations.</p><h3><strong>Stage 3: Generate Image with Hyperparameter Configuration</strong></h3><p>To generate better images, you can also add Hyperparameter Configuration. The hyperparameters you can apply include num_inference_steps, guidance_scale, height, width, strenght, generator, andscheduler. Keep in mind that not everything that’s big is necessarily good. Since these are just settings, you’ll need to experiment first to determine which ones work best for you. These are the hyperparameter settings I use.</p><pre>def generate_advanced_image(prompt, negative_prompt, seed,<br>                            guidance_scale=7.5, num_inference_steps=30):<br>    generator = torch.Generator(device=device).manual_seed(seed)<br>    image = pipe(<br>        prompt=prompt,<br>        negative_prompt=negative_prompt,<br>        generator=generator,<br>        guidance_scale=guidance_scale,<br>        num_inference_steps=num_inference_steps,<br>    ).images[0]<br>    return image<br><br><br>advanced_img = generate_advanced_image(<br>    PROMPT, NEGATIVE_PROMPT, SEED,<br>    guidance_scale=9.0, num_inference_steps=40,<br>)<br>show_images(<br>    [simple_img, advanced_img],<br>    [&quot;simple (default)&quot;, &quot;advanced (cfg=9.0, steps=40)&quot;],<br>    cols=2, figsize=(11, 6),<br>)</pre><p>Here is an example generated using the syntax settings above. You can try it yourself, too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3JOHg43aSJ98eKHJd5qQw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be981dcc0e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis of Google Play Store App Reviews with Deep Learning]]></title>
            <link>https://medium.com/@chelseaadhigiass/sentiment-analysis-of-google-play-store-app-reviews-with-deep-learning-b3f071660023?source=rss-6a7b9010fd0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3f071660023</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Chelsea]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 13:03:00 GMT</pubDate>
            <atom:updated>2026-07-08T13:03:00.689Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Every day, popular apps like Gojek, Grab, Shopee, and mobile banking services receive thousands of reviews on the Google Play Store. Buried inside that pile of text is a goldmine of feedback: what users love, what frustrates them, and which features quietly drive them away. Reading all of it manually is impossible, which is exactly where Natural Language Processing (NLP) earns its keep.</p><p>For this final project, I built an end-to-end <strong>sentiment analysis</strong> pipeline that classifies Indonesian app reviews into three classes: <strong>negative</strong>, <strong>neutral</strong>, and <strong>positive</strong>. I scraped the data myself, labeled it, and trained three different deep learning models to compare which architecture handles short, messy, real-world text the best.</p><p>The whole thing was split into a few clear stages:</p><ul><li><strong>Data scraping: </strong>collecting more than 10,000 reviews from 6 popular Indonesian apps.</li><li><strong>Lexicon-based labeling:</strong> turning raw text into 3 sentiment classes without relying on star ratings.</li><li><strong>Text preprocessing:</strong> cleaning and normalizing noisy Indonesian text.</li><li><strong>Feature extraction:</strong> Word2Vec embeddings trained on the review corpus.</li><li><strong>Modeling:</strong> three schemes, LSTM, Bidirectional LSTM, and CNN.</li><li><strong>Evaluation and inference:</strong> comparing results and predicting sentiment on brand-new text.</li></ul><h3>Stage 1: Scraping the Data</h3><p>Instead of downloading a ready-made dataset, I collected the reviews myself using the `google-play-scraper` library. I targeted 6 apps that most Indonesians use daily: Gojek, Grab, Shopee, Tokopedia, Dana, and BRImo, aiming for around 1,800 reviews each so the total would comfortably pass 10,000.</p><pre>from google_play_scraper import Sort, reviews<br><br>result, continuation_token = reviews(<br>    app_id,<br>    lang=&#39;id&#39;,<br>    country=&#39;id&#39;,<br>    sort=Sort.NEWEST,<br>    count=batch_size,<br>    continuation_token=continuation_token,<br>)</pre><p>Reviews were pulled in batches with a small random delay between requests to avoid rate limiting, then saved to `dataset_reviews.csv` with columns like `content`, `score`, `thumbsUpCount`, and `app_name`.</p><h3>Stage 2: Exploring the Data (EDA)</h3><p>Before any modeling, I looked at how the data was distributed, both across rating scores and across apps.</p><pre>fig, axes = plt.subplots(1, 2, figsize=(14, 5))<br>sns.countplot(data=df, x=&#39;score&#39;, ax=axes[0], palette=&#39;viridis&#39;)<br>axes[0].set_title(&#39;Rating Distribution&#39;)<br><br>sns.countplot(data=df, x=&#39;app_name&#39;, ax=axes[1], palette=&#39;Set2&#39;)<br>axes[1].set_title(&#39;Distribution per App&#39;)<br>axes[1].tick_params(axis=&#39;x&#39;, rotation=45)<br>plt.tight_layout(); plt.show()</pre><p>The rating distribution revealed a classic problem: reviews are heavily polarized toward 1 star and 5 stars, while 3-star reviews (the “neutral” ones) are extremely rare. This single chart is what convinced me not to use star ratings as labels.</p><h3>Stage 3: Labeling with the InSet Lexicon</h3><p>Here is the most important design decision of the project. Star ratings are tempting to use as labels, but they are unreliable: a user might type a glowing review and still tap 1 star out of habit or frustration with an unrelated issue. On top of that, the neutral class barely exists if you go by ratings alone.</p><p>So instead, I used lexicon-based labeling with the InSet (Indonesia Sentiment Lexicon) dictionary. Each word in a review carries a sentiment weight, and the overall sentiment score is the sum of positive weights minus the absolute value of negative weights.</p><pre>lex_pos = pd.read_csv(&#39;positive.tsv&#39;, sep=&#39;\t&#39;)<br>lex_neg = pd.read_csv(&#39;negative.tsv&#39;, sep=&#39;\t&#39;)<br><br>positive_lexicon = {row[&#39;word&#39;]: row[&#39;weight&#39;] for _, row in lex_pos.iterrows()}<br>negative_lexicon = {row[&#39;word&#39;]: row[&#39;weight&#39;] for _, row in lex_neg.iterrows()}<br><br>def pos_score(text):<br>    return sum(positive_lexicon.get(w, 0) for w in text.split())<br><br>def neg_score(text):<br>    return sum(abs(negative_lexicon.get(w, 0)) for w in text.split())<br><br>df[&#39;sentiment_score&#39;] = df[&#39;pos_score&#39;] - df[&#39;neg_score&#39;]</pre><p>Then I applied threshold rules to convert those scores into clean labels. Reviews that landed in an ambiguous middle zone were dropped entirely, because a noisy label is worse than no label.</p><pre>POS_THRESHOLD = 10<br>NEG_THRESHOLD = -12<br><br>def lexicon_label(row):<br>    s = row[&#39;sentiment_score&#39;]<br>    if s &gt;= POS_THRESHOLD:<br>        return &#39;positif&#39;<br>    if s &lt;= NEG_THRESHOLD:<br>        return &#39;negatif&#39;<br>    if -1 &lt;= s &lt;= 1 and (row[&#39;pos_score&#39;] + row[&#39;neg_score&#39;]) &lt;= 1:<br>        return &#39;netral&#39;<br>    return &#39;ambigu&#39;   # dropped<br><br>df[&#39;sentiment&#39;] = df.apply(lexicon_label, axis=1)<br>df = df[df[&#39;sentiment&#39;] != &#39;ambigu&#39;].reset_index(drop=True)</pre><p>A quick count plot confirmed I ended up with three usable classes whose labels actually match the review text.</p><pre>order = [&#39;negatif&#39;, &#39;netral&#39;, &#39;positif&#39;]<br>sns.countplot(data=df, x=&#39;sentiment&#39;, order=order,<br>              palette=[&#39;#ff6b6b&#39;, &#39;#feca57&#39;, &#39;#48dbfb&#39;])<br>plt.title(&#39;Sentiment Class Distribution (Lexicon-Based)&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*DN896_WY5B6EAD9mloWJ6g.png" /><figcaption><strong>Figure 1.</strong> Sentiment Class Distribution</figcaption></figure><h3>Stage 4: Text Preprocessing</h3><p>Real-world reviews are messy: emojis, slang, typos, URLs, and inconsistent spacing. Cleaning happens in two steps. A basic clean lowercases the text and strips URLs, non-ASCII characters, numbers, and punctuation:</p><pre>def basic_clean(text):<br>    text = str(text).lower()<br>    text = re.sub(r&#39;http\S+|www\S+|https\S+&#39;, &#39;&#39;, text)<br>    text = re.sub(r&#39;[^\x00-\x7F]+&#39;, &#39; &#39;, text)   # remove emoji/non-ASCII<br>    text = re.sub(r&#39;\d+&#39;, &#39;&#39;, text)<br>    text = text.translate(str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation))<br>    return re.sub(r&#39;\s+&#39;, &#39; &#39;, text).strip()</pre><p>Then I removed Indonesian stopwords, plus a custom list of common chat abbreviations (yg, gak, udah, aja, and friends) that carry no sentiment, and dropped very short tokens:</p><pre>stop_words_id = set(stopwords.words(&#39;indonesian&#39;))<br>custom_stopwords = {&#39;yg&#39;, &#39;nya&#39;, &#39;ga&#39;, &#39;gak&#39;, &#39;udah&#39;, &#39;tp&#39;, &#39;aja&#39;, &#39;lg&#39;,<br>                    &#39;nih&#39;, &#39;sih&#39;, &#39;dong&#39;, &#39;deh&#39;, &#39;kok&#39;, &#39;kan&#39;, &#39;tuh&#39;}<br>stop_words_id.update(custom_stopwords)<br><br>def preprocess_text(text):<br>    text = basic_clean(text)<br>    tokens = [t for t in text.split() if t not in stop_words_id and len(t) &gt; 2]<br>    return &#39; &#39;.join(tokens)</pre><h3>Stage 5: Splitting and Balancing (No Leakage)</h3><p>This is another spot where it is easy to accidentally cheat. If you oversample the minority classes before splitting, duplicated rows can leak into the test set and inflate your accuracy. So the order matters: split first, then oversample the training set only.</p><pre>def balance_train(X_tr, y_tr, seed=RANDOM_STATE):<br>    &quot;&quot;&quot;Oversample the TRAINING set only (prevents leakage).&quot;&quot;&quot;<br>    tr = pd.DataFrame({&#39;text&#39;: X_tr, &#39;label&#39;: y_tr})<br>    target = tr[&#39;label&#39;].value_counts().max()<br>    parts = []<br>    for c in tr[&#39;label&#39;].unique():<br>        sub = tr[tr[&#39;label&#39;] == c]<br>        parts.append(resample(sub, replace=len(sub) &lt; target,<br>                              n_samples=target, random_state=seed))<br>    bal = pd.concat(parts).sample(frac=1, random_state=seed).reset_index(drop=True)<br>    return bal[&#39;text&#39;].values, bal[&#39;label&#39;].values<br><br># Two split scenarios: 80/20 and 70/30<br>X_tr80, X_te80, y_tr80, y_te80 = train_test_split(<br>    X_all, y_all, test_size=0.2, random_state=42, stratify=y_all)<br>X_tr80_bal, y_tr80_bal = balance_train(X_tr80, y_tr80)</pre><p>I prepared two split scenarios, 80/20 and 70/30, so I could test different train/test ratios across the models.</p><h3>Stage 6: Feature Extraction with Word2Vec</h3><p>Deep learning models cannot read raw words, so text needs to become numbers. I used a Keras Tokenizer to turn words into integer sequences, then trained a Word2Vec model on the training corpus to learn dense 128-dimensional word vectors. Crucially, both the tokenizer and Word2Vec were fit on training text only.</p><pre>tokenizer = Tokenizer(num_words=20000, oov_token=&#39;&lt;OOV&gt;&#39;)<br>tokenizer.fit_on_texts(fit_corpus)<br><br>w2v_model = Word2Vec(sentences=tokenized_corpus, vector_size=128,<br>                     window=5, min_count=2, workers=4, epochs=20, sg=1)</pre><p>Those learned vectors were then packed into an embedding matrix that seeds the neural network’s embedding layer. Words missing from Word2Vec get a Glorot-uniform random init instead of a row of zeros:</p><pre>embedding_matrix = np.zeros((vocab_size, EMBEDDING_DIM))<br>for word, idx in tokenizer.word_index.items():<br>    if idx &lt; vocab_size and word in w2v_model.wv:<br>        embedding_matrix[idx] = w2v_model.wv[word]</pre><h3>Stage 7: Building the Models</h3><p>I trained three schemes with intentionally different architectures and data splits.</p><p><strong>Scheme 1 — LSTM (80/20)</strong>. A stacked LSTM that reads the sequence left to right, wrapped in dropout, L2 regularization, and batch normalization to fight overfitting.</p><pre>model_1 = Sequential([<br>    Embedding(vocab_size, EMBEDDING_DIM, weights=[embedding_matrix],<br>              input_length=MAX_SEQUENCE_LENGTH, trainable=True),<br>    SpatialDropout1D(0.3),<br>    LSTM(64, return_sequences=True, dropout=0.3),<br>    LSTM(32, dropout=0.3),<br>    Dense(32, activation=&#39;relu&#39;, kernel_regularizer=l2(1e-4)),<br>    BatchNormalization(),<br>    Dropout(0.5),<br>    Dense(num_classes, activation=&#39;softmax&#39;)<br>])</pre><p><strong>Scheme 2 — Bidirectional LSTM (80/20)</strong>. Same idea, but it reads the sequence in both directions so it captures context from the left and right of every word.</p><pre>model_2 = Sequential([<br>    Embedding(vocab_size, EMBEDDING_DIM, weights=[embedding_matrix],<br>              input_length=MAX_SEQUENCE_LENGTH, trainable=True),<br>    SpatialDropout1D(0.3),<br>    Bidirectional(LSTM(64, return_sequences=True, dropout=0.3)),<br>    Bidirectional(LSTM(32, dropout=0.3)),<br>    Dense(64, activation=&#39;relu&#39;, kernel_regularizer=l2(1e-4)),<br>    BatchNormalization(),<br>    Dropout(0.5),<br>    Dense(num_classes, activation=&#39;softmax&#39;)<br>])</pre><p><strong>Scheme 3 — CNN / Conv1D (70/30)</strong>. A completely different approach that slides convolutional filters over the text to detect local phrase patterns (n-grams), which is often surprisingly strong on short text.</p><pre>model_3 = Sequential([<br>    Embedding(vocab_size, EMBEDDING_DIM, weights=[embedding_matrix],<br>              input_length=MAX_SEQUENCE_LENGTH, trainable=True),<br>    SpatialDropout1D(0.3),<br>    Conv1D(128, 5, activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=l2(1e-4)),<br>    BatchNormalization(),<br>    Conv1D(64, 3, activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=l2(1e-4)),<br>    BatchNormalization(),<br>    GlobalMaxPooling1D(),<br>    Dense(64, activation=&#39;relu&#39;, kernel_regularizer=l2(1e-4)),<br>    Dropout(0.5),<br>    Dense(num_classes, activation=&#39;softmax&#39;)<br>])</pre><p>Every model used early stopping and learning-rate reduction on plateau, so training stops the moment validation accuracy stops improving.</p><pre>callbacks = [<br>    EarlyStopping(monitor=&#39;val_accuracy&#39;, patience=6,<br>                  restore_best_weights=True, mode=&#39;max&#39;),<br>    ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.5, patience=3, min_lr=1e-6),<br>]</pre><p>For each model I plotted training vs validation curves to watch for overfitting, and a confusion matrix to see where predictions actually went wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*KJeBVwrQbMg4xq0FhidDBQ.png" /><figcaption><strong>Figure 2.</strong> Confusion Matrix from CNN + Word2Vec</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbUBOQ7VE_yf0xBaFk-6zQ.png" /><figcaption><strong>Figure 3. </strong>Training and Validation Curves from CNN + Word2Vec</figcaption></figure><h3>Evaluation Result</h3><p>After training all three, I lined them up side by side with a grouped bar chart of train vs test accuracy.</p><pre>Scheme 1 (LSTM + Word2Vec + 80/20)  : Train Acc 33.33%  | Test Acc 45.57%<br>Scheme 2 (BiLSTM + Word2Vec + 80/20): Train Acc 99.25%  | Test Acc 94.17%<br>Scheme 3 (CNN + Word2Vec + 70/30)   : Train Acc 100.00% | Test Acc 94.67%</pre><p>The results tell a clear story. The plain LSTM struggled badly, getting stuck around chance level, likely failing to converge on this short, noisy text within the training budget. The Bidirectional LSTM and CNN, on the other hand, both crossed 94% test accuracy. The CNN came out on top at 94.67%, which fits the intuition that convolutional filters are great at catching sentiment-bearing phrases in short reviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*O3u60RP3r2UxzWShgyF6rQ.png" /><figcaption><strong>Figure 4. </strong>Accuracy Comparison</figcaption></figure><h3>Inference on New Text</h3><p>The real payoff is applying the best model to text it has never seen. The inference function cleans the input, tokenizes and pads it, and returns a categorical label with a confidence score.</p><pre>def predict_sentiment(text, model=best_model):<br> cleaned = preprocess_text(text)<br> padded = to_padded([cleaned])<br> prob = model.predict(padded, verbose=0)[0]<br> idx = int(np.argmax(prob))<br> return label_encoder.inverse_transform([idx])[0], float(prob[idx]), prob<br><br>predict_sentiment(&#39;Mantap aplikasinya, cepat dan mudah digunakan&#39;)<br># -&gt; (&#39;positif&#39;, 0.98, …)</pre><p>Testing it on a handful of hand-written reviews (praise, complaints, and lukewarm “it’s okay” comments) it correctly separated enthusiastic reviews from angry ones and flagged the genuinely middle-of-the-road ones as neutral.</p><p>Finally, the best model and its artifacts were saved for reuse:</p><pre>best_model.save(‘model_sentiment_best.h5’)<br>with open(‘tokenizer.pkl’, ‘wb’) as f:<br> pickle.dump(tokenizer, f)<br>with open(‘label_encoder.pkl’, ‘wb’) as f:<br> pickle.dump(label_encoder, f)</pre><h3>Conclusion</h3><p>Through this project I practiced a complete NLP workflow end to end:</p><ul><li>Independent data collection — scraping 10,000+ real reviews rather than using a canned dataset.</li><li>Thoughtful labeling — choosing a lexicon-based approach over biased star ratings, and being disciplined enough to throw away ambiguous samples.</li><li>Leakage-aware preparation — splitting before oversampling, and fitting the tokenizer and Word2Vec on training data only.</li><li>Model comparison — benchmarking LSTM, BiLSTM, and CNN, with the CNN winning at 94.67% test accuracy.</li></ul><p>One honest caveat worth repeating: because the labels come from a lexicon, the model is partly learning to reproduce that lexicon’s logic. In a production setting I would validate it against human-annotated reviews to be sure it generalizes to how people actually feel, not just which words they use.</p><p>The combination of scraping, lexicon labeling, and deep learning here mirrors how sentiment analysis is used in the real world, from product feedback dashboards to brand monitoring, making this a solid stepping stone toward more advanced NLP work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3f071660023" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering and Classifying Customer Transaction Behavior with Machine Learning]]></title>
            <link>https://medium.com/@chelseaadhigiass/clustering-and-classifying-customer-transaction-behavior-with-machine-learning-562d36829685?source=rss-6a7b9010fd0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/562d36829685</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Chelsea]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 13:06:31 GMT</pubDate>
            <atom:updated>2026-07-01T13:09:02.810Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Every day, banks and financial institutions process thousands, even millions, of transactions. Behind those numbers lie hidden behavioral patterns that can be extremely valuable. From understanding customer segments and designing better-targeted products, to detecting transactions that might be anomalous or suspicious.</p><p>For this final project, I worked with a financial transaction dataset containing <strong>2,512 samples</strong> with various attributes such as transaction amount, transaction type, location, channel (ATM, Online, Branch), customer age and occupation, transaction duration, and number of login attempts. The project was split into two stages:</p><ul><li><strong>Clustering (unsupervised learning)</strong> — grouping customers based on similarities in their transaction patterns without using any labels.</li><li><strong>Classification (supervised learning)</strong> — using the resulting clusters as target labels to train a model that can automatically predict a customer’s group for new data.</li></ul><p>This workflow mirrors a common real-world scenario: when data has no labels, clustering is used to “create” initial labels, which are then used as the foundation for building a predictive model that is faster and reusable.</p><h4>Stage 1: Understanding and Cleaning the Data</h4><p>Before jumping into modeling, the first mandatory step is exploration and data cleaning (Exploratory Data Analysis and Data Preprocessing). Some early findings:</p><ul><li>The dataset had <strong>missing values</strong> in nearly every column, as well as <strong>21 duplicate rows</strong>.</li><li>Columns such as TransactionID, AccountID, DeviceID, IP Address, MerchantID, and date columns (TransactionDate, PreviousTransactionDate) were irrelevant for clustering since they are unique/identifier fields, so they were dropped.</li><li>Categorical features such as TransactionType, Location, Channel, and CustomerOccupation were converted into numbers using <strong>Label Encoding</strong> so they could be processed by machine learning algorithms.</li><li>For additional analysis (skilled and advanced level criteria), I created visualizations including a <strong>correlation heatmap</strong>, <strong>distribution histograms</strong>, and <strong>boxplots/violin plots</strong> of transaction amount by customer occupation, and added <strong>outlier handling</strong> using the IQR (Interquartile Range) method before scaling the data with <strong>StandardScaler</strong>.</li></ul><p>After the cleaning process, the clean dataset ready for clustering consisted of 1,945 rows.</p><h4>Stage 2: Building the Clustering Model</h4><p>To determine the optimal number of clusters, I used the <strong>Elbow Method</strong> with the silhouette score metric via KElbowVisualizer. Based on the resulting visualization, <strong>2 clusters</strong> were selected as the best number of groups.</p><p>The algorithm used was <strong>K-Means Clustering</strong>, one of the most popular clustering algorithms due to its simplicity and efficiency. It works by partitioning data into a number of clusters based on the distance of each data point to the nearest cluster centroid.</p><pre>model = KMeans() <br>visualizer = KElbowVisualizer(model, k=(2,10), metric=’silhouette’, timings=False) <br>visualizer.fit(df)</pre><p>Model evaluation using the <strong>silhouette score returned a value of 0.57</strong>, indicating a reasonably good cluster structure — data points within a cluster are relatively close together, while the clusters themselves are fairly well separated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*FhVgwuKntpncEGCqcRQH1Q.png" /></figure><p>To visualize the clustering results, which originally exist in a high-dimensional space, I used <strong>Principal Component Analysis (PCA)</strong> to reduce the data to its two main dimensions, allowing the cluster distribution to be plotted as a 2D scatter plot complete with centroid markers.</p><h3>Cluster Interpretation</h3><p>After transforming the data back to its original scale (inverse transform), the two clusters can be interpreted as follows:</p><ul><li><strong>Cluster 0 — “Stable, Well-Established Customers”</strong>: average age of around 45 years old, dominated by the <em>Doctor</em> occupation, with a higher average account balance (±5,142) and relatively longer transaction durations. This group tends to transact more cautiously and frequently uses the <em>Branch</em> channel.</li><li><strong>Cluster 1 — “Young, Active Customers”</strong>: dominated by the <em>Student</em> occupation with a younger age group, slightly higher average transaction amounts but lower average account balances, and shorter transaction durations , indicating faster, more active transactions.</li></ul><p>Interpretations like these matter because they turn statistical numbers into actionable business insight. For example, offering low-risk investment products to Cluster 0, and more flexible or digital-first products to Cluster 1.</p><p>The clustering results were then saved as a new column called <strong>Target</strong>, and the complete dataset (both the scaled version and the inverse-transformed version) was exported to CSV files for use in the next stage.</p><h4>Stage 3: Building the Classification Model</h4><p>Once the Target label was available from the clustering results, the next step was to build a supervised learning model capable of predicting a customer&#39;s group based on the available features.</p><p>The workflow was as follows:</p><p><strong>One-Hot Encoding</strong> was applied to the categorical features, since the dataset used was the inverse-transformed version (categories in their original text form).</p><p><strong>Data Splitting</strong>: the dataset was split into training and testing sets with an 80:20 ratio using train_test_split, with the stratify parameter to keep class proportions balanced between the training and testing sets. Out of 1,945 total records, this resulted in 1,556 training samples and 389 testing samples.</p><pre>X = df_encoded.drop(&#39;Target&#39;, axis=1)<br>y = df_encoded[&#39;Target&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size = 0.2,<br>    random_state = 42,<br>    stratify = y<br>)<br><br>print(&quot;Jumlah data total: &quot;,len(X))<br>print(&quot;Jumlah data latih: &quot;,len(X_train))<br>print(&quot;Jumlah data test: &quot;,len(X_test))</pre><p><strong>Baseline model — Decision Tree Classifier</strong>: chosen as the baseline for its interpretability and fast training time.</p><p><strong>Comparison model — Random Forest Classifier</strong>: an ensemble algorithm typically more resistant to overfitting than a single decision tree.</p><p><strong>Hyperparameter Tuning</strong> was performed on the Random Forest model using GridSearchCV, searching over combinations of n_estimators (50, 100, 200), max_depth (None, 5, 10, 20), and min_samples_split (2, 5, 10), evaluated with 5-fold cross-validation.</p><pre>params = {&#39;n_estimators&#39;: [50, 100, 200],<br>          &#39;max_depth&#39;: [None, 5, 10, 20],<br>          &#39;min_samples_split&#39;: [2, 5, 10],}<br><br>new_model_tuned = GridSearchCV(<br>    estimator = RandomForestClassifier(random_state=42),<br>    param_grid = params,<br>    cv = 5,<br>    scoring = &#39;accuracy&#39;<br>)<br><br>new_model_tuned.fit(X_train, y_train)</pre><h3>Evaluation Results</h3><p>All three models, Decision Tree, Random Forest, and the tuned Random Forest achieved very high performance on the test set, with <strong>accuracy, precision, recall, and F1-score all reaching 1.00 (100%)</strong>.</p><p>This near-perfect performance makes sense, since the Target label was derived directly from K-Means clustering on the same features used for classification, meaning the boundaries between classes were very clear and easy for the model to learn. This is also an important reminder: when labels come from a clustering process applied to identical features, such high accuracy reflects pipeline consistency more than the complexity of a real-world problem. In a production setting, a model like this would ideally be re-evaluated on new data that was never part of the original clustering process.</p><h3>Conclusion</h3><p>Through this project, I practiced an end-to-end machine learning workflow commonly found in industry:</p><ul><li><strong>Careful data preprocessing</strong> (handling missing values, duplicates, encoding, scaling, and outliers) as the foundation for a good model.</li><li><strong>Unsupervised learning (K-Means)</strong> to uncover hidden structure in unlabeled data, supported by <strong>PCA</strong> for visualization and evaluated using the <strong>silhouette score</strong>.</li><li><strong>Supervised learning (Decision Tree and Random Forest)</strong> to build a predictive model from the clustering results, complete with <strong>hyperparameter tuning</strong> to optimize performance.</li></ul><p>This combination of clustering and classification is widely applied in the real world. For example, in customer segmentation, recommendation systems, and anomaly/fraud detection in the banking industry making this project a relevant exercise before tackling more complex machine learning problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=562d36829685" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>