<?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 John Rowen Miano on Medium]]></title>
        <description><![CDATA[Stories by John Rowen Miano on Medium]]></description>
        <link>https://medium.com/@johnrowenmiano?source=rss-9584afb6bb04------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TXgcqJlDhAvgsNSD</url>
            <title>Stories by John Rowen Miano on Medium</title>
            <link>https://medium.com/@johnrowenmiano?source=rss-9584afb6bb04------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:15:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnrowenmiano/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[CLARO – How to Design Prompts That Work]]></title>
            <link>https://medium.com/@johnrowenmiano/claro-how-to-design-prompts-that-work-15136ae49671?source=rss-9584afb6bb04------2</link>
            <guid isPermaLink="false">https://medium.com/p/15136ae49671</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[medium]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[John Rowen Miano]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 17:42:56 GMT</pubDate>
            <atom:updated>2025-03-11T06:06:00.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtmiLQGTqPvY8YOccgMfTw.png" /><figcaption>The right questions get the best answers.</figcaption></figure><p>Have you ever instructed a child before? You may want your brother to run some errands at the market. Did you state the instructions clearly to him? Did you make sure he understood the task properly? Someone must get the instructions right so that everything will go smoothly. The same applies to talking to large language models.</p><p>In this article, we’ll be diving deep into the art and science of prompt design — the key to getting the most out of large language models (LLMs) like ChatGPT. If you’ve ever received a vague or unhelpful AI response, chances are the prompt wasn’t well-structured.</p><p>To solve this, we’ll explore CLARO, a simple but powerful framework for crafting effective prompts. By the end of this session, you’ll understand:</p><p>• How LLMs work and why prompt design matters.<br>• What a prompt is and how it influences AI responses.<br>• The CLARO method—a structured approach for creating high-quality prompts.<br>• Best practices to consistently get accurate, useful results.</p><h4>What is an LLM? How Does It Work?</h4><p>A Large Language Model (LLM) is an advanced AI trained on vast amounts of text to generate human-like responses. Examples include ChatGPT, Gemini, Claude, and LLaMA.</p><p>Here’s a simplified breakdown of how an LLM works:</p><p>• It predicts the next most likely word based on input (your prompt).<br>• It uses context, patterns, and probabilities from its training data to generate coherent responses.<br>• It doesn’t &quot;think&quot; like a human—it follows patterns based on probability.<br>• The quality of the prompt directly affects the quality of the response.</p><p><strong>Why Does This Matter for Prompt Design?</strong><br>Since LLMs don’t inherently &quot;understand&quot; concepts like humans do, we must guide them with well-structured prompts. A vague or ambiguous prompt leads to random, misleading, or incomplete answers. A clear, structured prompt produces focused, useful, and reliable responses.</p><h4>What is a Prompt?</h4><p>A prompt is any input you provide to an LLM to generate a response. It can be as simple as a question or as detailed as a structured instruction with examples.</p><p><strong>Types of Prompts</strong>:<br>• Simple Prompts → &quot;Tell me about climate change.&quot;<br>• Detailed Prompts → &quot;Explain climate change in simple terms for a 10-year-old.&quot;<br>• Instruction-Based Prompts → &quot;Summarize this article in 100 words.&quot;<br>• Role-Based Prompts → &quot;You are a marketing expert. Create an ad campaign for a new energy drink.&quot;</p><p>A well-crafted prompt increases accuracy, relevance, and consistency in responses.</p><h4>Prompt Design and Engineering</h4><p>Prompt design is the process of structuring your input to get the best possible response from an LLM.</p><p>Prompt engineering goes a step further—it involves advanced techniques, like:</p><p>• Chain-of-thought prompting (forcing the AI to show reasoning step by step).<br>• Few-shot learning (providing examples to guide responses).<br>• Temperature and top-k tuning (adjusting randomness in responses).</p><h4>The Science and Psychology of Prompting</h4><p>A. <strong>Cognitive Load &amp; AI Interpretation</strong></p><p>Humans and AI process information differently. LLMs function deterministically based on input, while humans engage in reasoning and intuition. Reducing cognitive load in prompts improves clarity:</p><p>✅ Simple, structured prompts → Better AI performance</p><p>❌ Ambiguous, open-ended prompts → Inconsistent results</p><p>B. <strong>The Role of Language Framing</strong></p><p>How we phrase a question influences the response. Example:</p><p>Neutral framing → &quot;Describe climate change.&quot; (General response)</p><p>Guided framing → &quot;Explain climate change from a scientific perspective with three key effects.&quot; (Targeted response)</p><p>C. <strong>The Priming Effect</strong></p><p>Priming influences the AI’s response style. Example:</p><p>&quot;You are a legal expert. Analyze this contract.&quot;</p><p>&quot;You are a storyteller. Rewrite this in a dramatic tone.&quot;</p><p>These role-based prompts prime the AI to adopt specific perspectives.</p><p>But before diving into complex methods, we need a strong foundation in structured prompt design. That’s where CLARO comes in.</p><h4>The CLARO Framework</h4><p>CLARO is a step-by-step method to create prompts that produce clear, reliable, and structured AI responses. Let’s break it down:</p><p><strong>1. Clear Objectives</strong><br>What do you want the AI to do? Define the goal of your prompt explicitly. Add a persona for a more appropriate response.</p><p>✅ Good: &quot;You are a journalist. Summarize this news article in three bullet points.&quot;</p><p>❌ Bad: &quot;Tell me about this article.&quot;</p><p>The clearer your objective, the more useful the AI’s response.</p><p><strong>2. List Steps</strong><br>Guide the AI with a structured process. If a task requires multiple steps, outline them.</p><p>✅ Good:<br> &quot;Explain how to bake a cake in three steps: 1) Ingredients, 2) Mixing process, 3) Baking instructions.&quot;</p><p>❌ Bad:<br> &quot;How do I bake a cake?&quot; (Too open-ended, results may vary)</p><p><strong>3. Apply Rules</strong><br>Set guidelines for tone, depth, or constraints.</p><p>✅ Good: &quot;Write a 100-word summary in formal academic style.&quot;</p><p>❌ Bad: &quot;Summarize this.&quot; (No rules = unpredictable output)</p><p><strong>4. Relevant Info</strong><br>Provide necessary context. AI models don’t have real-time awareness, so feed them relevant details.</p><p>✅ Good: &quot;Summarize this article about AI ethics. Here is the full text: [paste article].&quot;</p><p>❌ Bad: &quot;Summarize AI ethics.&quot; (Lacks specific context)</p><p><strong>5. Output Format</strong><br>Specify the format for better readability.</p><p>✅ Good:<br> &quot;List the key points in bullet form.&quot;<br> &quot;Respond in JSON format.&quot;</p><p>❌ Bad:<br> &quot;Explain it to me.&quot; (No format guidance)</p><h4>Best Practices for Effective Prompts</h4><ul><li>Be Specific: Vague prompts lead to vague answers. The more precise you are, the better the response.</li><li>Use Step-by-Step Instructions: AI performs better when given clear steps or sequences.</li><li>Give Examples: If you need a specific style or format, show an example.</li><li>Limit Scope: Avoid overly broad questions. Narrow the focus to get useful answers.</li><li>Experiment and Refine: If a prompt doesn’t work, tweak it. Try different structures and approaches.</li><li>Use System Messages (if available): Some AI platforms allow system messages to set behavior. E.g., &quot;You are a legal expert. Provide responses based on official case law.&quot;</li></ul><h4>Conclusion</h4><p>Mastering prompt design is essential for getting the best results from LLMs. By following the CLARO method—Clear Objectives, List Steps, Apply Rules, Relevant Info, and Output Format—you can craft prompts that yield precise, structured, and useful AI responses.</p><p><strong>Final Takeaways</strong>:<br>• LLMs don’t think; they generate responses based on patterns.</p><p>• Better prompts = better outputs.</p><p>• Use CLARO to design effective prompts every time.<br><br>Try applying CLARO in your own AI interactions and see how your results improve. Remember, the right question gets the best answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15136ae49671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[eXtreme Gradient Boosting (XGBoost) for Accurate Breast Cancer Prediction]]></title>
            <link>https://blog.gopenai.com/extreme-gradient-boosting-xgboost-for-accurate-breast-cancer-prediction-db247f1838b0?source=rss-9584afb6bb04------2</link>
            <guid isPermaLink="false">https://medium.com/p/db247f1838b0</guid>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[cancer]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[John Rowen Miano]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 01:50:27 GMT</pubDate>
            <atom:updated>2024-10-25T02:54:23.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1w20lLP_9z1POmFX5FQxg.jpeg" /><figcaption>Photo by Susan Wilkinson on Unsplash</figcaption></figure><h4><strong>October is the Breast Cancer Awareness Month.</strong></h4><p>As we honor this celebration, it is vital to explore innovative approaches that enhance early detection and improve patient outcomes. Breast cancer remains one of the most prevalent cancers affecting women globally, making timely and accurate diagnosis crucial. Among the many advancements in medical technology, machine learning has emerged as a powerful ally in the fight against breast cancer.</p><p>eXtreme Gradient Boosting (XGBoost) has garnered significant attention for its ability to deliver precise predictions in various medical applications, including cancer detection.</p><p>This article delves into the principles of XGBoost, its application in breast cancer prediction, and the potential it holds for transforming healthcare practices during a month dedicated to raising awareness and promoting research efforts in this critical area.</p><h4>The dataset — Breast Cancer Wisconsin (Diagnostic) Data Set</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TNCH5MOmPapuxfW-7g5_A.png" /><figcaption>The Breast Cancer Wisconsin (Diagnostic) Data Set from UCI Machine Learning</figcaption></figure><p>The <a href="https://www.kaggle.com/datasets/uciml/breast-cancer-wisconsin-data">dataset</a> contains 569 observations and 32 variables. The first 30 variables are the features that we will use to train our model. The last two variables are the ID number and the diagnosis (M = malignant, B = benign). We will use the first 30 variables to train our model and the last variable to evaluate it.</p><p>This dataset does need a bit of cleaning. The ID number is not useful for our model. So we will drop it. There is also a column called Unnamed: 32 and this column is empty. So we will drop it as well.</p><pre># Import the dataset<br>df = pd.read_csv(&#39;data.csv&#39;)<br><br># Drop the id and empty column<br>data.drop([&quot;Unnamed: 32&quot;, &quot;id&quot;], axis=1, inplace=True)</pre><pre> #   Column                   Non-Null Count  Dtype  <br>---  ------                   --------------  -----  <br> 0   id                       569 non-null    int64  <br> 1   diagnosis                569 non-null    object <br> 2   radius_mean              569 non-null    float64<br> 3   texture_mean             569 non-null    float64<br> 4   perimeter_mean           569 non-null    float64<br> 5   area_mean                569 non-null    float64<br> 6   smoothness_mean          569 non-null    float64<br> 7   compactness_mean         569 non-null    float64<br> 8   concavity_mean           569 non-null    float64<br> 9   concave points_mean      569 non-null    float64<br> 10  symmetry_mean            569 non-null    float64<br> 11  fractal_dimension_mean   569 non-null    float64<br> 12  radius_se                569 non-null    float64<br> 13  texture_se               569 non-null    float64<br> 14  perimeter_se             569 non-null    float64<br> 15  area_se                  569 non-null    float64<br> 16  smoothness_se            569 non-null    float64<br> 17  compactness_se           569 non-null    float64<br> 18  concavity_se             569 non-null    float64<br> 19  concave points_se        569 non-null    float64<br> 20  symmetry_se              569 non-null    float64<br> 21  fractal_dimension_se     569 non-null    float64<br> 22  radius_worst             569 non-null    float64<br> 23  texture_worst            569 non-null    float64<br> 24  perimeter_worst          569 non-null    float64<br> 25  area_worst               569 non-null    float64<br> 26  smoothness_worst         569 non-null    float64<br> 27  compactness_worst        569 non-null    float64<br> 28  concavity_worst          569 non-null    float64<br> 29  concave points_worst     569 non-null    float64<br> 30  symmetry_worst           569 non-null    float64<br> 31  fractal_dimension_worst  569 non-null    float64<br> 32  Unnamed: 32              0 non-null      float64</pre><h4>The model — eXtreme Gradient Boosting (XGBoost)</h4><p>Using the dataset, we train an eXtreme Gradient Boosting model to predict the target variable using a dataset of input features. According to <a href="https://dl.acm.org/doi/abs/10.1145/2939672.2939785">Chen &amp; Guestrin (2016)</a> , XGBoost has demonstrated superior predictive performance compared to other models like logistic regression in medical studies, which is crucial for making accurate diagnoses or risk assessments in precision medicine.</p><p>In 2022, the mention of XGBoost skyrocketed in peer-reviewed articles on PubMed, with <a href="https://pubmed.ncbi.nlm.nih.gov/?term=XGBoost&amp;filter=years.2019-2022">over 1,200 references, marking a significant uptick from the mere 134 references in 2019</a>.</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.30, random_state=42)</pre><pre>from xgboost import XGBClassifier<br><br># Create XGBoost model<br>xgb = XGBClassifier()<br><br># Train the model on the training data<br>xgb.fit(X_train, y_train)<br><br># Predict the target variable on the test data<br>y_pred = xgb.predict(X_test)</pre><h4>The evaluation — Classification Metrics and SHAP</h4><p>It’s important to note that accuracy is just one measure of a model’s performance, and it may not be the most appropriate measure for all problems. Depending on the problem and the specific requirements of the application, other metrics such as precision, recall, or F1 score may be more relevant. We use the classification_report function from Scikit-learn to calculate those measures.</p><pre>from sklearn.metrics import accuracy_score<br><br># Evaluate the accuracy of the model<br>accuracy = accuracy_score(y_test, y_pred)<br>print(f&#39;Accuracy: {accuracy:.2f}&#39;)</pre><pre>Accuracy: 0.97</pre><p>After training the model on the training set and evaluating its performance on the test set, we achieved a final accuracy of 0.97. This is a strong performance and indicates that the model is able to make accurate predictions on new, unseen data.</p><pre>from sklearn.metrics import classification_report<br>print(classification_report(y_test,y_pred))</pre><pre>                 precision    recall  f1-score   support<br><br>           0       0.98      0.97      0.98       108<br>           1       0.95      0.97      0.96        63<br><br>    accuracy                           0.97       171<br>   macro avg       0.97      0.97      0.97       171<br>weighted avg       0.97      0.97      0.97       171</pre><p>SHAP (SHapley Additive exPlanations) values provide a unified framework for interpreting machine learning models by showing how much each feature contributes to the prediction for a specific instance or across the whole dataset. Here are the plots we used for this model:</p><ul><li>Waterfall Plot: The waterfall plot explains the SHAP values for a single prediction. It shows how each feature contributes to the model’s output.</li><li>Summary Plot: The summary plot gives an overall view of the impact each feature has on the model output across the entire test set. It shows the distribution of SHAP values per feature.</li><li>Bar Plot: This shows the overall importance of features by displaying the mean absolute SHAP value for each feature, which is a good measure of feature importance.</li></ul><pre># Ensure you use TreeExplainer for XGBoost<br>explainer = shap.TreeExplainer(xgb)<br><br># Calculate SHAP values for the test data (this returns an Explanation object)<br>shap_values = explainer(X_test)<br><br># Get the base value (E[F(x)]) in log-odds<br>log_odds_base_value = explainer.expected_value<br><br># Convert the base value from log-odds to probability using the logistic function<br>probability_base_value = 1 / (1 + np.exp(-log_odds_base_value))<br>print(f&quot;Base value in log-odds: {log_odds_base_value}&quot;)<br>print(f&quot;Base value in probability: {probability_base_value}&quot;)<br><br># Visualize the SHAP values for a single instance (e.g., the first instance in X_test)<br>shap.plots.waterfall(shap_values[0])<br><br># Summary plot of SHAP values across the test set<br>shap.summary_plot(shap_values, X_test, feature_names=X.columns)<br><br># Feature importance based on SHAP values (mean absolute value)<br>shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type=&quot;bar&quot;)</pre><pre>Base value in log-odds: -0.6562219262123108<br>Base value in probability: 0.34158880217219745</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*o2ZlTEA8ozY_ZuZMI6gQgQ.png" /><figcaption><strong>Waterfall Plot of SHAP Values for a Single Instance</strong>: This plot illustrates how individual feature contributions (both positive and negative) influence the model’s prediction for a specific patient. The cumulative effect of each feature pushes the prediction towards malignant or benign classification.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*kgdrIWLPrwMLuc1hLFTVYQ.png" /><figcaption><strong>Summary Plot of SHAP Values Across Test Instances</strong>: This plot provides an overview of the importance and impact of each feature on the model’s predictions. Features are ranked by their average influence, with color indicating the feature value — red represents higher values and blue lower values, revealing how different feature levels correlate with cancer predictions.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*xrOVb66dMY4ZRcwmLGJ3Zg.png" /><figcaption><strong>Feature Importance Based on Mean SHAP Values</strong>: This bar plot ranks features according to their average absolute SHAP value, highlighting their overall contribution to the model’s predictions. The length of each bar indicates the relative importance of each feature in determining the likelihood of malignancy.</figcaption></figure><h4>The results — Discussion on model accuracy and SHAP values</h4><h4><strong>1. Accuracy: 0.97</strong></h4><p>The XGBoost model acquired an <strong>accuracy of 0.97</strong>, which means that the model correctly predicted 97% of the cases in the dataset (benign and malignant), indicating excellent overall performance.</p><h4>2. Precision, Recall, F1-Score, and Support</h4><p>The metrics are reported for two classes:</p><ul><li><strong>0</strong>: Benign cases</li><li><strong>1</strong>: Malignant cases</li></ul><h4>Class 0 (Benign)</h4><p><strong>Precision: 0.98</strong></p><p>The model acquired a precision of 0.98 for benign cases, which means that 98% of the instances predicted as benign were indeed benign. This indicates a very low false positive rate, showing the model is reliable in identifying benign cases.</p><p><strong>Recall: 0.97</strong></p><p>The model acquired a recall of 0.97, which means that the model correctly identified 97% of the actual benign cases, indicating that it misses very few benign cases (low false negative rate).</p><p><strong>F1-Score: 0.98</strong></p><p>The model acquired an F1-score of 0.98, which indicates a strong balance between precision and recall for benign cases.</p><p><strong>Support: 108</strong></p><p>There are 108 benign cases in the dataset, providing a good sample size for evaluating model performance.</p><h4>Class 1 (Malignant)</h4><p><strong>Precision: 0.95</strong></p><p>The model acquired a precision of 0.95 for malignant cases, which indicates that 95% of the instances predicted as malignant were indeed malignant. While slightly lower than the precision for benign cases, it still reflects a strong ability to correctly identify malignant cases with a low false positive rate.</p><p><strong>Recall: 0.97</strong></p><p>The model acquired a recall of 0.97, which means that the model correctly identified 97% of the actual malignant cases, indicating it misses very few malignant cases (low false negative rate).</p><p><strong>F1-Score: 0.96</strong></p><p>The model acquired an F1-score of 0.96 shows a good balance between precision and recall for malignant cases, demonstrating effective performance in classifying this group.</p><p><strong>Support: 63</strong></p><p>There are 63 malignant cases in the dataset. The number of support for malignant cases is lower than for benign, which is common in datasets where benign cases outnumber malignant ones.</p><h4>3. Macro and Weighted Averages</h4><p><strong>Macro Average</strong>:</p><ul><li><strong>Precision: 0.97, Recall: 0.97, F1-Score: 0.97</strong></li><li>The macro average treats all classes equally, calculating the average performance across classes. This indicates that the model performs consistently well across both classes.</li></ul><p><strong>Weighted Average</strong>:</p><ul><li><strong>Precision: 0.97, Recall: 0.97, F1-Score: 0.97</strong></li><li>The weighted average considers the support of each class when calculating the average, which means it accounts for the class imbalance. The high values indicate that the model performs well even when factoring in the number of instances per class.</li></ul><h4>4. SHapley Additive exPlanations (SHAP) values</h4><p><strong>Waterfall Plot of SHAP Values for a Single Instance:</strong></p><p>1. <strong><em>XGBoost Prediction</em></strong>: The value at the top of the graph (<strong>-5.016</strong>), represents the raw output of the XGBoost model before applying any transformation to make the prediction. A negative score suggests the prediction leans towards one class (likely benign), while a positive score would lean towards the other (likely malignant).</p><p>2. <strong><em>E[f(x)] = -0.656</em></strong> : This is the average prediction across all samples. In this case, the baseline prediction is slightly negative. This value is in <strong>log-odds</strong> base value, which represents the default log-odds output of the model before any features are considered. The value is converted into probability base value, which now becomes <strong>0.3416</strong>. The value of 0.3416 indicates that, on average, the model predicts that <strong>34.16%</strong> of the instances (patients in this case) in the test set have malignant breast cancer. This means that there is a <strong>34.16% chance</strong> that a randomly selected patient from your test set is diagnosed with malignant cancer. Since <strong>0.3416</strong> is less than <strong>0.5</strong>, it suggests that the model predicts a higher likelihood of benign cases compared to malignant cases for the majority of the test set.</p><p>3. <strong><em>Feature Contributions</em></strong>: Each step in the waterfall plot corresponds to a feature in the dataset, and its impact on the prediction.</p><p>Features with blue boxes reduce the model&#39;s output score (in this case, likely pushing towards benign classification), while red boxes increase the score (pushing towards malignant classification). The magnitude of the change in score is shown inside each box.</p><p>4. <strong><em>Top Contributing Features</em></strong>: Feature 7 (which seems to correspond to &quot;concavity_mean&quot;) has the largest negative impact on the prediction, decreasing the score by -1.32.</p><p>Feature 22 (which seems to correspond to &quot;texture_worst&quot;) reduces the score by -0.99.</p><p>Feature 26 (possibly &quot;compactness_worst&quot;) adds +0.60 to the score, indicating it pushes the model slightly towards predicting malignancy.</p><p><strong>Summary Plot of SHAP Values Across Test Instances:</strong></p><p>1. <strong><em>X-Axis (SHAP Values)</em></strong>: The SHAP value represents the impact of a feature on the model&#39;s output.</p><p>Negative SHAP values (left side) contribute to a benign prediction, while positive SHAP values (right side) contribute to a malignant prediction.</p><p>2. <strong><em>Y-Axis (Features)</em></strong>: The features are ranked in descending order of importance, from the most impactful feature to the least impactful.</p><p>3. <strong><em>Dots</em></strong>: Each dot represents a specific data point (an observation) from your dataset.</p><p>The position of the dot on the x-axis shows the SHAP value for that data point (how much that feature pushed the prediction toward benign or malignant).</p><p>4. <strong><em>Color (Feature Value)</em></strong>: The color of the dot indicates the value of the feature for that particular data point:</p><p>Red: High feature values.<br>Blue: Low feature values.</p><p>5. <strong><em>Analysis</em></strong>: Concave points_mean and concave points_worst are the most important features (top of the chart), where high values (red dots) push the prediction toward malignancy, while low values (blue dots) push toward benign.</p><p>Concavity_worst, area_worst, and perimeter_worst are also important features. Large values for these features tend to increase the likelihood of a malignant prediction.</p><p>Features lower on the list, such as concavity_se and radius_se, have less impact overall, but individual values still contribute to predictions.</p><p>The plot shows that high values for some features (e.g., concave points, area_worst) are strongly associated with malignant diagnoses, while low values (especially in concave points) are more associated with benign diagnoses.</p><p><strong>Feature Importance Based on Mean SHAP Values:</strong></p><p>1. <strong><em>Y-Axis (Features)</em></strong>: The features are listed in descending order of their importance in the model.</p><p>This order is based on the mean absolute SHAP value of each feature, showing how much, on average, each feature contributes to the model’s predictions.</p><p>2. <strong><em>X-Axis (Mean SHAP Value)</em></strong>: The mean SHAP value (absolute) represents the average impact of each feature on the model&#39;s predictions.</p><p>Higher SHAP values indicate that the feature has a larger influence on the predictions.</p><p>3. <strong><em>Key Observations</em></strong>: Concave points_mean is the most important feature, with the highest mean SHAP value. This feature has the largest average influence on the model’s output.</p><p>Concave points_worst and concavity_worst are also highly important, which means these features consistently affect the predictions significantly.</p><p>Other important features include area_worst, perimeter_worst, and texture_worst, showing that various aspects of tumor shape and size (related to worst-case measurements) are strong indicators in predicting the malignancy of breast cancer.</p><p>Lower-ranked features such as smoothness_se, radius_se, and concavity_se have relatively smaller impacts on the predictions.</p><h4>Conclusion</h4><p>The XGBoost model demonstrated excellent performance in classifying benign and malignant breast cancer cases, with an accuracy of 0.97. The high precision, recall, and F1-scores across both classes indicate that the model is reliable in predicting both benign and malignant cases, while maintaining a balance between false positives and false negatives. The SHAP analysis further validates the model’s decision-making process, highlighting the importance of features like “concave points,” “area,” “perimeter,” and “texture” in influencing predictions.</p><p><strong>Key Insights:</strong></p><ol><li><strong>Accuracy and Metrics</strong>: The model’s high accuracy (97%) and nearly perfect precision, recall, and F1-scores demonstrate its ability to differentiate between benign and malignant cases effectively, with minimal errors.</li><li><strong>Feature Importance</strong>: SHAP analysis revealed that features related to the shape and size of the tumor (e.g., concave points_mean, area_worst, and perimeter_worst) are the most critical factors in predicting malignancy. These features, particularly related to concavity, play a significant role in the model’s decision-making process.</li><li><strong>Class Imbalance</strong>: Even though the dataset has more benign cases than malignant ones, the weighted averages for precision, recall, and F1-score are as high as the macro averages, indicating that the model handles class imbalance effectively.</li></ol><p><strong>Suggestions:</strong></p><ol><li><strong>Model Validation and Further Testing</strong>: While the current metrics suggest high performance, it would be beneficial to conduct further cross-validation to confirm the model’s generalizability to unseen data. Testing on larger or more diverse datasets can also help improve robustness.</li><li><strong>Explainability and Clinical Applications</strong>: The SHAP values provide valuable insights into how the model arrives at its predictions, making it more interpretable for clinical use. These insights should be communicated effectively to medical professionals to increase trust and acceptance of the model in diagnostic workflows.</li><li><strong>Improving Malignant Classification</strong>: Although the model performs well in predicting malignant cases, the precision for malignant cases is slightly lower (0.95) than for benign cases (0.98). Fine-tuning the model through hyperparameter optimization or adjusting class weights could potentially improve the precision for malignant classifications, reducing false positives even further.</li><li><strong>Feature Engineering and Reduction</strong>: Since concave points and related tumor shape features are dominant, there may be room for dimensionality reduction or feature engineering to optimize the model further. A feature selection process might remove less impactful features and streamline the model without sacrificing performance.</li><li><strong>Model Integration in Healthcare</strong>: If the model is to be used in real-world medical diagnostics, it should be integrated with other clinical tools for breast cancer detection. Additionally, regular model updates and retraining with new data would ensure that the model stays relevant and accurate as clinical practices evolve.</li></ol><h4>References</h4><p>[1] <em>Breast Cancer Wisconsin (Diagnostic) data set</em>. (2016, September 25). <a href="https://www.kaggle.com/datasets/uciml/breast-cancer-wisconsin-data">https://www.kaggle.com/datasets/uciml/breast-cancer-wisconsin-data</a></p><p>[2] Chen, T., &amp; Guestrin, C. (2016). XGBoost. <em>KDD ’16: Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining</em>. <a href="https://doi.org/10.1145/2939672.2939785">https://doi.org/10.1145/2939672.2939785</a></p><p>[3] Hyunjoonbok. (n.d.). <em>Python-Projects/GeneralML/ExplainableML at master · hyunjoonbok/Python-Projects</em>. GitHub. <a href="https://github.com/hyunjoonbok/Python-Projects/tree/master/GeneralML/ExplainableML">https://github.com/hyunjoonbok/Python-Projects/tree/master/GeneralML/ExplainableML</a></p><p>[4] Wolberg, W., Mangasarian, O., Street, N., &amp; Street, W. (1993). Breast Cancer Wisconsin (Diagnostic) [Dataset]. UCI Machine Learning Repository. <a href="https://doi.org/10.24432/C5DW2B">https://doi.org/10.24432/C5DW2B</a>.</p><p>[5]<em> XGBoost — Search results — PubMed</em>. (n.d.). PubMed. <a href="https://pubmed.ncbi.nlm.nih.gov/?term=XGBoost&amp;filter=years.2019-2022">https://pubmed.ncbi.nlm.nih.gov/?term=XGBoost&amp;filter=years.2019-2022</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db247f1838b0" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/extreme-gradient-boosting-xgboost-for-accurate-breast-cancer-prediction-db247f1838b0">eXtreme Gradient Boosting (XGBoost) for Accurate Breast Cancer Prediction</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explainable ML: Making Black-Box Models Understandable]]></title>
            <link>https://medium.com/@johnrowenmiano/explainable-ml-making-black-box-models-understandable-5751366b501a?source=rss-9584afb6bb04------2</link>
            <guid isPermaLink="false">https://medium.com/p/5751366b501a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[black-box]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <dc:creator><![CDATA[John Rowen Miano]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 04:16:30 GMT</pubDate>
            <atom:updated>2024-09-15T04:16:30.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJujoWZ1xw_7tMq4VS6gZQ.jpeg" /><figcaption>Photo by Anton Maksimov 5642.su on Unsplash</figcaption></figure><p>There’s a <strong>common misconception</strong> that <strong><em>machine learning (ML) is just a “black box,”</em></strong> meaning people think it’s impossible to understand how or why a model makes certain decisions. A <a href="https://www.sciencedirect.com/science/article/pii/S0004370218305988">study in 2019 by Miller</a> delves into the <strong>human need for explanations</strong> and how <strong>ML systems are often viewed as black boxes because they lack the ability to explain their reasoning in human-understandable ways</strong>. It stresses that when people can’t get clear explanations from ML models, they assume the models are mysterious or unknowable. While it’s true that some models, especially the more complex ones like deep learning, can be tricky to interpret, calling them “black boxes” oversimplifies things.</p><blockquote><a href="https://dictionary.cambridge.org/us/dictionary/english/black-box"><strong>black box</strong></a></blockquote><blockquote><strong><em>noun</em></strong> <a href="https://dictionary.cambridge.org/us/help/codes.html">[ C ]</a><br><strong>US</strong> /ˌblæk ˈbɑːks/ <strong>UK</strong> /ˌblæk ˈbɒks/</blockquote><blockquote><strong>a system that produces results without the user being able to see or understand how it works</strong></blockquote><p>As machine learning (ML) models become increasingly embedded in critical applications like healthcare, finance, and autonomous systems, their decisions can significantly impact people’s lives. However, many ML models, especially complex ones like deep neural networks and ensemble methods, are often referred to as “black-box” models. This term arises from their opaque nature, where the inner workings of the model and how decisions are made are not easily interpretable by humans. This<strong> lack of transparency can lead to distrust in AI systems</strong>, especially in high-stakes scenarios.</p><h4>Why Model Interpretability Matters</h4><ol><li><strong>Accountability and Trust</strong>: In applications like healthcare, AI models may influence diagnoses or treatment decisions. It is crucial for doctors and patients to understand how these decisions are made to build trust. For example, an AI model recommending a particular cancer treatment must provide a clear rationale for its decision to help healthcare professionals make informed choices.</li><li><strong>Bias Detection and Mitigation</strong>: Machine learning models can unintentionally perpetuate biases present in the training data. Interpretability helps identify these biases, allowing developers to address them before they cause harm. For instance, in credit scoring or job recruitment algorithms, unexplainable outcomes may lead to discriminatory decisions against certain groups.</li><li><strong>Compliance with Regulations</strong>: Laws like the European Union’s GDPR emphasize the right to explanation for individuals affected by algorithmic decisions. This regulatory push compels organizations to use interpretable models or employ techniques that explain their models’ decisions.</li><li><strong>Debugging and Improvement</strong>: Interpretability allows data scientists to understand where a model may be going wrong. If a model misclassifies an image or predicts incorrect outcomes in a financial forecasting model, understanding why the error occurred can help improve future iterations of the model.</li></ol><h4>Techniques for Model Interpretability</h4><p>To address the explainability challenge, several methods have been developed. Two of the most widely used techniques are LIME and SHAP, which provide insights into individual model predictions while offering flexibility across different types of models.</p><h4>1. <strong>LIME (Local Interpretable Model-agnostic Explanations)</strong></h4><p>LIME is a popular technique that provides interpretability for black-box models by approximating them with simpler, interpretable models like linear regression or decision trees. The key idea is to understand a specific prediction rather than the entire model.</p><p><strong>How LIME works</strong>:</p><ul><li>LIME perturbs the input data by slightly altering its features and records the predictions of the black-box model.</li><li>It then creates a locally interpretable model (such as a linear model) that is easy to understand and approximates the behavior of the black-box model around the specific instance.</li><li>LIME shows how each feature contributes to the prediction for that instance, giving a clear and intuitive explanation of the decision.</li></ul><p>For example, in an image classification task, LIME could identify which parts of the image (specific pixels or segments) were most important in determining the predicted class (e.g., “cat” or “dog”). This allows users to understand why the model made that particular prediction.</p><p><strong>Code Example for LIME:</strong></p><pre># Install lime if you haven&#39;t<br># !pip install lime<br><br>import numpy as np<br>import pandas as pd<br>from sklearn.datasets import load_iris<br>from sklearn.ensemble import RandomForestClassifier<br>from lime.lime_tabular import LimeTabularExplainer<br><br># Load data<br>data = load_iris()<br>X, y = data.data, data.target<br><br># Fit a black-box model<br>model = RandomForestClassifier(n_estimators=100)<br>model.fit(X, y)<br><br># Create a LIME explainer<br>explainer = LimeTabularExplainer(X, feature_names=data.feature_names, class_names=data.target_names, discretize_continuous=True)<br><br># Select an instance to explain<br>instance = X[50]<br>exp = explainer.explain_instance(instance, model.predict_proba, num_features=2)<br><br># Print the explanation<br>exp.show_in_notebook()</pre><p>In this example, we train a random forest model on the Iris dataset and use LIME to explain the prediction for a single instance. The output provides insights into which features most influenced the model’s prediction.</p><blockquote><strong>LIME Official Repository</strong>: <a href="https://github.com/marcotcr/lime">marcotcr/lime</a></blockquote><p>This repository contains the official implementation of <strong>LIME (Local Interpretable Model-agnostic Explanations)</strong>, created by Marco Tulio Ribeiro. LIME is a popular technique for explaining the predictions of machine learning models. The repository provides:</p><ul><li><strong>Code for LIME</strong>: This includes functions for creating interpretable explanations of complex, black-box models. LIME explains a model’s behavior by perturbing the input data and observing the changes in predictions.</li><li><strong>Tutorials and Examples</strong>: The repository offers tutorials for understanding and using LIME on various machine learning models (such as decision trees, neural networks, etc.).</li><li><strong>Community Contributions</strong>: Users can contribute by reporting issues, suggesting improvements, or submitting their own code, which helps improve the functionality and reach of the LIME library.</li></ul><h4>2. <strong>SHAP (SHapley Additive exPlanations)</strong></h4><p>SHAP is based on game theory and provides a unified approach to explaining model predictions. It assigns each feature a Shapley value, which represents the contribution of that feature to the prediction.</p><p><strong>How SHAP works</strong>:</p><ul><li>SHAP values measure the impact of each feature on a model’s prediction, assuming that features collaborate to form the prediction. This is based on the Shapley values concept from cooperative game theory.</li><li>SHAP works by considering all possible combinations of feature inputs and calculating their marginal contributions to the prediction. It then averages these contributions to assign an individual importance score to each feature.</li></ul><p><strong>Benefits</strong>:</p><ul><li>SHAP is model-agnostic, meaning it can be applied to any machine learning model, and it produces consistent explanations.</li><li>It not only explains individual predictions but also provides a global view of how each feature contributes to the overall model’s decision-making process.</li></ul><p>For example, in a loan approval model, SHAP could show that a customer’s credit score had the highest positive impact on their approval, while other factors, such as income or age, had smaller but still relevant influences. This makes it easier for both customers and banks to understand why a loan was approved or denied.</p><p><strong>Code Example for SHAP:</strong></p><pre># Install shap if you haven&#39;t<br># !pip install shap<br><br>import shap<br>import xgboost<br>from sklearn.model_selection import train_test_split<br><br># Load data<br>X, y = load_iris(return_X_y=True)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Train an XGBoost model<br>model = xgboost.XGBClassifier().fit(X_train, y_train)<br><br># Create a SHAP explainer<br>explainer = shap.TreeExplainer(model)<br><br># Select an instance to explain<br>shap_values = explainer.shap_values(X_test[0])<br><br># Visualize the SHAP explanation<br>shap.initjs()<br>shap.force_plot(explainer.expected_value, shap_values[1], X_test[0], feature_names=load_iris().feature_names)</pre><p>In this example, we train an XGBoost classifier on the Iris dataset and use SHAP to explain the prediction for a test instance. The SHAP force plot visually shows which features pushed the prediction towards a particular class.</p><blockquote><strong>SHAP Official Repository</strong>: <a href="https://github.com/slundberg/shap">slundberg/shap</a></blockquote><p>This repository contains the official implementation of <strong>SHAP (SHapley Additive exPlanations)</strong>, developed by Scott Lundberg. SHAP is a game-theory-based approach to explain model predictions by attributing the contribution of each feature to the prediction. The repository provides:</p><ul><li><strong>Code for SHAP</strong>: The implementation includes a variety of functions to compute SHAP values for different types of models, including tree-based models (like XGBoost, LightGBM), linear models, and deep learning models.</li><li><strong>Visualization Tools</strong>: SHAP includes powerful visualization tools that allow you to visualize feature importance, individual prediction explanations, and summary plots of feature effects across the dataset.</li><li><strong>Comprehensive Documentation</strong>: The repository has detailed documentation and examples, helping users understand how to apply SHAP in different contexts, including global model interpretability and instance-level explanations.</li></ul><h4>3. <strong>Model Transparency</strong></h4><p>Another approach to improving explainability is designing models that are inherently interpretable. While complex models like deep neural networks are powerful, simpler models like decision trees, linear regression, and logistic regression provide transparency by their nature.</p><p><strong>Interpretable models</strong>:</p><ul><li><strong>Decision Trees</strong>: These are easy to understand because they mimic human decision-making by breaking down decisions into logical sequences.</li><li><strong>Linear Models</strong>: In models like linear or logistic regression, the contribution of each feature is explicit, with weights showing how much each variable influences the outcome.</li></ul><p>In some cases, sacrificing a small amount of model accuracy for transparency is acceptable, especially in industries where understanding the decision-making process is more important than achieving state-of-the-art predictive performance.</p><h4>Real-World Use Cases of Explainable AI</h4><ol><li><strong>Healthcare</strong>: IBM’s Watson for Oncology assists doctors in cancer treatment recommendations by providing evidence and showing which medical studies or patient data points it used to make suggestions. Explainability ensures that doctors can trust the system to guide life-altering decisions. <br>IBM has open-source projects on GitHub like <a href="https://github.com/IBM/AIF360"><strong>IBM/AIF360</strong></a>, which focuses on fairness in AI models, an area closely linked to explainability.</li><li><strong>Finance</strong>: Financial institutions use machine learning models for credit scoring, fraud detection, and risk management. Regulatory bodies often require models to provide interpretable reasons for accepting or rejecting a loan application to ensure fairness and prevent discriminatory practices.<br>SHAP is used extensively in the financial sector to detect model bias or compliance with regulatory requirements. For practical use cases, check <a href="https://github.com/mementum/backtrader"><strong>Finance ML Models on GitHub</strong></a>.</li><li><strong>Autonomous Vehicles</strong>: Explainability is crucial in autonomous driving systems. If an autonomous vehicle makes a mistake or encounters an accident, it is important to know how the AI made its decision, whether it was due to faulty sensors, bad data, or poor model behavior. <br><a href="https://github.com/carla-simulator/carla"><strong>CARLA</strong></a>, an open-source autonomous driving simulator, provides an environment where explainability can be integrated to analyze how ML models in autonomous cars make decisions.</li></ol><h4>Conclusion</h4><p>As machine learning continues to shape the future of various industries, explainability will remain a key consideration. Techniques like LIME, SHAP, and inherently transparent models help bridge the gap between model complexity and human understanding, ensuring that black-box models can be trusted, debugged, and refined. By making machine learning models more interpretable, we can foster greater transparency, accountability, and fairness in AI systems that impact society on a large scale.</p><h4>References</h4><p><strong>[1]</strong><em> black box</em>. (2024). <a href="https://dictionary.cambridge.org/us/dictionary/english/black-box">https://dictionary.cambridge.org/us/dictionary/english/black-box</a><br><strong>[2]</strong> Carla-Simulator. (n.d.). <em>GitHub — carla-simulator/carla: Open-source simulator for autonomous driving research.</em> GitHub. <a href="https://github.com/carla-simulator/carla">https://github.com/carla-simulator/carla</a><br><strong>[3]</strong> Marcotcr. (n.d.). <em>GitHub — marcotcr/lime: Lime: Explaining the predictions of any machine learning classifier</em>. GitHub. <a href="https://github.com/marcotcr/lime">https://github.com/marcotcr/lime</a><br><strong>[4]</strong> Mementum. (n.d.). <em>GitHub — mementum/backtrader: Python Backtesting library for trading strategies</em>. GitHub. <a href="https://github.com/mementum/backtrader">https://github.com/mementum/backtrader</a><br><strong>[5]</strong> Miller, T. (2019). <em>Explanation in artificial intelligence: Insights from the social sciences</em>. Artificial Intelligence, 267, 1–38.<br><strong>[6]</strong> Shap. (n.d.). <em>GitHub — shap/shap: A game theoretic approach to explain the output of any machine learning model.</em> GitHub. <a href="https://github.com/shap/shap">https://github.com/shap/shap</a><br><strong>[7]</strong> Trusted-Ai. (n.d.). <em>GitHub — Trusted-AI/AIF360: A comprehensive set of fairness metrics for datasets and machine learning models, explanations for these metrics, and algorithms to mitigate bias in datasets and models.</em> GitHub. <a href="https://github.com/Trusted-AI/AIF360">https://github.com/Trusted-AI/AIF360</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5751366b501a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Statistical Learning Theory in Machine Learning]]></title>
            <link>https://medium.com/@johnrowenmiano/understanding-statistical-learning-theory-in-machine-learning-7ade966137c9?source=rss-9584afb6bb04------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ade966137c9</guid>
            <category><![CDATA[statistical-learning]]></category>
            <category><![CDATA[generalization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[John Rowen Miano]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 12:28:19 GMT</pubDate>
            <atom:updated>2024-09-17T08:37:32.811Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Statistical learning theory is a branch of artificial intelligence that provides the theoretical foundation for machine learning algorithms.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4gkNOcRcLbvjCnjIV5LEA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sortino?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Joshua Sortino</a> on <a href="https://unsplash.com/photos/worms-eye-view-photography-of-ceiling-LqKhnDzSF-8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Imagine you’re teaching a child how to recognize different animals. You show them countless pictures of cats and dogs, pointing out their unique features. Over time, the child learns to identify these animals even in unfamiliar images. But what if you had only shown them a few pictures? Or if the pictures were blurred and inconsistent? This is where <strong>Statistical Learning Theory (SLT)</strong> comes into play — it’s the unsung hero behind the scenes, ensuring that machine learning algorithms can make sense of data and perform admirably in the real world.</p><p>Statistical Learning Theory provides a rigorous foundation for understanding how machine learning algorithms learn from data, generalize to new situations, and make predictions. This framework integrates concepts from statistics, machine learning, and optimization, and has been pivotal in the development of many modern learning algorithms.</p><h3>The History and Development of Statistical Learning Theory</h3><p>Statistical Learning Theory has its roots in the late 20th century, primarily through the contributions of Vladimir Vapnik and his colleagues. The theory was developed to address the limitations of earlier statistical methods and provide a theoretical basis for learning algorithms that can generalize well from limited training data.</p><h4>Vapnik-Chervonenkis (VC) Theory</h4><p>At the heart of SLT lies the Vapnik-Chervonenkis (VC) dimension, introduced by Vladimir Vapnik and Alexey Chervonenkis in the early 1970s. Think of it as the IQ test for machine learning models. The VC dimension measures a model’s capacity to classify various datasets — essentially, how flexible the model is. A high VC dimension means the model can capture complex patterns but might overfit (like a student who memorizes answers rather than understanding concepts). A low VC dimension suggests a model that might be too simplistic, potentially missing the nuances (akin to a student who doesn’t grasp the core material).</p><blockquote><strong>VC Dimension</strong>: The VC dimension is defined as the largest number of points that can be shattered (perfectly classified) by the hypothesis class. A high VC dimension indicates a more complex model that can fit more intricate patterns in the data, but also risks overfitting. Conversely, a low VC dimension suggests a simpler model that may underfit the data.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*xODfXpBQJFTJA_iG606gIQ.jpeg" /><figcaption><a href="http://www.clrc.rhul.ac.uk/people/chervonenkis/"><em>Alexei Chervonenkis</em></a><em> and </em><a href="http://www.clrc.rhul.ac.uk/people/vlad/"><em>Vladimir Vapnik</em></a></figcaption></figure><h4>Support Vector Machines (SVM)</h4><p>Fast forward to the 1990s, and we see the rise of Support Vector Machines (SVMs). Imagine a high-stakes courtroom drama where you need to draw a line (or hyperplane) that best separates two opposing sides. That’s what SVMs do — they find the optimal boundary that maximizes the margin between different classes of data. Thanks to VC Theory, SVMs could generalize exceptionally well, making them the go-to method for various classification tasks.</p><p>The development of Support Vector Machines (SVMs) was a major practical application of VC Theory. This approach leverages the principles of Statistical Learning Theory to achieve robust generalization even in high-dimensional spaces.</p><blockquote><strong>Margin Maximization</strong>: SVMs aim to maximize the margin, or the distance between the hyperplane and the nearest data points from each class (support vectors). This principle helps in improving the model’s ability to generalize to unseen data.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*1jova1Ps7hfWqnsfJB7Ptw.png" /><figcaption>Margin maximization principle: the basic idea of Support Vector Machine</figcaption></figure><h3>Key Concepts in Statistical Learning Theory</h3><p>Understanding SLT involves grasping several core concepts that underpin its effectiveness.</p><h4>Hypothesis Space</h4><p>Consider the hypothesis space as a buffet of potential solutions. It encompasses all the functions a learning algorithm might consider. The richer this buffet, the more options the algorithm has — but beware, a vast hypothesis space can also lead to overfitting, just like a buffet with too many choices might overwhelm you.</p><blockquote>The hypothesis space is the set of all possible functions (hypotheses) that a learning algorithm can consider based on the training data. A more extensive hypothesis space allows for greater flexibility and complexity, potentially leading to better fitting of the data. However, it also increases the risk of overfitting.</blockquote><h4>Overfitting and Underfitting</h4><ul><li><strong>Overfitting</strong>: Overfitting occurs when a model learns the noise in the training data rather than the underlying pattern. This typically results in high accuracy on the training set but poor performance on new, unseen data. It’s like cramming for an exam without understanding the subject.</li><li><strong>Underfitting</strong>: Underfitting happens when a model is too simple to capture the underlying structure in the data. This results in poor performance on both training and test data. This is akin to not studying enough, resulting in poor performance overall.</li></ul><h4>Generalization</h4><p>Generalization is the golden goal. It’s the model’s ability to apply learned patterns to new, unseen data. SLT provides methods to estimate generalization performance, including cross-validation and out-of-sample testing. Imagine a student who, after learning from practice tests, can ace any new question that comes their way.</p><h4>Bias-Variance Trade-off</h4><p>The bias-variance trade-off is a fundamental concept in machine learning. Balancing bias and variance is akin to walking a tightrope.</p><ul><li><strong>Bias</strong>: Bias refers to the error introduced by approximating a real-world problem with a simplified model. High bias can lead to underfitting, where the model is too simple to capture the underlying data trends.</li><li><strong>Variance</strong>: Variance measures how much the model’s predictions vary with changes in the training data. High variance can lead to overfitting, where the model is too sensitive to the training data and performs poorly on new data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*Xb1pARRObW2WM6-vK037QA.jpeg" /><figcaption>An optimal balance of bias and variance would never overfit or underfit the model.</figcaption></figure><p>Balancing bias and variance is crucial for developing models that generalize well.</p><h4>Error Bounds</h4><p>Error bounds are like crystal balls for models.</p><p>Statistical Learning Theory provides methods to derive error bounds that indicate how well a model is expected to perform on unseen data. These bounds are based on factors such as the size of the training sample and the complexity of the hypothesis class. Techniques like the Hoeffding inequality and PAC (Probably Approximately Correct) learning theory are used to derive these bounds.</p><h3>Application of Statistical Learning Theory on SVMs</h3><p>To demonstrate an application of Statistical Learning Theory (SLT) in Support Vector Machines (SVM) using Python, we’ll use the scikit-learn library to train an SVM classifier on a sample dataset. The goal is to illustrate how the principles of SLT, such as maximizing the margin between classes and preventing overfitting, are applied through SVM.</p><p>We’ll use the Iris dataset, a popular dataset in machine learning, and train an SVM to classify different types of iris flowers.</p><h4>1. Importing Libraries</h4><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn import datasets<br>from sklearn.model_selection import train_test_split<br>from sklearn.svm import SVC<br>from sklearn.metrics import accuracy_score<br></pre><ul><li><strong>numpy</strong>: Used for numerical operations, particularly for handling arrays and matrices.</li><li><strong>matplotlib.pyplot</strong>: Used for plotting data and results in a graphical format.</li><li><strong>sklearn.datasets</strong>: Provides datasets for machine learning. In this case, the <strong>Iris</strong> dataset will be used.</li><li><strong>sklearn.model_selection.train_test_split</strong>: A function that splits the dataset into training and testing sets.</li><li><strong>sklearn.svm.SVC</strong>: Support Vector Classification, which implements the SVM algorithm for classification tasks.</li><li><strong>sklearn.metrics.accuracy_score</strong>: Calculates the accuracy of the model’s predictions compared to actual values.</li></ul><h4>2. Loading Dataset</h4><pre># Load the iris dataset<br>iris = datasets.load_iris()<br>X = iris.data[:, :2]  # We only take the first two features.<br>y = iris.target</pre><ul><li><strong>datasets.load_iris()</strong>: Loads the famous <strong>Iris</strong> dataset, a common dataset used for classification tasks with three types of flowers (setosa, versicolor, virginica).</li><li><strong>X = iris.data[:, :2]</strong>: Here, X is the feature matrix. We are selecting only the first two features (for simplicity and visualization purposes) out of the four available features in the Iris dataset.</li><li><strong>y = iris.target</strong>: The target labels (i.e., the species of the iris flower) are stored in y.</li></ul><h4>3. Splitting the Data</h4><pre># Split into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)</pre><p><strong>train_test_split()</strong>: Splits the dataset into training and testing sets.</p><ul><li><strong>X_train and </strong><strong>y_train</strong>: Features and labels for training the SVM.</li><li><strong>X_test and </strong><strong>y_test</strong>: Features and labels for evaluating the model.</li><li><strong>test_size=0.3</strong>: 30% of the data is used for testing, and 70% for training.</li><li><strong>random_state=42</strong>: Ensures the same random split is generated every time the code is run, making the results reproducible.</li></ul><h4>4. Training the SVM Model</h4><pre># Create the SVM model<br>svm_model = SVC(kernel=&#39;linear&#39;, C=1)<br><br># Train the model<br>svm_model.fit(X_train, y_train)</pre><p><strong>SVC()</strong>: Initializes the Support Vector Classifier (SVC) with specific parameters.</p><ul><li><strong>kernel=&#39;linear&#39;</strong>: Specifies a linear kernel. In SVM, a kernel function is used to transform the data so that a linear boundary can be applied even for non-linear problems. Here, we use a linear boundary (hyperplane) to separate the classes.</li><li><strong>C=1</strong>: This parameter controls the trade-off between maximizing the margin (distance between the decision boundary and support vectors) and minimizing classification error. A lower C creates a wider margin, but may misclassify some points, while a higher C results in a narrower margin.</li></ul><p><strong>svm_model.fit(X_train, y_train)</strong>: Trains the SVM model using the training data (X_train and y_train). The model finds the optimal hyperplane that separates the classes in the training data.</p><h4>5. Making Predictions</h4><pre># Make predictions on the test data<br>y_pred = svm_model.predict(X_test)</pre><p><strong>svm_model.predict(X_test)</strong>: Uses the trained SVM model to predict the class labels (y_pred) of the unseen test data (X_test).</p><h4>6. Evaluating the Model</h4><pre># Calculate the accuracy<br>accuracy = accuracy_score(y_test, y_pred)<br>print(f&quot;Accuracy: {accuracy * 100:.2f}%&quot;)</pre><ul><li><strong>accuracy_score(y_test, y_pred)</strong>: Compares the true labels (y_test) to the predicted labels (y_pred) and calculates the accuracy of the model.</li><li><strong>print(f&quot;Accuracy: {accuracy * 100:.2f}%&quot;)</strong>: Prints the accuracy as a percentage with two decimal places of precision.</li></ul><h4>7. Plotting the Decision Boundary</h4><pre># Plot the decision boundary<br>def plot_decision_boundary(X, y, model):<br>    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1<br>    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1<br>    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),<br>                         np.arange(y_min, y_max, 0.02))<br><br>    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])<br>    Z = Z.reshape(xx.shape)<br><br>    plt.contourf(xx, yy, Z, alpha=0.8)<br>    plt.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor=&#39;k&#39;)<br>    plt.xlim(xx.min(), xx.max())<br>    plt.ylim(yy.min(), yy.max())<br>    plt.xlabel(&#39;Feature 1&#39;)<br>    plt.ylabel(&#39;Feature 2&#39;)<br>    plt.title(&quot;SVM Decision Boundary&quot;)<br>    plt.show()<br><br># Call the plotting function<br>plot_decision_boundary(X_test, y_test, svm_model)</pre><p><strong>plot_decision_boundary(X, y, model)</strong>: This function visualizes the decision boundary created by the SVM model and plots the test data points to show how well the model separates them.</p><ul><li><strong>x_min, x_max, </strong><strong>y_min, y_max</strong>: Determine the range of the feature values to define the plotting area.</li><li><strong>np.meshgrid()</strong>: Generates a grid of points (a 2D array) over the feature space. This grid will be used to evaluate the decision boundary.</li><li><strong>np.c_[xx.ravel(), yy.ravel()]</strong>: Combines the x and y coordinates of the grid to form a list of points.</li><li><strong>model.predict()</strong>: Predicts the class for each point on the grid to determine which side of the boundary it falls on.</li><li><strong>plt.contourf()</strong>: Fills the plot with colors corresponding to the predicted class regions, providing a visual representation of the decision boundary.</li><li><strong>plt.scatter()</strong>: Plots the actual data points, color-coded by their true labels (y), to see how well the model classified them.</li><li><strong>plt.show()</strong>: Displays the plot.</li></ul><h4>Key SLT Concepts in Action</h4><ul><li><strong>Hypothesis Space</strong>: In this case, the hypothesis space consists of all possible linear classifiers (since we are using the linear kernel in SVM).</li><li><strong>Overfitting and Underfitting</strong>: The C parameter in the SVC controls the trade-off between margin size and classification error. A smaller C value allows for a wider margin and better generalization (reducing overfitting), while a larger C tries to minimize classification errors on the training data but might overfit.</li><li><strong>VC Dimension</strong>: The capacity of the SVM model to classify data points is related to its VC dimension. The kernel choice and the regularization parameter C influence this capacity.</li><li><strong>Generalization</strong>: The accuracy on the test set provides an estimate of how well the model generalizes to new, unseen data.</li></ul><h3>Applications of Statistical Learning Theory</h3><p>Statistical Learning Theory isn’t just theoretical — it’s instrumental in various real-world applications.</p><h4>Image Recognition</h4><p>In image recognition, algorithms that utilize Statistical Learning Theory principles can effectively classify images by extracting and learning patterns from the data. Techniques such as convolutional neural networks (CNNs) have benefited from theoretical insights into generalization and model complexity.</p><h4>Natural Language Processing (NLP)</h4><p>In NLP, Statistical Learning Theory helps in understanding the statistical properties of text data, enabling models to make accurate predictions in tasks like sentiment analysis, language translation, and information retrieval. For example, models like Transformers leverage these principles to handle complex language tasks.</p><h4>Bioinformatics</h4><p>In bioinformatics, Statistical Learning Theory aids in analyzing high-dimensional data, such as gene expression profiles and protein structures. Techniques like support vector machines and regularized regression are used to uncover patterns in biological data.</p><h4>Finance and Economics</h4><p>Statistical Learning Theory is applied in finance and economics for tasks such as predicting market trends, assessing credit risk, and algorithmic trading. The ability to generalize from historical data to future events is crucial in these domains.</p><h3>Conclusion</h3><p>Statistical Learning Theory is the invisible architect behind many successful machine learning models. By addressing key challenges such as overfitting and underfitting, and providing tools for error estimation and model selection, SLT has paved the way for robust and effective algorithms. As machine learning continues to advance, the principles of SLT will remain central, guiding the development of innovative solutions across diverse fields. Whether it’s improving healthcare outcomes or optimizing financial strategies, SLT ensures that machine learning continues to make a meaningful impact in our world.</p><h4>References</h4><p><strong>[1]</strong> Gerbelot, C., Karagulyan, A., Karp, S., Ravichandran, K., Stern, M., &amp; Srebro, N. (2023, November 26). <em>Applying statistical learning theory to deep learning</em>. arXiv.org. <a href="https://arxiv.org/abs/2311.15404">https://arxiv.org/abs/2311.15404</a><br><strong>[2]</strong><em> The nature of statistical learning theory</em>. (2000). SpringerLink. <a href="https://link.springer.com/book/10.1007/978-1-4757-3264-1">https://link.springer.com/book/10.1007/978-1-4757-3264-1</a><br><strong>[3] </strong>Ulrike, V. L., &amp; Schoelkopf, B. (2008, October 27). <em>Statistical Learning Theory: Models, Concepts, and results</em>. arXiv.org. <a href="https://arxiv.org/abs/0810.4752">https://arxiv.org/abs/0810.4752</a><br><strong>[4]</strong> Xiong, J. (2023, June 30). <em>An introduction to statistical machine learning</em>. <a href="https://www.datacamp.com/tutorial/unveiling-the-magic-of-statistical-machine-learning">https://www.datacamp.com/tutorial/unveiling-the-magic-of-statistical-machine-learning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ade966137c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing a Baseline Machine Learning Model with Project CCHAIN Data: A Case Study Review]]></title>
            <link>https://medium.com/@johnrowenmiano/developing-a-baseline-machine-learning-model-with-project-cchain-data-a-case-study-review-a301e9df2d04?source=rss-9584afb6bb04------2</link>
            <guid isPermaLink="false">https://medium.com/p/a301e9df2d04</guid>
            <dc:creator><![CDATA[John Rowen Miano]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 04:57:42 GMT</pubDate>
            <atom:updated>2024-11-02T03:45:41.775Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML Review: Developing a Baseline Machine Learning Model with Project CCHAIN Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbQWg3LCtKRaIk045TrzdQ.png" /><figcaption>A validated, publicly-accessible linked dataset, <strong>Project CCHAIN</strong> covers 20 years (2003–2022) and includes socioeconomic, environmental, and health-related variables at the barangay (village) level in 12 cities around the Philippines.</figcaption></figure><h4><strong>Introduction</strong></h4><p>Dengue fever is a persistent and life-threatening public health challenge, especially in tropical and subtropical regions. In countries like the Philippines, where mosquito-borne diseases are prevalent, predicting outbreaks is vital to mitigate their impact. Zamboanga City, a bustling urban center in the Philippines, is particularly vulnerable to dengue outbreaks due to its dense population, climatic conditions, and environmental factors.</p><p>According to the Zamboanga City Health Office, the city recorded 2,489 dengue cases in 2022, a significant increase from previous years. This rise in cases has put a strain on local healthcare facilities, prompting the need for more effective outbreak prediction and prevention strategies.</p><p>In one reported case, a barangay in Zamboanga experienced a sudden spike in dengue cases, overwhelming the local health center. The outbreak was attributed to a combination of heavy rainfall and inadequate waste management, leading to an increase in mosquito breeding sites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*dbJbzhYIEdesxGbdYMtV4g.jpeg" /><figcaption>The City Health Office of Zamboanga conducts fogging operations amid rising dengue cases in this March 13, 2022 Facebook post. (<em>Photo courtesy of City Government of Zamboanga Facebook)</em></figcaption></figure><p><strong>Thinking Machines Data Science</strong>, with the support of the Lacuna Fund and Wellcome Trust, assembled an open linked dataset of climate, environmental, socioeconomic, and health variables.</p><p>The Project CCHAIN dataset is a validated, open-sourced linked dataset containing 20 years (2003-2022) of health, climate, environment, and socioeconomic variables at the barangay (village) level across 12 Philippine cities.</p><p>The project team has provided a comprehensive dataset that integrates various factors influencing dengue transmission. Leveraging this rich dataset, they embarked on developing a baseline machine learning model to forecast dengue outbreaks on a weekly basis, aiming to provide public health authorities with a predictive tool for early intervention and effective disease management.</p><h4><strong>Model Objective and Scope</strong></h4><p>The primary objective of their baseline machine learning model is to predict the likelihood of a dengue outbreak in Zamboanga City, utilizing a multi-factorial approach that includes climatic, demographic, healthcare, and economic indicators. This predictive capability is essential for preparing healthcare systems, guiding vector control measures, and informing the public about potential risks.</p><p>The model was trained and tested using a dataset spanning nearly seven years, divided into two distinct periods:</p><ul><li><strong>Training Set:</strong> January 2014 to March 2019 (75 months)</li><li><strong>Testing Set:</strong> April 2019 to December 2020 (20 months)</li></ul><p>This division allows the team to evaluate the model’s performance on unseen data, ensuring its reliability and generalizability.</p><h4><strong>Key Data Inputs and Features</strong></h4><p>To accurately forecast dengue outbreaks, they included a wide range of features in the model:</p><ol><li><strong>Climate Variables:</strong></li></ol><ul><li><strong>Temperature:</strong> Maximum, minimum, and average temperatures were considered, as temperature influences mosquito life cycles and viral replication rates.</li><li><strong>Humidity:</strong> Higher humidity levels are conducive to mosquito breeding and survival.</li><li><strong>Rainfall:</strong> Rainfall creates breeding sites for mosquitoes, making it a critical factor in outbreak prediction.</li><li><strong>Solar Radiation:</strong> Solar radiation can impact mosquito activity and virus transmission.</li><li><strong>Wind Speed:</strong> Wind can influence the dispersal of mosquitoes and affect the spread of the virus.</li><li><strong>Air Quality:</strong> Poor air quality might correlate with respiratory diseases that could mask or exacerbate dengue symptoms, indirectly affecting outbreak detection.</li></ul><p><strong>2. Demographic Data:</strong></p><ul><li><strong>Population Density:</strong> High population density increases human-mosquito contact, heightening the risk of disease transmission.</li><li><strong>Population Growth:</strong> Rapid urbanization and population growth can strain public health infrastructure, affecting outbreak management.</li></ul><p><strong>3. Healthcare Infrastructure:</strong></p><ul><li><strong>Number of Clinics and Hospitals:</strong> Access to healthcare facilities is crucial for early diagnosis and treatment, which can influence outbreak dynamics.</li><li><strong>Sanitation and Water Sources:</strong> Poor sanitation and stagnant water sources are breeding grounds for mosquitoes, increasing outbreak risks.</li></ul><p><strong>4. Economic Activity:</strong></p><ul><li><strong>Nighttime Light Radiance:</strong> This proxy for economic activity and urbanization can indicate areas with high human activity, where dengue transmission might be more likely.</li></ul><h4><strong>Model Development and Methodology</strong></h4><p>The model development process involved several critical steps to ensure accuracy and reliability in predicting dengue outbreaks:</p><p><strong>1. Outbreak Definition:</strong></p><ul><li>A dengue outbreak was defined based on weekly case numbers exceeding a predefined threshold, set at the 75th percentile of total weekly cases during years with significant dengue activity. The model flagged an outbreak when weekly cases surpassed this threshold and continued until cases dropped below it for two consecutive weeks.</li></ul><p>This is implemented in the code as follows:</p><p><strong>Definition 1</strong></p><pre># Create a new column &#39;outbreak&#39; initialized with zeros<br>linked_data[&quot;outbreak&quot;] = 0<br><br># Track weeks satisfying the threshold, and count consecutive outbreak weeks<br>consecutive_weeks_below_threshold = 0<br>previous_outbreak = False<br><br>for index, row in linked_data.iterrows():<br>    if row[&quot;case_total_dengue&quot;] &gt; OUTBREAK_THRESHOLD:<br>        consecutive_weeks_below_threshold = 0<br>        previous_outbreak = True<br>        linked_data.at[index, &quot;outbreak&quot;] = 1<br>    else:<br>        # check if previous week was an outbreak<br>        # if yes, continue to tag current week as outbreak<br>        # part of observation period<br>        if previous_outbreak and consecutive_weeks_below_threshold &lt; 2:<br>            linked_data.at[index, &quot;outbreak&quot;] = 1<br>            consecutive_weeks_below_threshold += 1<br>        elif consecutive_weeks_below_threshold == 2:<br>            linked_data.at[index, &quot;outbreak&quot;] = 0<br>            previous_outbreak = False<br>        else:<br>            linked_data.at[index, &quot;outbreak&quot;] = 0<br></pre><p><strong>2. Incorporating Lagged Features:</strong></p><ul><li>To capture the temporal patterns leading up to an outbreak, the team introduced lagged features, specifically the number of dengue cases from 1–4 weeks prior to the current week. This approach helps the model identify trends and make more informed predictions.</li></ul><p>This is implemented in the code as follows:</p><pre># Uncomment lines if you want to explore the other lags<br>lagged_linked_data = linked_data.assign(<br>    # prev_1_wk_numcases=linked_data[&quot;case_total_dengue&quot;].shift(<br>    #     1, fill_value=0<br>    # ),  # cases a week before<br>    #prev_2_wk_numcases=linked_data[&quot;case_total_dengue&quot;].shift(<br>    #    2, fill_value=0<br>    #),  # cases 2 weeks before<br>    prev_3_wk_numcases=linked_data[&quot;case_total_dengue&quot;].shift(<br>         3, fill_value=0<br>    ),  # cases 3 weeks before<br>    prev_1_mo_numcases=linked_data[&quot;case_total_dengue&quot;].shift(<br>        4, fill_value=0<br>    ),  # cases 1 month before<br>)<br><br>print(lagged_linked_data.shape)<br>lagged_linked_data.head()<br></pre><p><strong>3. Model Training with TimeSeriesSplit:</strong></p><ul><li>Given the time-series nature of their data, they employed the <strong>TimeSeriesSplit</strong> function from scikit-learn for cross-validation. This method maintains the temporal order of the data, ensuring that the model is validated in a manner consistent with real-world scenarios.</li></ul><pre># Illustrate time series split.<br># You may experiment the splits by changing the `n_splits` parameter.<br># Increasing the `n_splits` would give a narrower time period for the test set.<br>tss = TimeSeriesSplit(n_splits=5)<br>for i, (split_train_index, split_test_index) in enumerate(tss.split(X_train)):<br>    print(f&#39;Split {i}:&#39;)<br>    split_X_train, split_X_test = X_train.iloc[split_train_index, :], X_train.iloc[split_test_index, :]<br>    split_y_train, split_y_test = y_train.iloc[split_test_index], y_train.iloc[split_test_index]<br>    print(split_X_train.index.min(), split_X_train.index.max())<br>    print(split_y_train.index.min(), split_y_train.index.max())<br></pre><p><strong>4. Random Forest Classifier:</strong></p><ul><li>The team selected the Random Forest (RF) classifier as the baseline model due to its robustness in handling large datasets and its ability to manage complex interactions between features. Hyperparameter tuning was conducted using GridSearchCV, exploring various combinations to optimize the model’s performance.</li></ul><pre># Define parameter space to optimize<br>param_grid = {<br>    &quot;n_estimators&quot;: [50, 100, 200, 300, 500],<br>    &quot;max_depth&quot;: [None, 5, 10, 15, 20],<br>}<br></pre><h4><strong>Results and Performance Metrics</strong></h4><p>The final model demonstrated strong predictive capabilities, achieving the following accuracy rates:</p><ul><li><strong>Training Set:</strong> 84.89% accuracy in predicting outbreak labels.</li><li><strong>Testing Set:</strong> 95.65% accuracy in predicting outbreak labels.</li></ul><pre># Show results of model training<br>print(f&quot;Best hyperparameters: {model_grid_search.best_params_}&quot;)<br>print(f&quot;Train best score: {model_grid_search.best_score_:0.4}&quot;)<br>print(<br>    f&quot;Train best score std: {np.std(model_grid_search.cv_results_[&#39;mean_test_score&#39;]):0.4}&quot;<br>)<br></pre><pre># Show results<br><br># Evaluate the model on test data<br>best_rf_classifier_model = model_grid_search.best_estimator_<br>test_accuracy = best_rf_classifier_model.score(X_test, y_test)<br>print(&quot;Test Accuracy:&quot;, test_accuracy)<br></pre><pre>report = classification_report(y_test, y_pred, output_dict=True)<br>report_df = pd.DataFrame(report).transpose()<br>report_df<br></pre><p>However, the model’s performance varied when distinguishing between outbreak (outbreak=1) and non-outbreak (outbreak=0) weeks. While the overall accuracy was high, the precision and recall for actual outbreak weeks were slightly lower. This indicates a need for further refinement, particularly in improving the model’s sensitivity to the initial stages of an outbreak, which is critical for timely public health responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Ep3E6FDOg1pEDeh9h1Gp7A.png" /><figcaption>Based on actual data, there is only one outbreak period for the target timespan, a 30-week event from 2019-04-22 to 2019-11-11. The model predicted a 26-week outbreak period from 2019-05-20 to 2019-11-11, which was detected 4 weeks after actual, and ended on the same week.<br><br>While most of the outbreak period was covered, the model still needs to be trained to be more sensitive to the start of the outbreak, which is crucial for early intervention. (Chart from Thinking Machines Data Science)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*wkEvGXxBmwtoMNtFNdhU8g.png" /><figcaption>The model was able to determine outbreaks for the consectuve weeks in 2019-05-20 to 2019-11-11, when actual data records 75-380 weekly cases.<br><br>For the rest of 2020, it was also able to correctly identify that there should be no outbreaks during that year. (Chart from Thinking Machines Data Science)</figcaption></figure><h4><strong>Feature Importance Analysis</strong></h4><p>To understand the factors driving the model’s predictions, the team used SHapley Additive exPlanations (SHAP) to analyze feature importance. The analysis revealed that:</p><ul><li><strong>Lagged Dengue Cases:</strong> Previous weeks’ dengue case numbers were the most significant predictors, highlighting the importance of historical trends in forecasting outbreaks.</li><li><strong>Climate Variables:</strong> Maximum and average temperatures emerged as key factors, consistent with the known impact of temperature on mosquito behavior and viral replication.</li><li><strong>Population Metrics:</strong> The mean population count also played a significant role, reflecting the influence of human density on disease transmission dynamics.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*bgkc3cRqWty_OpEafymbIw.png" /><figcaption>From the results of SHAP, the features that drove the predictions are the cases from the previous weeks, the climate variables for temperature tmax and tave, and the mean population count. (Chart from Thinking Machines Data Science)</figcaption></figure><h4><strong>Real-World Application and Case Study</strong></h4><p>To evaluate the model’s practical utility, the team tested it against actual outbreak data from Zamboanga City. The model successfully identified a major outbreak period from May 20, 2019, to November 11, 2019. Although the model detected the outbreak four weeks later than desired, it closely aligned with the actual outbreak timeline, demonstrating its potential as a forecasting tool. Moreover, the model accurately predicted the absence of outbreaks throughout 2020, further validating its reliability.</p><h4><strong>Challenges and Future Directions</strong></h4><p>While the baseline model shows promise, several challenges remain:</p><ul><li><strong>Early Outbreak Detection:</strong> Improving the model’s ability to detect the early stages of an outbreak is essential for timely interventions. Future work will focus on enhancing the model’s sensitivity to subtle changes in key indicators.</li><li><strong>Incorporating Additional Data Sources:</strong> Integrating more granular data, such as mosquito population dynamics and detailed environmental conditions, could further improve the model’s accuracy.</li><li><strong>Model Generalization:</strong> Testing the model in different geographic regions with varying climatic and socio-economic conditions will help assess its generalizability and robustness.</li></ul><h4><strong>Conclusion</strong></h4><p>This baseline machine learning model represents a significant step forward in predicting dengue outbreaks using a multi-factorial approach. By integrating climate, demographic, healthcare, and economic data, the model provides a comprehensive tool for public health officials to anticipate and respond to dengue outbreaks more effectively.</p><p>The successful application of this model underscores the potential of machine learning in public health, offering a blueprint for future innovations in disease outbreak prediction. The model and its underlying code are available under the Apache 2.0 license, encouraging collaboration and continuous improvement by researchers and public health practitioners worldwide.</p><p>As they continue to refine this model, the goal of Thinking Machines Data Science is to create a more accurate and responsive tool that can be deployed in real-time, empowering communities to take proactive measures against dengue and other vector-borne diseases.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Explore the Demo here:</strong></p><p><a href="https://drive.google.com/file/d/1y1kP8QlV3BJVz4tYwUcK8Hs7GrV8JAJo/view?usp=drivesdk">Outbreak Prediction Model Demo</a></p><p><strong>Access the data here:</strong><br><a href="https://drive.google.com/drive/folders/1NF_e3YM0dVBSxlVBWRxGQXwkl59sp5Jf">Google Drive</a> <br><a href="https://www.kaggle.com/datasets/thinkdatasci/project-cchain/">Kaggle</a><br><a href="https://data.humdata.org/m/dataset/project-cchain?">HDX</a></p><p><strong>See full data documentation </strong><a href="https://dbdocs.io/lacuna-fund-project-team/Project-CCHAIN"><strong>here</strong></a><strong> and documentation reports from their partners </strong><a href="https://drive.google.com/drive/folders/1cATESCXBHDRyTDZT8s--UAEp7zcQ6jqV"><strong>here</strong></a><strong>.</strong></p><p><strong>Cite the data as:</strong><br>Thinking Machines Data Science (2024). Project CCHAIN Dataset: Open validated health, climate, environment, and socioeconomic data in 12 Philippine cities. Kaggle. https://doi.org/10.34740/kaggle/ds/4918229</p><p><strong>Follow Thinking Machines Data Science on all of their social media platforms:</strong></p><p><a href="http://thinkingmachin.es/">Website</a></p><p><a href="https://www.facebook.com/thinkdatasci?mibextid=ZbWKwL">Facebook</a></p><p><a href="https://www.linkedin.com/company/thinkdatasci/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a301e9df2d04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Scientist as a Filipino Patriot: Insights from the DOST-SEI Scholars Leadership Camp ’24]]></title>
            <link>https://medium.com/@johnrowenmiano/the-scientist-as-a-filipino-patriot-insights-from-the-dost-sei-scholars-leadership-camp-24-86e3c130ae76?source=rss-9584afb6bb04------2</link>
            <guid isPermaLink="false">https://medium.com/p/86e3c130ae76</guid>
            <category><![CDATA[scholar]]></category>
            <category><![CDATA[scientist]]></category>
            <category><![CDATA[dost-sei]]></category>
            <category><![CDATA[filipino-patriot]]></category>
            <category><![CDATA[xiao-chua]]></category>
            <dc:creator><![CDATA[John Rowen Miano]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 07:11:10 GMT</pubDate>
            <atom:updated>2024-08-11T06:38:10.379Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>The work of science is the work of making people free. The whole point is to give ‘kaginhawaan’ to our people.</strong></blockquote><p>— Dr. Michael Charleston ‘Xiao’ Chua</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JnKp9ViZ1S4wtn8Lhi5RFw.jpeg" /><figcaption>Photo Card from DOST SEI The Filipino Patriot Scholars Program Facebook Page <a href="https://www.facebook.com/FilipinoPatriotProgram">https://www.facebook.com/FilipinoPatriotProgram</a></figcaption></figure><p>In the story of the Filipino struggle for identity and self-sovereignty, emerges a scientist who becomes much more than being just a purveyor for knowledge, he becomes a shining beacon of patriotism. Immersed in rich traditions and historical lore of the Philippines, it is this figure who bears witness to the synthesis of intellect and national pride as an immortal statement on the soul of the Filipino.</p><p>The road to becoming a scientist is usually jump-started by the opportunity provided by the Department of Science and Technology in the Philippines. The scholarship program of DOST-SEI nurtures young minds, equipping them with tools necessary to make innovators, leaders, and patriots out of them. Much as anything else, scholars are the special brew of intellectual firepower and national pride, capable of contributing to national development while being faithful to the rich cultural and historical tapestry that is the Filipino identity.</p><p>Our story starts with the concept of the <strong>bayan</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*IBXlrTKvLF7od3M2Qv3YDA.png" /><figcaption>“Bayanihan” by Carlos “Botong” V. Francisco</figcaption></figure><p>The concept of <strong>bayan</strong> — community and nation — lies at the core of DOST scholars. These students, having been recipients of the DOST scholarship, do not think of education as an act of triumph but as a commitment to their bayan. As beneficiaries of the DOST scholarship, these students understand that their education is not merely a personal achievement but a commitment to their bayan. This mirrors the historical <strong>sandugo</strong>, a blood compact symbolizing unity and shared destiny among the Filipino people. DOST scholars, in their quest for knowledge, echo the unity and collective spirit that has long defined the Philippines.</p><p>In ancient times, the <strong>datu</strong> and <strong>bagani</strong> were revered as leaders and warriors who protected their communities. Modern DOST scholars, like the <strong>panday</strong> of old — masters of their craft — forge new paths in science and technology, acting as guardians of the nation’s intellectual future. Their role is somewhat comparable to the <strong>babaylan</strong>, who integrated knowledge and spirituality as a healer and guide for her people. In a similar vein, modern-day scholars integrate <strong>art and science</strong> in the realization that complex problems on the national and global level can only be solved through holistic and interdisciplinary approaches.</p><p>The traditional <strong>balatik</strong> constellation, used for navigation and agricultural planning, exemplifies the integration of scientific knowledge with cultural heritage. DOST scholars, much like the navigators of old, utilize their scientific expertise to guide the nation toward progress and sustainability. This deep connection to cultural roots is also seen in traditional practices like the <strong>bubu</strong> (fish trap), representing the resourcefulness and ingenuity that these scholars bring to contemporary challenges, from environmental conservation to technological innovation.</p><p>The <strong>Manunggul Jar</strong> is symbolic of heritage and continuity of the role played by scholars in making sure that bridges between the past and the future are connected. As custodians of scientific knowledge, DOST scholars ensure that the body of research and innovations they do pay tribute to their forefathers while at the same time opening up the road for the next generations.</p><p>The simplicity and sustainability of the <strong>bahay-kubo</strong> resonate with the principles that DOST scholars advocate for in their work. They strive for sustainable development and environmental stewardship, much like the bahay kubo reflects living in harmony with nature.</p><p>DOST scholars embody the spirit of the <strong>bagani</strong> as <strong>bayani</strong> — warriors and heroes of their time. Their intellectual and scientific endeavors are a testament to their commitment to national development and progress. The skills and expertise they develop, akin to the ancient <strong>batek</strong> and <strong>batekan</strong> (skilled craftsmen), showcase their mastery and contribute to national pride and resilience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*nw-tyGq626ymsfXjw0Gxfw.jpeg" /><figcaption>An illustration of Visayan Pintados (batekan) from the Boxer Codex.</figcaption></figure><p>Guided by a <strong>matuwid na kaluluwa</strong> (righteous soul), DOST scholars aim for <strong>kaginhawaan</strong> (well-being) and <strong>kalayaan</strong> (freedom) in their pursuits. Their work is grounded in the ethical and moral responsibility to uplift their communities and foster inclusive growth.</p><p>The integration of <strong>liberal arts</strong> in their education promotes a well-rounded perspective, encouraging DOST scholars to consider the broader social implications of their scientific work. This approach aligns with the <strong>social contract</strong>, emphasizing their role in contributing to the common good and reflecting the Filipino value of community responsibility.</p><p>On a final note, DOST scholars exemplify the ideal of the scientist as a Filipino patriot. Their journey is rooted in the values of <strong>bayan</strong>, <strong>sandugo</strong>, <strong>datu</strong>, <strong>bagani</strong>, <strong>babaylan</strong>, <strong>balatik</strong>, <strong>bubu</strong>, and cultural symbols like the <strong>Manunggul Jar</strong> and <strong>bahay kubo</strong>. These scholars, guided by principles of <strong>matuwid na kaluluwa</strong>, <strong>kaginhawaan</strong>, and <strong>kalayaan</strong>, demonstrate the critical role of arts and sciences, liberal arts, and the social contract in building a progressive, inclusive, and resilient Philippines. Their contributions not only advance the nation’s scientific and technological frontiers but also uphold and enrich the cultural and historical legacy of the Filipino people.</p><p>This is the Filipino Story. We are DOST-SEI Scholars. We are the new Baganis.</p><p><strong>Iskolar ng Bayan, Lagi’t-lagi para sa Bayan!</strong></p><p><em>If you want to listen more about the history of the Scientist as a Filipino Patriot, follow Dr. Xiao on his social media accounts:</em></p><p><em>Facebook: </em><a href="https://www.facebook.com/sirxiaochua/"><em>https://www.facebook.com/sirxiaochua/</em></a><em><br>Instagram: </em><a href="https://www.instagram.com/xiao.chua/?hl=en"><em>https://www.instagram.com/xiao.chua/</em></a><em><br>Twitter: </em><a href="https://x.com/Xiao_Chua?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor"><em>https://x.com/Xiao_Chua</em></a><em>/</em></p><p><em>Want to know more about The Filipino Story? Subscribe to this YouTube Channel:<br></em><a href="https://www.youtube.com/@thefilipinostorystudio"><em>https://www.youtube.com/@thefilipinostorystudio</em></a></p><p><em>Learn more about the Filipino Patriot Scholars Program:<br></em><a href="https://www.facebook.com/FilipinoPatriotProgram"><em>https://www.facebook.com/FilipinoPatriotProgram</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86e3c130ae76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML4EO: Machine Learning Approach in Earth Engine]]></title>
            <link>https://medium.com/@johnrowenmiano/ml4eo-machine-learning-approach-in-earth-engine-9392f6ca0736?source=rss-9584afb6bb04------2</link>
            <guid isPermaLink="false">https://medium.com/p/9392f6ca0736</guid>
            <dc:creator><![CDATA[John Rowen Miano]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 17:07:32 GMT</pubDate>
            <atom:updated>2024-07-25T17:07:32.758Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In recent years, the integration of machine learning with geospatial analysis has opened new horizons for understanding and managing our planet’s resources. <a href="https://earthengine.google.com/">Google Earth Engine (GEE)</a> stands at the forefront of this innovation, providing a powerful platform for planetary-scale analysis. This article explores how to leverage built-in classifiers in GEE for various geospatial applications, providing a comprehensive guide for researchers and practitioners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGYaCyUBFWSW_U9toBA-WQ.png" /><figcaption>Google Earth Engine at <a href="https://earthengine.google.com/">https://earthengine.google.com/</a></figcaption></figure><p><strong>What is Google Earth Engine?</strong></p><p>Google Earth Engine is a cloud-based platform for planetary-scale environmental data analysis. It combines a multi-petabyte catalog of satellite imagery and geospatial datasets with powerful analysis capabilities, allowing users to process vast amounts of data with ease. GEE supports a range of applications from land cover mapping to disaster response, making it an invaluable tool for the geospatial community.</p><p><strong>Machine Learning in GEE</strong></p><p>Machine learning (ML) is a subset of artificial intelligence that enables systems to learn from data and improve their performance over time without being explicitly programmed. In geospatial analysis, ML can be used for tasks such as classification, regression, and clustering. Classifiers, a type of ML algorithm, are particularly useful for categorizing data into predefined classes based on input features.</p><p><strong>Built-in Classifiers in GEE</strong></p><p>Earth Engine provides several built-in classifiers, each with unique strengths and applications. The main classifiers available are:</p><ul><li>Decision Trees: Simple and interpretable models that split data into subsets based on feature values.</li><li>Random Forest: An ensemble method that builds multiple decision trees and combines their outputs for improved accuracy.</li><li>Support Vector Machines (SVM): Powerful models that find the optimal boundary separating different classes.</li><li>Naive Bayes: Probabilistic classifiers based on Bayes’ theorem, assuming feature independence.</li><li>k-Nearest Neighbors (k-NN): A simple, instance-based method that classifies data points based on the majority class of their nearest neighbors.</li></ul><p><strong>Workflow for Using Built-in Classifiers</strong></p><ol><li><em>Data Preparation and Preprocessing</em></li></ol><p>The first step in any ML workflow is preparing and preprocessing the data. This involves selecting relevant features, handling missing values, and normalizing the data if necessary.</p><p><em>2. Selection of Training Data</em></p><p>Training data is crucial for building a reliable model. In GEE, users can create training datasets by manually labeling samples or using existing labeled data. The quality and quantity of the training data significantly impact the model’s performance.</p><p><em>3. Training the Model</em></p><p>Once the training data is ready, the chosen classifier can be trained. GEE’s API provides functions to fit the model to the data, allowing users to specify parameters and control the training process.</p><p><em>4. Applying the Classifier</em></p><p>After training, the classifier can be applied to new, unlabeled data to make predictions. This step involves using the model to classify each pixel in an image based on its features.</p><p><em>5. Evaluating the Results</em></p><p>Model evaluation is essential to assess the classifier’s performance. Metrics such as accuracy, precision, recall, and the confusion matrix provide insights into the model’s strengths and weaknesses.</p><p>In order to apply our knowledge of Google Earth Engine and machine learning, let’s explore 2 case studies below.</p><h4>Case Study 1: Supervised Classification with Landsat 9 Images using Random Forest</h4><p>This part will show you how to apply supervised classification with Landsat 9 Images — a machine-learning approach in Google Earth Engine. (<em>Warning: This is my take on applying ML on GEE so there may be some errors, but I will gladly accept constructive criticisms regarding the analysis.</em>)</p><p><a href="https://landsat.gsfc.nasa.gov/satellites/landsat-9/"><strong>Landsat 9</strong></a> was launched on September 27, 2021, and it carries two instruments: the <strong>Operational Land Imager 2 (OLI-2)</strong> and the <strong>Thermal Infrared Sensor 2 (TIRS-2)</strong>. OLI-2 has nine bands covering the visible, near-infrared, and shortwave infrared wavelengths, with a spatial resolution of 30 meters, except for the panchromatic band, which has a 15-meter resolution. TIRS-2 has two bands with a 100-meter spatial resolution.</p><p>We’ll be using the GEE cloud computing platform for this task. If you are new to Earth Engine, you can <a href="https://courses.spatialthoughts.com/gee-sign-up.html">sign up for an account</a> on their website. Google provides this service for educational, training, or non-profit research purposes, and approvals usually take 24 to 48 hours.</p><p>In GEE, you can access a variety of datasets including Landsat, Sentinel, MODIS, and many more. For our purposes, we will be using the <a href="https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2"><strong>Landsat 9 surface reflectance dataset</strong></a><strong> (</strong>LANDSAT/LC09/C02/T1_L2). To do this, go to the <a href="https://code.earthengine.google.com/"><strong>GEE code editor</strong></a>, where you can write and execute your JavaScript code, and visualize results on the map canvas.</p><p>Here’s a step-by-step overview of the script:</p><h4>Load Landsat 9 Data</h4><pre>// Load Landsat 9 data<br>var dataset = ee.ImageCollection (&#39;LANDSAT/LC09/C02/T1_L2&#39;)<br>.filterDate(&#39;2022-01-01&#39;, &#39;2022-05-30&#39;)<br>.filterBounds(roi)<br>.filterMetadata(&#39;CLOUD_COVER&#39;, &#39;less_than&#39;, 14);<br><br>// Applies scaling factors.<br>function applyScaleFactors (image) {<br>var opticalBands = image.select(&#39;SR_B.&#39;).multiply (0.0000275).add(-0.2);<br>var thermalBands = image.select(&#39;ST_B.*&#39;).multiply (0.00341802).add(149.0); <br>return image.addBands(opticalBands, null, true)<br>            .addBands(thermalBands, null, true);<br>}<br><br>var rescale = dataset.map(applyScaleFactors); <br>var image = rescale.median();<br><br>var visualization = {<br>  bands: [&#39;SR_B4&#39;, &#39;SR_B3&#39;, &#39;SR_B2&#39;],<br>  min: 0.0,<br>  max: 0.3,<br>};<br>Map.addLayer(image.clip(roi), visualization, &#39;Landsat 9&#39;);<br>Map.centerObject(roi, 11);</pre><p>This block loads Landsat 9 satellite data within the specified date range (2022-01-01 to 2022-05-30) and area of interest (roi). It filters images with less than 14% cloud cover.</p><ul><li><strong>Scaling Factors</strong>: A function applyScaleFactors is defined to apply scaling factors to optical and thermal bands to convert them to top-of-atmosphere reflectance.</li><li><strong>Rescale and Composite</strong>: The applyScaleFactors function is applied to each image in the collection. The median composite of the rescaled images is then computed.</li><li><strong>Visualization</strong>: Defines visualization parameters for a true-color composite and adds the composite image to the map, clipping it to the region of interest (roi).</li></ul><p><strong>Purpose</strong>: To load, preprocess, and visualize Landsat 9 data for the specified region and time period.</p><p>After I loaded the Landsat 9 data, I created the training data using geometry imports. I manually picked the points (data) on the map myself, identifying five land cover classes such as Water, Urban, Crop, Forest, and Barren. Each of the classes have exactly 100 data points each. I changed the data into a feature collection and added properties like assign Water as Class 0, Urban as Class 1, and so on. I also assigned each of the classes different colors.</p><h4>Create Training Data</h4><pre>// Create Training Data<br>var training = Barren.merge(Forest).merge(Water).merge(Urban).merge(Crop); <br>// print (training);<br>// Export Training Data<br>// Export.table.toAsset(training);<br><br>var label = &#39;Class&#39;;<br>var bands = [&#39;SR_B1&#39;, &#39;SR_B2&#39;, &#39;SR_B3&#39;, &#39;SR_B4&#39;, &#39;SR_B5&#39;, &#39;SR_B7&#39;];<br>var input = image.select(bands);<br><br>// Overlay the points on the imagery to get training.<br>var trainImage = input.sampleRegions({<br>  collection: training,<br>  properties: [label],<br>  scale: 30<br>});   <br>//print(trainImage);<br><br>var trainingData = trainImage.randomColumn();<br>var trainSet = trainingData.filter(ee.Filter.lessThan(&#39;random&#39;, 0.8));<br>var testSet = trainingData.filter(ee.Filter.greaterThanOrEquals(&#39;random&#39;, 0.8));</pre><p>This block prepares the training dataset for the classifier.</p><ul><li><strong>Merging Classes</strong>: Merges different land cover classes (Barren, Forest, Water, Urban, Crop) into a single feature collection named training.</li><li><strong>Label and Bands</strong>: Specifies the label (Class) and the spectral bands to be used for classification.</li><li><strong>Sample Regions</strong>: Samples the input image at the locations of the training points to create the training dataset.</li><li><strong>Random Column</strong>: Adds a random value column to the training dataset to split it into training (80%) and testing (20%) sets.</li></ul><p><strong>Purpose</strong>: To prepare the data needed to train and validate the Random Forest classifier.</p><h4>Classification Model</h4><pre>// Classification Model<br>// Make a Random Forest classifier and train it.<br><br>var classifier = ee.Classifier.smileRandomForest(10)<br>    .train({<br>      features: trainSet,<br>      classProperty: label,<br>      inputProperties: bands<br>    });<br>    <br>// Classifiy the image<br>var classified = input.classify(classifier);<br>// print(classified.getInfo());<br><br><br>/// Define a palette for the classification.<br>var landcoverPalette = [<br>  &#39;#0c2c84&#39;, //water (0)<br>  &#39;#e31a1c&#39;, //urban (1)<br>  &#39;#005a32&#39;, //forest (2)<br>  &#39;FF8000&#39;, //crop (3)<br>  &#39;969696&#39;, //barren (4)<br>];<br>Map.addLayer(classified.clip(roi), {palette: landcoverPalette, min: 0, max: 4 }, &#39;classification&#39;);</pre><p>This block trains and applies the Random Forest classifier.</p><ul><li><strong>Classifier Training</strong>: Initializes a Random Forest classifier with 10 trees and trains it using the training set.</li><li><strong>Image Classification</strong>: Applies the trained classifier to the input image to produce a classified image.</li><li><strong>Palette</strong>: Defines a color palette for visualizing the different land cover classes and adds the classified image to the map.</li></ul><p><strong>Purpose</strong>: To perform land cover classification using the Random Forest algorithm and visualize the results.</p><h4>Accuracy Assessment</h4><pre>// Accuracy Assessment<br>// Classify the testingSet and get a Confusion Matrix<br>var confusionMatrix = ee.ConfusionMatrix(testSet.classify(classifier)<br>    .errorMatrix({<br>      actual: &#39;Class&#39;,<br>      predicted: &#39;classification&#39;<br>    }));<br><br>print(&#39;Confusion matrix:&#39;, confusionMatrix);<br>print(&#39;Overall Accuracy:&#39;, confusionMatrix.accuracy());<br>print(&#39;Producers Accuracy:&#39;, confusionMatrix.producersAccuracy());<br>print(&#39;Consumers Accuracy:&#39;, confusionMatrix.consumersAccuracy());</pre><p>This block assesses the accuracy of the classifier.</p><ul><li><strong>Confusion Matrix</strong>: Classifies the test set and computes the confusion matrix to compare the actual and predicted classifications.</li><li><strong>Accuracy Metrics</strong>: Calculates and prints overall accuracy, producer’s accuracy, and consumer’s accuracy based on the confusion matrix.</li></ul><p><strong>Purpose</strong>: To evaluate the performance of the classifier and understand its accuracy in classifying the different land cover types.</p><h4>Export Classified Map</h4><pre>// Export classified map to Google Drive<br>Export.image.toDrive({<br>  image: classified,<br>  description: &#39;Landsat_Classified_RF&#39;,<br>  scale: 30,<br>  region: roi,<br>  maxPixels: 1e13,<br>});</pre><p>This block exports the classified image to Google Drive.</p><ul><li><strong>Export Parameters</strong>: Specifies the image to be exported, description, scale (30 meters), region of interest, and maximum number of pixels.</li></ul><p><strong>Purpose</strong>: To save the classified map for further use or analysis outside of Google Earth Engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGuwWxyPeSltSz1tvkuHCQ.png" /><figcaption>Landsat 9 Image Visualization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XbMMJuvD7_TMvVRoylhZA.png" /><figcaption>Classification Image Result from Random Forest</figcaption></figure><p>We’ve had enough of the codes, though, so let’s move on to the metrics to see how accurate our model is.</p><h4>Confusion Matrix</h4><p>The confusion matrix is a table used to describe the performance of a classification model. Each row of the matrix represents the instances in a true class, while each column represents the instances in a predicted class.</p><pre>      Predicted<br>         0  1  2  3  4<br>     0 [24, 0, 0, 0, 0]<br>     1 [ 0,14, 2, 2, 3]<br>True 2 [ 0, 0,16, 2, 0]<br>     3 [ 0, 0, 0,19, 2]<br>     4 [ 0, 4, 0, 0,17]</pre><ul><li><strong>Class 0 (Water)</strong>: 24 instances are correctly classified as water.</li><li><strong>Class 1 (Urban)</strong>: 14 instances correctly classified as urban, 2 misclassified as class 2 (Forest), 2 as class 3 (Crop), and 3 as class 4 (Barren).</li><li><strong>Class 2 (Forest)</strong>: 16 instances correctly classified as forest, 2 misclassified as class 3 (Crop).</li><li><strong>Class 3 (Crop)</strong>: 19 instances correctly classified as crop, 2 misclassified as class 4 (Barren).</li><li><strong>Class 4 (Barren)</strong>: 17 instances correctly classified as barren, 4 misclassified as class 1 (Urban).</li></ul><h4>Overall Accuracy</h4><ul><li><strong>Overall Accuracy</strong>: 0.857 (85.71%)</li><li>This is the ratio of correctly predicted instances (sum of the diagonal elements) to the total instances.</li></ul><h4>Producer’s Accuracy (Sensitivity/Recall)</h4><ul><li><strong>Producer’s Accuracy</strong> measures the classifier’s ability to correctly classify a given class.</li><li>Class 0: 1 (100%)</li><li>Class 1: 0.667 (66.67%)</li><li>Class 2: 0.889 (88.89%)</li><li>Class 3: 0.905 (90.48%)</li><li>Class 4: 0.810 (80.95%)</li></ul><p><strong>Producer’s Accuracy</strong>:</p><ul><li>High for Class 0 (Water), Class 2 (Forest), and Class 3 (Crop).</li><li>Relatively low for Class 1 (Urban) and Class 4 (Barren) indicating more confusion in classifying these classes.</li></ul><h4>Consumer’s Accuracy (Precision)</h4><ul><li><strong>Consumer’s Accuracy</strong> (not fully listed in the output but can be derived from the confusion matrix):</li><li>Class 0: 1 (100%)</li><li>Class 1: 0.583 (58.33%)</li><li>Class 2: 0.889 (88.89%)</li><li>Class 3: 0.826 (82.61%)</li><li>Class 4: 0.850 (85.00%)</li></ul><p><strong>Consumer’s Accuracy</strong>:</p><ul><li>High for Class 0 (Water) and Class 2 (Forest), indicating fewer false positives for these classes.</li><li>Lower for Class 1 (Urban) indicating more misclassifications where other classes are predicted as Urban.</li></ul><h4>Interpretation</h4><p><strong>High Overall Accuracy</strong>: The classifier performs well overall, with an accuracy of about 86%.</p><p><strong>Class-Specific Performance</strong>:</p><ul><li>Excellent for Class 0 (Water) with both producer’s and consumer’s accuracy at 100%.</li><li>Moderate performance for Class 1 (Urban) with lower accuracy metrics, suggesting the classifier has difficulty distinguishing urban areas from other classes, especially barren areas.</li></ul><h4><strong>Case Study 2: </strong><a href="https://eo4landscape.natur.cuni.cz/new-article-on-automatic-forest-cover-classification-using-sentinel-2-data-in-google-earth-engine/"><strong>Automatic Forest Cover Classification Using Sentinel-2 Multispectral Satellite Data and Machine Learning Algorithms in Google Earth Engine</strong></a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuisAb0ZnQOX4YzGfr2ulw.png" /><figcaption>Photo from: Onačillová, Katarína &amp; Krištofová, Veronika &amp; Paluba, Daniel. (2023). Automatic Forest Cover Classification Using Sentinel-2 Multispectral Satellite Data and Machine Learning Algorithms in Google Earth Engine. 67. 163–185.</figcaption></figure><p>This case has a much more advanced use of ML on Earth Engine so I’ll give you the task of reading the full article, titled “<a href="https://www.researchgate.net/publication/376894798_Automatic_Forest_Cover_Classification_Using_Sentinel-2_Multispectral_Satellite_Data_and_Machine_Learning_Algorithms_in_Google_Earth_Engine">Automatic Forest Cover Classification Using Sentinel-2 Multispectral Satellite Data and Machine Learning Algorithms in Google Earth Engine</a>” in the Acta Geographica Universitatis Comenianae journal. But, anyway, here are its findings:</p><p>[1] Random Forest performed better than Support Vector Machine, achieving an impressive <em>95% overall accuracy</em> in both test years (2017 and 2020), accompanied by an F1-score as high as 0.95.</p><p>[2] During the period from 2017 to 2019, the <em>forest cover</em> in Slovakia <em>notably increased</em>, followed by a <em>slight decline</em> observed between <em>2019 and 2020</em>.</p><p>[3] Satellite data analysis revealed that the <em>current forest cover is lower</em> than what official statistics indicate.</p><p>[4] An <em>automated tool for classifying forest cover</em> has been successfully developed for Slovakia spanning the years <em>2017 to 2022</em>.</p><p>The code was made open-access by the authors. It is available on GitHub for everyone interested in applying it to other areas and dates, testing, or further development: <br><a href="https://github.com/palubad/Automatic-Forest-Classification-GEE">https://github.com/palubad/Automatic-Forest-Classification-GEE</a></p><p><strong>Applications and Use Cases</strong></p><p>Machine learning classifiers in GEE have been successfully applied in various fields, including:</p><ul><li>Land Cover Mapping: Identifying and monitoring different land cover types, such as forests, urban areas, and water bodies.</li><li>Change Detection: Detecting changes in land use and land cover over time.</li><li>Vegetation Monitoring: Assessing vegetation health and productivity using spectral indices.</li><li>Urban Planning: Analyzing urban growth and land use patterns for sustainable development.</li></ul><p><strong>Best Practices and Tips</strong></p><ul><li>Select Appropriate Features: Carefully choose features that are relevant to the classification task.</li><li>Use Sufficient Training Data: Ensure that the training dataset is large and representative of all classes.</li><li>Evaluate Model Performance: Regularly evaluate and refine the model to improve accuracy.</li><li>Consider Ensemble Methods: Combining multiple classifiers can enhance performance and robustness.</li></ul><p><strong>Conclusion</strong></p><p>Machine learning in Google Earth Engine offers powerful tools for geospatial analysis, enabling users to derive valuable insights from satellite imagery and other geospatial data. By leveraging built-in classifiers, researchers and practitioners can efficiently perform complex classification tasks, contributing to a better understanding of our planet.</p><p><strong>References</strong></p><p>[1] <em>Google Earth Engine</em>. (n.d.). <a href="https://earthengine.google.com/">https://earthengine.google.com/</a></p><p>[2] Landsat NASA. (2022, March 24). <em>LandsAt 9 | Landsat Science</em>. Landsat Science | a Joint NASA/USGS Earth Observation Program. <a href="https://landsat.gsfc.nasa.gov/satellites/landsat-9/">https://landsat.gsfc.nasa.gov/satellites/landsat-9/</a></p><p>[3] Onačillová, Katarína &amp; Krištofová, Veronika &amp; Paluba, Daniel. (2023). Automatic Forest Cover Classification Using Sentinel-2 Multispectral Satellite Data and Machine Learning Algorithms in Google Earth Engine. 67. 163–185.</p><p>[4] Palubad. (n.d.). <em>GitHub — palubad/Automatic-Forest-Classification-GEE: Supplementary material for the article “Automatic classification of forests using Sentinel-2 multispectral satellite data and machine learning methods in Google Earth Engine.”</em> GitHub. <a href="https://github.com/palubad/Automatic-Forest-Classification-GEE">https://github.com/palubad/Automatic-Forest-Classification-GEE</a></p><p>[5] <em>Sign-up for Google Earth engine</em>. (n.d.). <a href="https://courses.spatialthoughts.com/gee-sign-up.html">https://courses.spatialthoughts.com/gee-sign-up.html</a></p><p>[6] <em>USGS Landsat 9 Level 2, Collection 2, Tier 1</em>. (n.d.). Google for Developers. <a href="https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2">https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9392f6ca0736" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>